CuraEngineBackend.py 18 KB

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