CuraEngineBackend.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # Copyright (c) 2015 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 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.Settings.Validator import ValidatorState #To find if a setting is in an error state. We can't slice then.
  13. from UM.Platform import Platform
  14. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  15. import cura.Settings
  16. from cura.OneAtATimeIterator import OneAtATimeIterator
  17. from cura.Settings.ExtruderManager import ExtruderManager
  18. from . import ProcessSlicedLayersJob
  19. from . import ProcessGCodeJob
  20. from . import StartSliceJob
  21. import os
  22. import sys
  23. from time import time
  24. from PyQt5.QtCore import QTimer
  25. import Arcus
  26. from UM.i18n import i18nCatalog
  27. catalog = i18nCatalog("cura")
  28. class CuraEngineBackend(Backend):
  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. def __init__(self):
  34. super().__init__()
  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. if not default_engine_location:
  54. raise EnvironmentError("Could not find CuraEngine")
  55. Logger.log("i", "Found CuraEngine at: %s" %(default_engine_location))
  56. default_engine_location = os.path.abspath(default_engine_location)
  57. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  58. self._scene = Application.getInstance().getController().getScene()
  59. self._scene.sceneChanged.connect(self._onSceneChanged)
  60. self._pause_slicing = False
  61. self._block_slicing = False # continueSlicing does not have effect if True
  62. # Workaround to disable layer view processing if layer view is not active.
  63. self._layer_view_active = False
  64. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  65. self._onActiveViewChanged()
  66. self._stored_layer_data = []
  67. self._stored_optimized_layer_data = []
  68. # Triggers for when to (re)start slicing:
  69. self._global_container_stack = None
  70. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  71. self._onGlobalStackChanged()
  72. self._active_extruder_stack = None
  73. cura.Settings.ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
  74. self._onActiveExtruderChanged()
  75. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  76. # This timer will group them up, and only slice for the last setting changed signal.
  77. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  78. self._change_timer = QTimer()
  79. self._change_timer.setInterval(500)
  80. self._change_timer.setSingleShot(True)
  81. self._change_timer.timeout.connect(self.slice)
  82. # Listeners for receiving messages from the back-end.
  83. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  84. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  85. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  86. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  87. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  88. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  89. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  90. self._start_slice_job = None
  91. self._slicing = False # Are we currently slicing?
  92. self._restart = False # Back-end is currently restarting?
  93. self._enabled = True # Should we be slicing? Slicing might be paused when, for instance, the user is dragging the mesh around.
  94. self._always_restart = True # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  95. self._process_layers_job = None # The currently active job to process layers, or None if it is not processing layers.
  96. self._backend_log_max_lines = 20000 # Maximum number of lines to buffer
  97. self._error_message = None # Pop-up message that shows errors.
  98. self.backendQuit.connect(self._onBackendQuit)
  99. self.backendConnected.connect(self._onBackendConnected)
  100. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  101. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  102. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  103. self._slice_start_time = None
  104. ## Called when closing the application.
  105. #
  106. # This function should terminate the engine process.
  107. def close(self):
  108. # Terminate CuraEngine if it is still running at this point
  109. self._terminate()
  110. ## Get the command that is used to call the engine.
  111. # This is useful for debugging and used to actually start the engine.
  112. # \return list of commands and args / parameters.
  113. def getEngineCommand(self):
  114. json_path = Resources.getPath(Resources.DefinitionContainers, "fdmprinter.def.json")
  115. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, ""]
  116. ## Emitted when we get a message containing print duration and material amount.
  117. # This also implies the slicing has finished.
  118. # \param time The amount of time the print will take.
  119. # \param material_amount The amount of material the print will use.
  120. printDurationMessage = Signal()
  121. ## Emitted when the slicing process starts.
  122. slicingStarted = Signal()
  123. ## Emitted when the slicing process is aborted forcefully.
  124. slicingCancelled = Signal()
  125. ## Perform a slice of the scene.
  126. def slice(self):
  127. Logger.log("d", "Starting slice job...")
  128. if self._pause_slicing or self._block_slicing:
  129. return
  130. self._slice_start_time = time()
  131. if not self._enabled or not self._global_container_stack: # We shouldn't be slicing.
  132. # try again in a short time
  133. self._change_timer.start()
  134. return
  135. self.printDurationMessage.emit(0, [0])
  136. self._stored_layer_data = []
  137. self._stored_optimized_layer_data = []
  138. if self._slicing: # We were already slicing. Stop the old job.
  139. self._terminate()
  140. if self._process_layers_job: # We were processing layers. Stop that, the layers are going to change soon.
  141. self._process_layers_job.abort()
  142. self._process_layers_job = None
  143. if self._error_message:
  144. self._error_message.hide()
  145. self.processingProgress.emit(0.0)
  146. self.backendStateChange.emit(BackendState.NotStarted)
  147. self._scene.gcode_list = []
  148. self._slicing = True
  149. self.slicingStarted.emit()
  150. slice_message = self._socket.createMessage("cura.proto.Slice")
  151. self._start_slice_job = StartSliceJob.StartSliceJob(slice_message)
  152. self._start_slice_job.start()
  153. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  154. def pauseSlicing(self):
  155. self.close()
  156. self._pause_slicing = True
  157. self.backendStateChange.emit(BackendState.Disabled)
  158. def continueSlicing(self):
  159. if self._pause_slicing and not self._block_slicing:
  160. self._pause_slicing = False
  161. self.backendStateChange.emit(BackendState.NotStarted)
  162. ## Terminate the engine process.
  163. def _terminate(self):
  164. self._slicing = False
  165. self._restart = True
  166. self._stored_layer_data = []
  167. self._stored_optimized_layer_data = []
  168. if self._start_slice_job is not None:
  169. self._start_slice_job.cancel()
  170. self.slicingCancelled.emit()
  171. self.processingProgress.emit(0)
  172. Logger.log("d", "Attempting to kill the engine process")
  173. if Application.getInstance().getCommandLineOption("external-backend", False):
  174. return
  175. if self._process is not None:
  176. Logger.log("d", "Killing engine process")
  177. try:
  178. self._process.terminate()
  179. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  180. self._process = None
  181. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  182. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  183. else:
  184. # Process is none, but something did went wrong here. Try and re-create the socket
  185. self._createSocket()
  186. ## Event handler to call when the job to initiate the slicing process is
  187. # completed.
  188. #
  189. # When the start slice job is successfully completed, it will be happily
  190. # slicing. This function handles any errors that may occur during the
  191. # bootstrapping of a slice job.
  192. #
  193. # \param job The start slice job that was just finished.
  194. def _onStartSliceCompleted(self, job):
  195. if self._error_message:
  196. self._error_message.hide()
  197. # Note that cancelled slice jobs can still call this method.
  198. if self._start_slice_job is job:
  199. self._start_slice_job = None
  200. if job.isCancelled() or job.getError() or job.getResult() == StartSliceJob.StartJobResult.Error:
  201. return
  202. if job.getResult() == StartSliceJob.StartJobResult.MaterialIncompatible:
  203. if Application.getInstance().getPlatformActivity:
  204. self._error_message = Message(catalog.i18nc("@info:status",
  205. "The selected material is incompatible with the selected machine or configuration."))
  206. self._error_message.show()
  207. self.backendStateChange.emit(BackendState.Error)
  208. else:
  209. self.backendStateChange.emit(BackendState.NotStarted)
  210. return
  211. if job.getResult() == StartSliceJob.StartJobResult.SettingError:
  212. if Application.getInstance().getPlatformActivity:
  213. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  214. error_keys = []
  215. for extruder in extruders:
  216. error_keys.extend(extruder.getErrorKeys())
  217. if not extruders:
  218. error_keys = self._global_container_stack.getErrorKeys()
  219. error_labels = set()
  220. definition_container = self._global_container_stack.getBottom()
  221. for key in error_keys:
  222. error_labels.add(definition_container.findDefinitions(key = key)[0].label)
  223. error_labels = ", ".join(error_labels)
  224. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice with the current settings. The following settings have errors: {0}".format(error_labels)))
  225. self._error_message.show()
  226. self.backendStateChange.emit(BackendState.Error)
  227. else:
  228. self.backendStateChange.emit(BackendState.NotStarted)
  229. return
  230. if job.getResult() == StartSliceJob.StartJobResult.BuildPlateError:
  231. if Application.getInstance().getPlatformActivity:
  232. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice because the prime tower or prime position(s) are invalid."))
  233. self._error_message.show()
  234. self.backendStateChange.emit(BackendState.Error)
  235. else:
  236. self.backendStateChange.emit(BackendState.NotStarted)
  237. if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
  238. if Application.getInstance().getPlatformActivity:
  239. 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."))
  240. self._error_message.show()
  241. self.backendStateChange.emit(BackendState.Error)
  242. else:
  243. self.backendStateChange.emit(BackendState.NotStarted)
  244. return
  245. # Preparation completed, send it to the backend.
  246. self._socket.sendMessage(job.getSliceMessage())
  247. # Notify the user that it's now up to the backend to do it's job
  248. self.backendStateChange.emit(BackendState.Processing)
  249. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  250. ## Listener for when the scene has changed.
  251. #
  252. # This should start a slice if the scene is now ready to slice.
  253. #
  254. # \param source The scene node that was changed.
  255. def _onSceneChanged(self, source):
  256. if type(source) is not SceneNode:
  257. return
  258. if source is self._scene.getRoot():
  259. return
  260. should_pause = self._pause_slicing
  261. block_slicing = False
  262. for node in DepthFirstIterator(self._scene.getRoot()):
  263. if node.callDecoration("isBlockSlicing"):
  264. should_pause = True
  265. block_slicing = True
  266. gcode_list = node.callDecoration("getGCodeList")
  267. if gcode_list is not None:
  268. self._scene.gcode_list = gcode_list
  269. self._block_slicing = block_slicing
  270. if should_pause and self._block_slicing:
  271. self.pauseSlicing()
  272. else:
  273. self.continueSlicing()
  274. if source.getMeshData() is None:
  275. return
  276. if source.getMeshData().getVertices() is None:
  277. return
  278. self._onChanged()
  279. ## Called when an error occurs in the socket connection towards the engine.
  280. #
  281. # \param error The exception that occurred.
  282. def _onSocketError(self, error):
  283. if Application.getInstance().isShuttingDown():
  284. return
  285. super()._onSocketError(error)
  286. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  287. return
  288. self._terminate()
  289. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  290. Logger.log("w", "A socket error caused the connection to be reset")
  291. ## A setting has changed, so check if we must reslice.
  292. #
  293. # \param instance The setting instance that has changed.
  294. # \param property The property of the setting instance that has changed.
  295. def _onSettingChanged(self, instance, property):
  296. if property == "value": # Only reslice if the value has changed.
  297. self._onChanged()
  298. ## Called when a sliced layer data message is received from the engine.
  299. #
  300. # \param message The protobuf message containing sliced layer data.
  301. def _onLayerMessage(self, message):
  302. self._stored_layer_data.append(message)
  303. ## Called when an optimized sliced layer data message is received from the engine.
  304. #
  305. # \param message The protobuf message containing sliced layer data.
  306. def _onOptimizedLayerMessage(self, message):
  307. self._stored_optimized_layer_data.append(message)
  308. ## Called when a progress message is received from the engine.
  309. #
  310. # \param message The protobuf message containing the slicing progress.
  311. def _onProgressMessage(self, message):
  312. self.processingProgress.emit(message.amount)
  313. self.backendStateChange.emit(BackendState.Processing)
  314. ## Called when the engine sends a message that slicing is finished.
  315. #
  316. # \param message The protobuf message signalling that slicing is finished.
  317. def _onSlicingFinishedMessage(self, message):
  318. self.backendStateChange.emit(BackendState.Done)
  319. self.processingProgress.emit(1.0)
  320. self._slicing = False
  321. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  322. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  323. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  324. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  325. self._process_layers_job.start()
  326. self._stored_optimized_layer_data = []
  327. ## Called when a g-code message is received from the engine.
  328. #
  329. # \param message The protobuf message containing g-code, encoded as UTF-8.
  330. def _onGCodeLayerMessage(self, message):
  331. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  332. ## Called when a g-code prefix message is received from the engine.
  333. #
  334. # \param message The protobuf message containing the g-code prefix,
  335. # encoded as UTF-8.
  336. def _onGCodePrefixMessage(self, message):
  337. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  338. ## Called when a print time message is received from the engine.
  339. #
  340. # \param message The protobuff message containing the print time and
  341. # material amount per extruder
  342. def _onPrintTimeMaterialEstimates(self, message):
  343. material_amounts = []
  344. for index in range(message.repeatedMessageCount("materialEstimates")):
  345. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  346. self.printDurationMessage.emit(message.time, material_amounts)
  347. ## Creates a new socket connection.
  348. def _createSocket(self):
  349. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  350. ## Manually triggers a reslice
  351. def forceSlice(self):
  352. self._change_timer.start()
  353. ## Called when anything has changed to the stuff that needs to be sliced.
  354. #
  355. # This indicates that we should probably re-slice soon.
  356. def _onChanged(self, *args, **kwargs):
  357. self._change_timer.start()
  358. ## Called when the back-end connects to the front-end.
  359. def _onBackendConnected(self):
  360. if self._restart:
  361. self._onChanged()
  362. self._restart = False
  363. ## Called when the user starts using some tool.
  364. #
  365. # When the user starts using a tool, we should pause slicing to prevent
  366. # continuously slicing while the user is dragging some tool handle.
  367. #
  368. # \param tool The tool that the user is using.
  369. def _onToolOperationStarted(self, tool):
  370. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  371. self._terminate() # Do not continue slicing once a tool has started
  372. ## Called when the user stops using some tool.
  373. #
  374. # This indicates that we can safely start slicing again.
  375. #
  376. # \param tool The tool that the user was using.
  377. def _onToolOperationStopped(self, tool):
  378. self._enabled = True # Tool stop, start listening for changes again.
  379. ## Called when the user changes the active view mode.
  380. def _onActiveViewChanged(self):
  381. if Application.getInstance().getController().getActiveView():
  382. view = Application.getInstance().getController().getActiveView()
  383. if view.getPluginId() == "LayerView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  384. self._layer_view_active = True
  385. # There is data and we're not slicing at the moment
  386. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  387. if self._stored_optimized_layer_data and not self._slicing:
  388. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_optimized_layer_data)
  389. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  390. self._process_layers_job.start()
  391. self._stored_optimized_layer_data = []
  392. else:
  393. self._layer_view_active = False
  394. ## Called when the back-end self-terminates.
  395. #
  396. # We should reset our state and start listening for new connections.
  397. def _onBackendQuit(self):
  398. if not self._restart:
  399. if self._process:
  400. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  401. self._process = None
  402. self._createSocket()
  403. ## Called when the global container stack changes
  404. def _onGlobalStackChanged(self):
  405. if self._global_container_stack:
  406. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  407. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  408. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  409. if extruders:
  410. for extruder in extruders:
  411. extruder.propertyChanged.disconnect(self._onSettingChanged)
  412. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  413. if self._global_container_stack:
  414. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  415. self._global_container_stack.containersChanged.connect(self._onChanged)
  416. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  417. if extruders:
  418. for extruder in extruders:
  419. extruder.propertyChanged.connect(self._onSettingChanged)
  420. self._onActiveExtruderChanged()
  421. self._onChanged()
  422. def _onActiveExtruderChanged(self):
  423. if self._global_container_stack:
  424. # Connect all extruders of the active machine. This might cause a few connects that have already happend,
  425. # but that shouldn't cause issues as only new / unique connections are added.
  426. extruders = list(ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId()))
  427. if extruders:
  428. for extruder in extruders:
  429. extruder.propertyChanged.connect(self._onSettingChanged)
  430. if self._active_extruder_stack:
  431. self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
  432. self._active_extruder_stack = cura.Settings.ExtruderManager.getInstance().getActiveExtruderStack()
  433. if self._active_extruder_stack:
  434. self._active_extruder_stack.containersChanged.connect(self._onChanged)
  435. def _onProcessLayersFinished(self, job):
  436. self._process_layers_job = None