CuraEngineBackend.py 39 KB

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