CuraEngineBackend.py 46 KB

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