CuraEngineBackend.py 44 KB

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