CuraEngineBackend.py 39 KB

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