CuraEngineBackend.py 45 KB

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