CuraEngineBackend.py 24 KB

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