CuraEngineBackend.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. import cura.Settings
  15. from cura.OneAtATimeIterator import OneAtATimeIterator
  16. from . import ProcessSlicedLayersJob
  17. from . import ProcessGCodeJob
  18. from . import StartSliceJob
  19. import os
  20. import sys
  21. from PyQt5.QtCore import QTimer
  22. import Arcus
  23. from UM.i18n import i18nCatalog
  24. catalog = i18nCatalog("cura")
  25. class CuraEngineBackend(Backend):
  26. ## Starts the back-end plug-in.
  27. #
  28. # This registers all the signal listeners and prepares for communication
  29. # with the back-end in general.
  30. def __init__(self):
  31. super().__init__()
  32. # Find out where the engine is located, and how it is called. This depends on how Cura is packaged and which OS we are running on.
  33. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  34. if hasattr(sys, "frozen"):
  35. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  36. if Platform.isWindows():
  37. default_engine_location += ".exe"
  38. default_engine_location = os.path.abspath(default_engine_location)
  39. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  40. self._scene = Application.getInstance().getController().getScene()
  41. self._scene.sceneChanged.connect(self._onSceneChanged)
  42. # Workaround to disable layer view processing if layer view is not active.
  43. self._layer_view_active = False
  44. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  45. self._onActiveViewChanged()
  46. self._stored_layer_data = []
  47. #Triggers for when to (re)start slicing:
  48. self._global_container_stack = None
  49. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  50. self._onGlobalStackChanged()
  51. self._active_extruder_stack = None
  52. cura.Settings.ExtruderManager.getInstance().activeExtruderChanged.connect(self._onActiveExtruderChanged)
  53. self._onActiveExtruderChanged()
  54. #When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  55. #This timer will group them up, and only slice for the last setting changed signal.
  56. #TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  57. self._change_timer = QTimer()
  58. self._change_timer.setInterval(500)
  59. self._change_timer.setSingleShot(True)
  60. self._change_timer.timeout.connect(self.slice)
  61. #Listeners for receiving messages from the back-end.
  62. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  63. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  64. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  65. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  66. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  67. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  68. self._start_slice_job = None
  69. self._slicing = False #Are we currently slicing?
  70. self._restart = False #Back-end is currently restarting?
  71. self._enabled = True #Should we be slicing? Slicing might be paused when, for instance, the user is dragging the mesh around.
  72. self._always_restart = True #Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  73. self._process_layers_job = None #The currently active job to process layers, or None if it is not processing layers.
  74. self._backend_log_max_lines = 200 # Maximal count of lines to buffer
  75. self._error_message = None #Pop-up message that shows errors.
  76. self.backendQuit.connect(self._onBackendQuit)
  77. self.backendConnected.connect(self._onBackendConnected)
  78. #When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  79. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  80. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  81. ## Called when closing the application.
  82. #
  83. # This function should terminate the engine process.
  84. def close(self):
  85. # Terminate CuraEngine if it is still running at this point
  86. self._terminate()
  87. super().close()
  88. ## Get the command that is used to call the engine.
  89. # This is useful for debugging and used to actually start the engine.
  90. # \return list of commands and args / parameters.
  91. def getEngineCommand(self):
  92. json_path = Resources.getPath(Resources.DefinitionContainers, "fdmprinter.def.json")
  93. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", json_path, "-vv"]
  94. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  95. # \param time The amount of time the print will take.
  96. # \param material_amount The amount of material the print will use.
  97. printDurationMessage = Signal()
  98. ## Emitted when the slicing process starts.
  99. slicingStarted = Signal()
  100. ## Emitted when the slicing process is aborted forcefully.
  101. slicingCancelled = Signal()
  102. ## Perform a slice of the scene.
  103. def slice(self):
  104. if not self._enabled or not self._global_container_stack: #We shouldn't be slicing.
  105. # try again in a short time
  106. self._change_timer.start()
  107. return
  108. self.printDurationMessage.emit(0, [0])
  109. self._stored_layer_data = []
  110. if self._slicing: #We were already slicing. Stop the old job.
  111. self._terminate()
  112. if self._process_layers_job: #We were processing layers. Stop that, the layers are going to change soon.
  113. self._process_layers_job.abort()
  114. self._process_layers_job = None
  115. if self._error_message:
  116. self._error_message.hide()
  117. self.processingProgress.emit(0.0)
  118. self.backendStateChange.emit(BackendState.NotStarted)
  119. self._scene.gcode_list = []
  120. self._slicing = True
  121. self.slicingStarted.emit()
  122. slice_message = self._socket.createMessage("cura.proto.Slice")
  123. self._start_slice_job = StartSliceJob.StartSliceJob(slice_message)
  124. self._start_slice_job.start()
  125. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  126. ## Terminate the engine process.
  127. def _terminate(self):
  128. self._slicing = False
  129. self._restart = True
  130. self._stored_layer_data = []
  131. if self._start_slice_job is not None:
  132. self._start_slice_job.cancel()
  133. self.slicingCancelled.emit()
  134. self.processingProgress.emit(0)
  135. Logger.log("d", "Attempting to kill the engine process")
  136. if self._process is not None:
  137. Logger.log("d", "Killing engine process")
  138. try:
  139. self._process.terminate()
  140. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait())
  141. self._process = None
  142. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  143. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  144. ## Event handler to call when the job to initiate the slicing process is
  145. # completed.
  146. #
  147. # When the start slice job is successfully completed, it will be happily
  148. # slicing. This function handles any errors that may occur during the
  149. # bootstrapping of a slice job.
  150. #
  151. # \param job The start slice job that was just finished.
  152. def _onStartSliceCompleted(self, job):
  153. # Note that cancelled slice jobs can still call this method.
  154. if self._start_slice_job is job:
  155. self._start_slice_job = None
  156. if job.isCancelled() or job.getError() or job.getResult() == StartSliceJob.StartJobResult.Error:
  157. return
  158. if job.getResult() == StartSliceJob.StartJobResult.SettingError:
  159. if Application.getInstance().getPlatformActivity:
  160. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."), lifetime = 10)
  161. self._error_message.show()
  162. self.backendStateChange.emit(BackendState.Error)
  163. else:
  164. self.backendStateChange.emit(BackendState.NotStarted)
  165. return
  166. if job.getResult() == StartSliceJob.StartJobResult.NothingToSlice:
  167. if Application.getInstance().getPlatformActivity:
  168. self._error_message = Message(catalog.i18nc("@info:status", "Unable to slice. No suitable objects found."), lifetime = 10)
  169. self._error_message.show()
  170. self.backendStateChange.emit(BackendState.Error)
  171. else:
  172. self.backendStateChange.emit(BackendState.NotStarted)
  173. return
  174. # Preparation completed, send it to the backend.
  175. self._socket.sendMessage(job.getSliceMessage())
  176. ## Listener for when the scene has changed.
  177. #
  178. # This should start a slice if the scene is now ready to slice.
  179. #
  180. # \param source The scene node that was changed.
  181. def _onSceneChanged(self, source):
  182. if type(source) is not SceneNode:
  183. return
  184. if source is self._scene.getRoot():
  185. return
  186. if source.getMeshData() is None:
  187. return
  188. if source.getMeshData().getVertices() is None:
  189. return
  190. self._onChanged()
  191. ## Called when an error occurs in the socket connection towards the engine.
  192. #
  193. # \param error The exception that occurred.
  194. def _onSocketError(self, error):
  195. if Application.getInstance().isShuttingDown():
  196. return
  197. super()._onSocketError(error)
  198. self._terminate()
  199. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  200. Logger.log("e", "A socket error caused the connection to be reset")
  201. ## A setting has changed, so check if we must reslice.
  202. #
  203. # \param instance The setting instance that has changed.
  204. # \param property The property of the setting instance that has changed.
  205. def _onSettingChanged(self, instance, property):
  206. if property == "value": #Only reslice if the value has changed.
  207. self._onChanged()
  208. ## Called when a sliced layer data message is received from the engine.
  209. #
  210. # \param message The protobuf message containing sliced layer data.
  211. def _onLayerMessage(self, message):
  212. self._stored_layer_data.append(message)
  213. ## Called when a progress message is received from the engine.
  214. #
  215. # \param message The protobuf message containing the slicing progress.
  216. def _onProgressMessage(self, message):
  217. self.processingProgress.emit(message.amount)
  218. self.backendStateChange.emit(BackendState.Processing)
  219. ## Called when the engine sends a message that slicing is finished.
  220. #
  221. # \param message The protobuf message signalling that slicing is finished.
  222. def _onSlicingFinishedMessage(self, message):
  223. self.backendStateChange.emit(BackendState.Done)
  224. self.processingProgress.emit(1.0)
  225. self._slicing = False
  226. if self._layer_view_active and (self._process_layers_job is None or not self._process_layers_job.isRunning()):
  227. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_layer_data)
  228. self._process_layers_job.start()
  229. self._stored_layer_data = []
  230. ## Called when a g-code message is received from the engine.
  231. #
  232. # \param message The protobuf message containing g-code, encoded as UTF-8.
  233. def _onGCodeLayerMessage(self, message):
  234. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  235. ## Called when a g-code prefix message is received from the engine.
  236. #
  237. # \param message The protobuf message containing the g-code prefix,
  238. # encoded as UTF-8.
  239. def _onGCodePrefixMessage(self, message):
  240. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  241. ## Called when a print time message is received from the engine.
  242. #
  243. # \param message The protobuf message containing the print time and
  244. # material amount per extruder
  245. def _onPrintTimeMaterialEstimates(self, message):
  246. material_amounts = []
  247. for index in range(message.repeatedMessageCount("materialEstimates")):
  248. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  249. self.printDurationMessage.emit(message.time, material_amounts)
  250. ## Creates a new socket connection.
  251. def _createSocket(self):
  252. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  253. ## Manually triggers a reslice
  254. def forceSlice(self):
  255. self._change_timer.start()
  256. ## Called when anything has changed to the stuff that needs to be sliced.
  257. #
  258. # This indicates that we should probably re-slice soon.
  259. def _onChanged(self, *args, **kwargs):
  260. self._change_timer.start()
  261. ## Called when the back-end connects to the front-end.
  262. def _onBackendConnected(self):
  263. if self._restart:
  264. self._onChanged()
  265. self._restart = False
  266. ## Called when the user starts using some tool.
  267. #
  268. # When the user starts using a tool, we should pause slicing to prevent
  269. # continuously slicing while the user is dragging some tool handle.
  270. #
  271. # \param tool The tool that the user is using.
  272. def _onToolOperationStarted(self, tool):
  273. self._terminate() # Do not continue slicing once a tool has started
  274. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  275. ## Called when the user stops using some tool.
  276. #
  277. # This indicates that we can safely start slicing again.
  278. #
  279. # \param tool The tool that the user was using.
  280. def _onToolOperationStopped(self, tool):
  281. self._enabled = True # Tool stop, start listening for changes again.
  282. ## Called when the user changes the active view mode.
  283. def _onActiveViewChanged(self):
  284. if Application.getInstance().getController().getActiveView():
  285. view = Application.getInstance().getController().getActiveView()
  286. if view.getPluginId() == "LayerView": #If switching to layer view, we should process the layers if that hasn't been done yet.
  287. self._layer_view_active = True
  288. # There is data and we're not slicing at the moment
  289. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  290. if self._stored_layer_data and not self._slicing:
  291. self._process_layers_job = ProcessSlicedLayersJob.ProcessSlicedLayersJob(self._stored_layer_data)
  292. self._process_layers_job.start()
  293. self._stored_layer_data = []
  294. else:
  295. self._layer_view_active = False
  296. ## Called when the back-end self-terminates.
  297. #
  298. # We should reset our state and start listening for new connections.
  299. def _onBackendQuit(self):
  300. if not self._restart and self._process:
  301. Logger.log("d", "Backend quit with return code %s. Resetting process and socket.", self._process.wait())
  302. self._process = None
  303. self._createSocket()
  304. ## Called when the global container stack changes
  305. def _onGlobalStackChanged(self):
  306. if self._global_container_stack:
  307. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  308. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  309. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  310. if self._global_container_stack:
  311. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) #Note: Only starts slicing when the value changed.
  312. self._global_container_stack.containersChanged.connect(self._onChanged)
  313. self._onActiveExtruderChanged()
  314. self._onChanged()
  315. def _onActiveExtruderChanged(self):
  316. if self._active_extruder_stack:
  317. self._active_extruder_stack.propertyChanged.disconnect(self._onSettingChanged)
  318. self._active_extruder_stack.containersChanged.disconnect(self._onChanged)
  319. self._active_extruder_stack = cura.Settings.ExtruderManager.getInstance().getActiveExtruderStack()
  320. if self._active_extruder_stack:
  321. self._active_extruder_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  322. self._active_extruder_stack.containersChanged.connect(self._onChanged)