CuraEngineBackend.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import argparse #To run the engine in debug mode if the front-end is in debug mode.
  4. from collections import defaultdict
  5. import os
  6. from PyQt5.QtCore import QObject, QTimer, pyqtSlot
  7. import sys
  8. from time import time
  9. from typing import Any, cast, Dict, List, Optional, Set, TYPE_CHECKING
  10. from UM.Backend.Backend import Backend, BackendState
  11. from UM.Scene.SceneNode import SceneNode
  12. from UM.Signal import Signal
  13. from UM.Logger import Logger
  14. from UM.Message import Message
  15. from UM.PluginRegistry import PluginRegistry
  16. from UM.Platform import Platform
  17. from UM.Qt.Duration import DurationFormat
  18. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  19. from UM.Settings.Interfaces import DefinitionContainerInterface
  20. from UM.Settings.SettingInstance import SettingInstance #For typing.
  21. from UM.Tool import Tool #For typing.
  22. from cura.CuraApplication import CuraApplication
  23. from cura.Settings.ExtruderManager import ExtruderManager
  24. from .ProcessSlicedLayersJob import ProcessSlicedLayersJob
  25. from .StartSliceJob import StartSliceJob, StartJobResult
  26. import Arcus
  27. if TYPE_CHECKING:
  28. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  29. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  30. from UM.Scene.Scene import Scene
  31. from UM.Settings.ContainerStack import ContainerStack
  32. from UM.i18n import i18nCatalog
  33. catalog = i18nCatalog("cura")
  34. class CuraEngineBackend(QObject, Backend):
  35. backendError = Signal()
  36. ## Starts the back-end plug-in.
  37. #
  38. # This registers all the signal listeners and prepares for communication
  39. # with the back-end in general.
  40. # CuraEngineBackend is exposed to qml as well.
  41. def __init__(self) -> None:
  42. super().__init__()
  43. # Find out where the engine is located, and how it is called.
  44. # This depends on how Cura is packaged and which OS we are running on.
  45. executable_name = "CuraEngine"
  46. if Platform.isWindows():
  47. executable_name += ".exe"
  48. default_engine_location = executable_name
  49. if os.path.exists(os.path.join(CuraApplication.getInstallPrefix(), "bin", executable_name)):
  50. default_engine_location = os.path.join(CuraApplication.getInstallPrefix(), "bin", executable_name)
  51. if hasattr(sys, "frozen"):
  52. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), executable_name)
  53. if Platform.isLinux() and not default_engine_location:
  54. if not os.getenv("PATH"):
  55. raise OSError("There is something wrong with your Linux installation.")
  56. for pathdir in cast(str, os.getenv("PATH")).split(os.pathsep):
  57. execpath = os.path.join(pathdir, executable_name)
  58. if os.path.exists(execpath):
  59. default_engine_location = execpath
  60. break
  61. self._application = CuraApplication.getInstance() #type: CuraApplication
  62. self._multi_build_plate_model = None #type: Optional[MultiBuildPlateModel]
  63. self._machine_error_checker = None #type: Optional[MachineErrorChecker]
  64. if not default_engine_location:
  65. raise EnvironmentError("Could not find CuraEngine")
  66. Logger.log("i", "Found CuraEngine at: %s", default_engine_location)
  67. default_engine_location = os.path.abspath(default_engine_location)
  68. self._application.getPreferences().addPreference("backend/location", default_engine_location)
  69. # Workaround to disable layer view processing if layer view is not active.
  70. self._layer_view_active = False #type: bool
  71. self._onActiveViewChanged()
  72. self._stored_layer_data = [] # type: List[Arcus.PythonMessage]
  73. self._stored_optimized_layer_data = {} # type: Dict[int, List[Arcus.PythonMessage]] # key is build plate number, then arrays are stored until they go to the ProcessSlicesLayersJob
  74. self._scene = self._application.getController().getScene() #type: Scene
  75. self._scene.sceneChanged.connect(self._onSceneChanged)
  76. # Triggers for auto-slicing. Auto-slicing is triggered as follows:
  77. # - auto-slicing is started with a timer
  78. # - whenever there is a value change, we start the timer
  79. # - sometimes an error check can get scheduled for a value change, in that case, we ONLY want to start the
  80. # auto-slicing timer when that error check is finished
  81. # If there is an error check, stop the auto-slicing timer, and only wait for the error check to be finished
  82. # to start the auto-slicing timer again.
  83. #
  84. self._global_container_stack = None #type: Optional[ContainerStack]
  85. # Listeners for receiving messages from the back-end.
  86. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  87. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  88. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  89. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  90. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  91. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  92. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  93. self._start_slice_job = None #type: Optional[StartSliceJob]
  94. self._start_slice_job_build_plate = None #type: Optional[int]
  95. self._slicing = False #type: bool # Are we currently slicing?
  96. self._restart = False #type: bool # Back-end is currently restarting?
  97. self._tool_active = False #type: bool # If a tool is active, some tasks do not have to do anything
  98. self._always_restart = True #type: bool # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  99. self._process_layers_job = None #type: Optional[ProcessSlicedLayersJob] # The currently active job to process layers, or None if it is not processing layers.
  100. self._build_plates_to_be_sliced = [] #type: List[int] # what needs slicing?
  101. self._engine_is_fresh = True #type: bool # Is the newly started engine used before or not?
  102. self._backend_log_max_lines = 20000 #type: int # Maximum number of lines to buffer
  103. self._error_message = None #type: Optional[Message] # Pop-up message that shows errors.
  104. self._last_num_objects = defaultdict(int) #type: Dict[int, int] # Count number of objects to see if there is something changed
  105. self._postponed_scene_change_sources = [] #type: List[SceneNode] # scene change is postponed (by a tool)
  106. self._slice_start_time = None #type: Optional[float]
  107. self._is_disabled = False #type: bool
  108. self._application.getPreferences().addPreference("general/auto_slice", False)
  109. self._use_timer = False #type: bool
  110. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  111. # This timer will group them up, and only slice for the last setting changed signal.
  112. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  113. self._change_timer = QTimer() #type: QTimer
  114. self._change_timer.setSingleShot(True)
  115. self._change_timer.setInterval(500)
  116. self.determineAutoSlicing()
  117. self._application.getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  118. self._application.initializationFinished.connect(self.initialize)
  119. def initialize(self) -> None:
  120. self._multi_build_plate_model = self._application.getMultiBuildPlateModel()
  121. self._application.getController().activeViewChanged.connect(self._onActiveViewChanged)
  122. if self._multi_build_plate_model:
  123. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged)
  124. self._application.getMachineManager().globalContainerChanged.connect(self._onGlobalStackChanged)
  125. self._onGlobalStackChanged()
  126. # extruder enable / disable. Actually wanted to use machine manager here, but the initialization order causes it to crash
  127. ExtruderManager.getInstance().extrudersChanged.connect(self._extruderChanged)
  128. self.backendQuit.connect(self._onBackendQuit)
  129. self.backendConnected.connect(self._onBackendConnected)
  130. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  131. self._application.getController().toolOperationStarted.connect(self._onToolOperationStarted)
  132. self._application.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  133. self._machine_error_checker = self._application.getMachineErrorChecker()
  134. self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished)
  135. ## Terminate the engine process.
  136. #
  137. # This function should terminate the engine process.
  138. # Called when closing the application.
  139. def close(self) -> None:
  140. # Terminate CuraEngine if it is still running at this point
  141. self._terminate()
  142. ## Get the command that is used to call the engine.
  143. # This is useful for debugging and used to actually start the engine.
  144. # \return list of commands and args / parameters.
  145. def getEngineCommand(self) -> List[str]:
  146. command = [self._application.getPreferences().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), ""]
  147. parser = argparse.ArgumentParser(prog = "cura", add_help = False)
  148. parser.add_argument("--debug", action = "store_true", default = False, help = "Turn on the debug mode by setting this option.")
  149. known_args = vars(parser.parse_known_args()[0])
  150. if known_args["debug"]:
  151. command.append("-vvv")
  152. return command
  153. ## Emitted when we get a message containing print duration and material amount.
  154. # This also implies the slicing has finished.
  155. # \param time The amount of time the print will take.
  156. # \param material_amount The amount of material the print will use.
  157. printDurationMessage = Signal()
  158. ## Emitted when the slicing process starts.
  159. slicingStarted = Signal()
  160. ## Emitted when the slicing process is aborted forcefully.
  161. slicingCancelled = Signal()
  162. @pyqtSlot()
  163. def stopSlicing(self) -> None:
  164. self.setState(BackendState.NotStarted)
  165. if self._slicing: # We were already slicing. Stop the old job.
  166. self._terminate()
  167. self._createSocket()
  168. if self._process_layers_job is not None: # We were processing layers. Stop that, the layers are going to change soon.
  169. Logger.log("i", "Aborting process layers job...")
  170. self._process_layers_job.abort()
  171. self._process_layers_job = None
  172. if self._error_message:
  173. self._error_message.hide()
  174. ## Manually triggers a reslice
  175. @pyqtSlot()
  176. def forceSlice(self) -> None:
  177. self.markSliceAll()
  178. self.slice()
  179. ## Perform a slice of the scene.
  180. def slice(self) -> None:
  181. Logger.log("i", "Starting to slice...")
  182. self._slice_start_time = time()
  183. if not self._build_plates_to_be_sliced:
  184. self.processingProgress.emit(1.0)
  185. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  186. self.setState(BackendState.Done)
  187. return
  188. if self._process_layers_job:
  189. Logger.log("d", "Process layers job still busy, trying later.")
  190. return
  191. if not hasattr(self._scene, "gcode_dict"):
  192. self._scene.gcode_dict = {} #type: ignore #Because we are creating the missing attribute here.
  193. # see if we really have to slice
  194. active_build_plate = self._application.getMultiBuildPlateModel().activeBuildPlate
  195. build_plate_to_be_sliced = self._build_plates_to_be_sliced.pop(0)
  196. Logger.log("d", "Going to slice build plate [%s]!" % build_plate_to_be_sliced)
  197. num_objects = self._numObjectsPerBuildPlate()
  198. self._stored_layer_data = []
  199. if build_plate_to_be_sliced not in num_objects or num_objects[build_plate_to_be_sliced] == 0:
  200. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #Because we created this attribute above.
  201. Logger.log("d", "Build plate %s has no objects to be sliced, skipping", build_plate_to_be_sliced)
  202. if self._build_plates_to_be_sliced:
  203. self.slice()
  204. return
  205. self._stored_optimized_layer_data[build_plate_to_be_sliced] = []
  206. if self._application.getPrintInformation() and build_plate_to_be_sliced == active_build_plate:
  207. self._application.getPrintInformation().setToZeroPrintInformation(build_plate_to_be_sliced)
  208. if self._process is None: # type: ignore
  209. self._createSocket()
  210. self.stopSlicing()
  211. self._engine_is_fresh = False # Yes we're going to use the engine
  212. self.processingProgress.emit(0.0)
  213. self.backendStateChange.emit(BackendState.NotStarted)
  214. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #[] indexed by build plate number
  215. self._slicing = True
  216. self.slicingStarted.emit()
  217. self.determineAutoSlicing() # Switch timer on or off if appropriate
  218. slice_message = self._socket.createMessage("cura.proto.Slice")
  219. self._start_slice_job = StartSliceJob(slice_message)
  220. self._start_slice_job_build_plate = build_plate_to_be_sliced
  221. self._start_slice_job.setBuildPlate(self._start_slice_job_build_plate)
  222. self._start_slice_job.start()
  223. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  224. ## Terminate the engine process.
  225. # Start the engine process by calling _createSocket()
  226. def _terminate(self) -> None:
  227. self._slicing = False
  228. self._stored_layer_data = []
  229. if self._start_slice_job_build_plate in self._stored_optimized_layer_data:
  230. del self._stored_optimized_layer_data[self._start_slice_job_build_plate]
  231. if self._start_slice_job is not None:
  232. self._start_slice_job.cancel()
  233. self.slicingCancelled.emit()
  234. self.processingProgress.emit(0)
  235. Logger.log("d", "Attempting to kill the engine process")
  236. if self._application.getUseExternalBackend():
  237. return
  238. if self._process is not None: # type: ignore
  239. Logger.log("d", "Killing engine process")
  240. try:
  241. self._process.terminate() # type: ignore
  242. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait()) # type: ignore
  243. self._process = None # type: ignore
  244. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  245. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  246. ## Event handler to call when the job to initiate the slicing process is
  247. # completed.
  248. #
  249. # When the start slice job is successfully completed, it will be happily
  250. # slicing. This function handles any errors that may occur during the
  251. # bootstrapping of a slice job.
  252. #
  253. # \param job The start slice job that was just finished.
  254. def _onStartSliceCompleted(self, job: StartSliceJob) -> None:
  255. if self._error_message:
  256. self._error_message.hide()
  257. # Note that cancelled slice jobs can still call this method.
  258. if self._start_slice_job is job:
  259. self._start_slice_job = None
  260. if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error:
  261. self.setState(BackendState.Error)
  262. self.backendError.emit(job)
  263. return
  264. if job.getResult() == StartJobResult.MaterialIncompatible:
  265. if self._application.platformActivity:
  266. self._error_message = Message(catalog.i18nc("@info:status",
  267. "Unable to slice with the current material as it is incompatible with the selected machine or configuration."), title = catalog.i18nc("@info:title", "Unable to slice"))
  268. self._error_message.show()
  269. self.setState(BackendState.Error)
  270. self.backendError.emit(job)
  271. else:
  272. self.setState(BackendState.NotStarted)
  273. return
  274. if job.getResult() == StartJobResult.SettingError:
  275. if self._application.platformActivity:
  276. if not self._global_container_stack:
  277. Logger.log("w", "Global container stack not assigned to CuraEngineBackend!")
  278. return
  279. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  280. error_keys = [] #type: List[str]
  281. for extruder in extruders:
  282. error_keys.extend(extruder.getErrorKeys())
  283. if not extruders:
  284. error_keys = self._global_container_stack.getErrorKeys()
  285. error_labels = set()
  286. for key in error_keys:
  287. for stack in [self._global_container_stack] + extruders: #Search all container stacks for the definition of this setting. Some are only in an extruder stack.
  288. definitions = cast(DefinitionContainerInterface, stack.getBottom()).findDefinitions(key = key)
  289. if definitions:
  290. break #Found it! No need to continue search.
  291. else: #No stack has a definition for this setting.
  292. Logger.log("w", "When checking settings for errors, unable to find definition for key: {key}".format(key = key))
  293. continue
  294. error_labels.add(definitions[0].label)
  295. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}").format(", ".join(error_labels)),
  296. title = catalog.i18nc("@info:title", "Unable to slice"))
  297. self._error_message.show()
  298. self.setState(BackendState.Error)
  299. self.backendError.emit(job)
  300. else:
  301. self.setState(BackendState.NotStarted)
  302. return
  303. elif job.getResult() == StartJobResult.ObjectSettingError:
  304. errors = {}
  305. for node in DepthFirstIterator(self._application.getController().getScene().getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  306. stack = node.callDecoration("getStack")
  307. if not stack:
  308. continue
  309. for key in stack.getErrorKeys():
  310. if not self._global_container_stack:
  311. Logger.log("e", "CuraEngineBackend does not have global_container_stack assigned.")
  312. continue
  313. definition = cast(DefinitionContainerInterface, self._global_container_stack.getBottom()).findDefinitions(key = key)
  314. if not definition:
  315. Logger.log("e", "When checking settings for errors, unable to find definition for key {key} in per-object stack.".format(key = key))
  316. continue
  317. errors[key] = definition[0].label
  318. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice due to some per-model settings. The following settings have errors on one or more models: {error_labels}").format(error_labels = ", ".join(errors.values())),
  319. title = catalog.i18nc("@info:title", "Unable to slice"))
  320. self._error_message.show()
  321. self.setState(BackendState.Error)
  322. self.backendError.emit(job)
  323. return
  324. if job.getResult() == StartJobResult.BuildPlateError:
  325. if self._application.platformActivity:
  326. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."),
  327. title = catalog.i18nc("@info:title", "Unable to slice"))
  328. self._error_message.show()
  329. self.setState(BackendState.Error)
  330. self.backendError.emit(job)
  331. else:
  332. self.setState(BackendState.NotStarted)
  333. if job.getResult() == StartJobResult.ObjectsWithDisabledExtruder:
  334. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because there are objects associated with disabled Extruder %s." % job.getMessage()),
  335. title = catalog.i18nc("@info:title", "Unable to slice"))
  336. self._error_message.show()
  337. self.setState(BackendState.Error)
  338. self.backendError.emit(job)
  339. return
  340. if job.getResult() == StartJobResult.NothingToSlice:
  341. if self._application.platformActivity:
  342. self._error_message = Message(catalog.i18nc("@info:status", "Nothing to slice because none of the models fit the build volume or are assigned to a disabled extruder. Please scale or rotate models to fit, or enable an extruder."),
  343. title = catalog.i18nc("@info:title", "Unable to slice"))
  344. self._error_message.show()
  345. self.setState(BackendState.Error)
  346. self.backendError.emit(job)
  347. else:
  348. self.setState(BackendState.NotStarted)
  349. self._invokeSlice()
  350. return
  351. # Preparation completed, send it to the backend.
  352. self._socket.sendMessage(job.getSliceMessage())
  353. # Notify the user that it's now up to the backend to do it's job
  354. self.setState(BackendState.Processing)
  355. if self._slice_start_time:
  356. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  357. ## Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  358. # It disables when
  359. # - preference auto slice is off
  360. # - decorator isBlockSlicing is found (used in g-code reader)
  361. def determineAutoSlicing(self) -> bool:
  362. enable_timer = True
  363. self._is_disabled = False
  364. if not self._application.getPreferences().getValue("general/auto_slice"):
  365. enable_timer = False
  366. for node in DepthFirstIterator(self._scene.getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  367. if node.callDecoration("isBlockSlicing"):
  368. enable_timer = False
  369. self.setState(BackendState.Disabled)
  370. self._is_disabled = True
  371. gcode_list = node.callDecoration("getGCodeList")
  372. if gcode_list is not None:
  373. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list #type: ignore #Because we generate this attribute dynamically.
  374. if self._use_timer == enable_timer:
  375. return self._use_timer
  376. if enable_timer:
  377. self.setState(BackendState.NotStarted)
  378. self.enableTimer()
  379. return True
  380. else:
  381. self.disableTimer()
  382. return False
  383. ## Return a dict with number of objects per build plate
  384. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  385. num_objects = defaultdict(int) #type: Dict[int, int]
  386. for node in DepthFirstIterator(self._scene.getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  387. # Only count sliceable objects
  388. if node.callDecoration("isSliceable"):
  389. build_plate_number = node.callDecoration("getBuildPlateNumber")
  390. if build_plate_number is not None:
  391. num_objects[build_plate_number] += 1
  392. return num_objects
  393. ## Listener for when the scene has changed.
  394. #
  395. # This should start a slice if the scene is now ready to slice.
  396. #
  397. # \param source The scene node that was changed.
  398. def _onSceneChanged(self, source: SceneNode) -> None:
  399. if not source.callDecoration("isSliceable"):
  400. return
  401. # This case checks if the source node is a node that contains GCode. In this case the
  402. # current layer data is removed so the previous data is not rendered - CURA-4821
  403. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  404. self._stored_optimized_layer_data = {}
  405. build_plate_changed = set()
  406. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  407. if source == self._scene.getRoot():
  408. # we got the root node
  409. num_objects = self._numObjectsPerBuildPlate()
  410. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  411. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  412. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  413. build_plate_changed.add(build_plate_number)
  414. else:
  415. # we got a single scenenode
  416. if not source.callDecoration("isGroup"):
  417. mesh_data = source.getMeshData()
  418. if mesh_data is None or mesh_data.getVertices() is None:
  419. return
  420. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  421. if source_build_plate_number is not None:
  422. build_plate_changed.add(source_build_plate_number)
  423. if not build_plate_changed:
  424. return
  425. if self._tool_active:
  426. # do it later, each source only has to be done once
  427. if source not in self._postponed_scene_change_sources:
  428. self._postponed_scene_change_sources.append(source)
  429. return
  430. self.stopSlicing()
  431. for build_plate_number in build_plate_changed:
  432. if build_plate_number not in self._build_plates_to_be_sliced:
  433. self._build_plates_to_be_sliced.append(build_plate_number)
  434. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  435. self.processingProgress.emit(0.0)
  436. self._clearLayerData(build_plate_changed)
  437. self._invokeSlice()
  438. ## Called when an error occurs in the socket connection towards the engine.
  439. #
  440. # \param error The exception that occurred.
  441. def _onSocketError(self, error: Arcus.Error) -> None:
  442. if self._application.isShuttingDown():
  443. return
  444. super()._onSocketError(error)
  445. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  446. return
  447. self._terminate()
  448. self._createSocket()
  449. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  450. Logger.log("w", "A socket error caused the connection to be reset")
  451. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  452. # needs to be updated. Otherwise backendState is "Unable To Slice"
  453. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  454. self._start_slice_job.setIsCancelled(False)
  455. ## Remove old layer data (if any)
  456. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  457. # Clear out any old gcode
  458. self._scene.gcode_dict = {} # type: ignore
  459. for node in DepthFirstIterator(self._scene.getRoot()): #type: ignore #Ignore type error because iter() should get called automatically by Python syntax.
  460. if node.callDecoration("getLayerData"):
  461. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  462. node.getParent().removeChild(node)
  463. def markSliceAll(self) -> None:
  464. for build_plate_number in range(self._application.getMultiBuildPlateModel().maxBuildPlate + 1):
  465. if build_plate_number not in self._build_plates_to_be_sliced:
  466. self._build_plates_to_be_sliced.append(build_plate_number)
  467. ## Convenient function: mark everything to slice, emit state and clear layer data
  468. def needsSlicing(self) -> None:
  469. self.determineAutoSlicing()
  470. self.stopSlicing()
  471. self.markSliceAll()
  472. self.processingProgress.emit(0.0)
  473. if not self._use_timer:
  474. # With manually having to slice, we want to clear the old invalid layer data.
  475. self._clearLayerData()
  476. ## A setting has changed, so check if we must reslice.
  477. # \param instance The setting instance that has changed.
  478. # \param property The property of the setting instance that has changed.
  479. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  480. if property == "value": # Only reslice if the value has changed.
  481. self.needsSlicing()
  482. self._onChanged()
  483. elif property == "validationState":
  484. if self._use_timer:
  485. self._change_timer.stop()
  486. def _onStackErrorCheckFinished(self) -> None:
  487. self.determineAutoSlicing()
  488. if self._is_disabled:
  489. return
  490. if not self._slicing and self._build_plates_to_be_sliced:
  491. self.needsSlicing()
  492. self._onChanged()
  493. ## Called when a sliced layer data message is received from the engine.
  494. #
  495. # \param message The protobuf message containing sliced layer data.
  496. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  497. self._stored_layer_data.append(message)
  498. ## Called when an optimized sliced layer data message is received from the engine.
  499. #
  500. # \param message The protobuf message containing sliced layer data.
  501. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  502. if self._start_slice_job_build_plate is not None:
  503. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  504. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  505. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  506. ## Called when a progress message is received from the engine.
  507. #
  508. # \param message The protobuf message containing the slicing progress.
  509. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  510. self.processingProgress.emit(message.amount)
  511. self.setState(BackendState.Processing)
  512. def _invokeSlice(self) -> None:
  513. if self._use_timer:
  514. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  515. # otherwise business as usual
  516. if self._machine_error_checker is None:
  517. self._change_timer.stop()
  518. return
  519. if self._machine_error_checker.needToWaitForResult:
  520. self._change_timer.stop()
  521. else:
  522. self._change_timer.start()
  523. ## Called when the engine sends a message that slicing is finished.
  524. #
  525. # \param message The protobuf message signalling that slicing is finished.
  526. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  527. self.setState(BackendState.Done)
  528. self.processingProgress.emit(1.0)
  529. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore #Because we generate this attribute dynamically.
  530. for index, line in enumerate(gcode_list):
  531. replaced = line.replace("{print_time}", str(self._application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  532. replaced = replaced.replace("{filament_amount}", str(self._application.getPrintInformation().materialLengths))
  533. replaced = replaced.replace("{filament_weight}", str(self._application.getPrintInformation().materialWeights))
  534. replaced = replaced.replace("{filament_cost}", str(self._application.getPrintInformation().materialCosts))
  535. replaced = replaced.replace("{jobname}", str(self._application.getPrintInformation().jobName))
  536. gcode_list[index] = replaced
  537. self._slicing = False
  538. if self._slice_start_time:
  539. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  540. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  541. # See if we need to process the sliced layers job.
  542. active_build_plate = self._application.getMultiBuildPlateModel().activeBuildPlate
  543. if (
  544. self._layer_view_active and
  545. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  546. active_build_plate == self._start_slice_job_build_plate and
  547. active_build_plate not in self._build_plates_to_be_sliced):
  548. self._startProcessSlicedLayersJob(active_build_plate)
  549. # self._onActiveViewChanged()
  550. self._start_slice_job_build_plate = None
  551. Logger.log("d", "See if there is more to slice...")
  552. # Somehow this results in an Arcus Error
  553. # self.slice()
  554. # Call slice again using the timer, allowing the backend to restart
  555. if self._build_plates_to_be_sliced:
  556. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  557. self._invokeSlice()
  558. ## Called when a g-code message is received from the engine.
  559. #
  560. # \param message The protobuf message containing g-code, encoded as UTF-8.
  561. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  562. self._scene.gcode_dict[self._start_slice_job_build_plate].append(message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  563. ## Called when a g-code prefix message is received from the engine.
  564. #
  565. # \param message The protobuf message containing the g-code prefix,
  566. # encoded as UTF-8.
  567. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  568. self._scene.gcode_dict[self._start_slice_job_build_plate].insert(0, message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  569. ## Creates a new socket connection.
  570. def _createSocket(self, protocol_file: str = None) -> None:
  571. if not protocol_file:
  572. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  573. if not plugin_path:
  574. Logger.log("e", "Could not get plugin path!", self.getPluginId())
  575. return
  576. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  577. super()._createSocket(protocol_file)
  578. self._engine_is_fresh = True
  579. ## Called when anything has changed to the stuff that needs to be sliced.
  580. #
  581. # This indicates that we should probably re-slice soon.
  582. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  583. self.needsSlicing()
  584. if self._use_timer:
  585. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  586. # otherwise business as usual
  587. if self._machine_error_checker is None:
  588. self._change_timer.stop()
  589. return
  590. if self._machine_error_checker.needToWaitForResult:
  591. self._change_timer.stop()
  592. else:
  593. self._change_timer.start()
  594. ## Called when a print time message is received from the engine.
  595. #
  596. # \param message The protobuf message containing the print time per feature and
  597. # material amount per extruder
  598. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  599. material_amounts = []
  600. for index in range(message.repeatedMessageCount("materialEstimates")):
  601. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  602. times = self._parseMessagePrintTimes(message)
  603. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  604. ## Called for parsing message to retrieve estimated time per feature
  605. #
  606. # \param message The protobuf message containing the print time per feature
  607. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  608. result = {
  609. "inset_0": message.time_inset_0,
  610. "inset_x": message.time_inset_x,
  611. "skin": message.time_skin,
  612. "infill": message.time_infill,
  613. "support_infill": message.time_support_infill,
  614. "support_interface": message.time_support_interface,
  615. "support": message.time_support,
  616. "skirt": message.time_skirt,
  617. "prime_tower": message.time_prime_tower,
  618. "travel": message.time_travel,
  619. "retract": message.time_retract,
  620. "none": message.time_none
  621. }
  622. return result
  623. ## Called when the back-end connects to the front-end.
  624. def _onBackendConnected(self) -> None:
  625. if self._restart:
  626. self._restart = False
  627. self._onChanged()
  628. ## Called when the user starts using some tool.
  629. #
  630. # When the user starts using a tool, we should pause slicing to prevent
  631. # continuously slicing while the user is dragging some tool handle.
  632. #
  633. # \param tool The tool that the user is using.
  634. def _onToolOperationStarted(self, tool: Tool) -> None:
  635. self._tool_active = True # Do not react on scene change
  636. self.disableTimer()
  637. # Restart engine as soon as possible, we know we want to slice afterwards
  638. if not self._engine_is_fresh:
  639. self._terminate()
  640. self._createSocket()
  641. ## Called when the user stops using some tool.
  642. #
  643. # This indicates that we can safely start slicing again.
  644. #
  645. # \param tool The tool that the user was using.
  646. def _onToolOperationStopped(self, tool: Tool) -> None:
  647. self._tool_active = False # React on scene change again
  648. self.determineAutoSlicing() # Switch timer on if appropriate
  649. # Process all the postponed scene changes
  650. while self._postponed_scene_change_sources:
  651. source = self._postponed_scene_change_sources.pop(0)
  652. self._onSceneChanged(source)
  653. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  654. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  655. self._process_layers_job.setBuildPlate(build_plate_number)
  656. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  657. self._process_layers_job.start()
  658. ## Called when the user changes the active view mode.
  659. def _onActiveViewChanged(self) -> None:
  660. view = self._application.getController().getActiveView()
  661. if view:
  662. active_build_plate = self._application.getMultiBuildPlateModel().activeBuildPlate
  663. if view.getPluginId() == "SimulationView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  664. self._layer_view_active = True
  665. # There is data and we're not slicing at the moment
  666. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  667. # TODO: what build plate I am slicing
  668. if (active_build_plate in self._stored_optimized_layer_data and
  669. not self._slicing and
  670. not self._process_layers_job and
  671. active_build_plate not in self._build_plates_to_be_sliced):
  672. self._startProcessSlicedLayersJob(active_build_plate)
  673. else:
  674. self._layer_view_active = False
  675. ## Called when the back-end self-terminates.
  676. #
  677. # We should reset our state and start listening for new connections.
  678. def _onBackendQuit(self) -> None:
  679. if not self._restart:
  680. if self._process: # type: ignore
  681. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait()) # type: ignore
  682. self._process = None # type: ignore
  683. ## Called when the global container stack changes
  684. def _onGlobalStackChanged(self) -> None:
  685. if self._global_container_stack:
  686. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  687. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  688. extruders = list(self._global_container_stack.extruders.values())
  689. for extruder in extruders:
  690. extruder.propertyChanged.disconnect(self._onSettingChanged)
  691. extruder.containersChanged.disconnect(self._onChanged)
  692. self._global_container_stack = self._application.getMachineManager().activeMachine
  693. if self._global_container_stack:
  694. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  695. self._global_container_stack.containersChanged.connect(self._onChanged)
  696. extruders = list(self._global_container_stack.extruders.values())
  697. for extruder in extruders:
  698. extruder.propertyChanged.connect(self._onSettingChanged)
  699. extruder.containersChanged.connect(self._onChanged)
  700. self._onChanged()
  701. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  702. if job.getBuildPlate() in self._stored_optimized_layer_data:
  703. del self._stored_optimized_layer_data[job.getBuildPlate()]
  704. else:
  705. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  706. self._process_layers_job = None
  707. Logger.log("d", "See if there is more to slice(2)...")
  708. self._invokeSlice()
  709. ## Connect slice function to timer.
  710. def enableTimer(self) -> None:
  711. if not self._use_timer:
  712. self._change_timer.timeout.connect(self.slice)
  713. self._use_timer = True
  714. ## Disconnect slice function from timer.
  715. # This means that slicing will not be triggered automatically
  716. def disableTimer(self) -> None:
  717. if self._use_timer:
  718. self._use_timer = False
  719. self._change_timer.timeout.disconnect(self.slice)
  720. def _onPreferencesChanged(self, preference: str) -> None:
  721. if preference != "general/auto_slice":
  722. return
  723. auto_slice = self.determineAutoSlicing()
  724. if auto_slice:
  725. self._change_timer.start()
  726. ## Tickle the backend so in case of auto slicing, it starts the timer.
  727. def tickle(self) -> None:
  728. if self._use_timer:
  729. self._change_timer.start()
  730. def _extruderChanged(self) -> None:
  731. if not self._multi_build_plate_model:
  732. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  733. return
  734. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  735. if build_plate_number not in self._build_plates_to_be_sliced:
  736. self._build_plates_to_be_sliced.append(build_plate_number)
  737. self._invokeSlice()