CuraEngineBackend.py 24 KB

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