CuraEngineBackend.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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
  4. from UM.Application import Application
  5. from UM.Scene.SceneNode import SceneNode
  6. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  7. from UM.Preferences import Preferences
  8. from UM.Math.Vector import Vector
  9. from UM.Signal import Signal
  10. from UM.Logger import Logger
  11. from UM.Qt.Bindings.BackendProxy import BackendState #To determine the state of the slicing job.
  12. from UM.Resources import Resources
  13. from UM.Settings.SettingOverrideDecorator import SettingOverrideDecorator
  14. from UM.Message import Message
  15. from UM.PluginRegistry import PluginRegistry
  16. from cura.OneAtATimeIterator import OneAtATimeIterator
  17. from . import ProcessSlicedObjectListJob
  18. from . import ProcessGCodeJob
  19. from . import StartSliceJob
  20. import os
  21. import sys
  22. import numpy
  23. from PyQt5.QtCore import QTimer
  24. import Arcus
  25. from UM.i18n import i18nCatalog
  26. catalog = i18nCatalog("cura")
  27. class CuraEngineBackend(Backend):
  28. def __init__(self):
  29. super().__init__()
  30. # 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.
  31. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  32. if hasattr(sys, "frozen"):
  33. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  34. if sys.platform == "win32":
  35. default_engine_location += ".exe"
  36. default_engine_location = os.path.abspath(default_engine_location)
  37. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  38. self._scene = Application.getInstance().getController().getScene()
  39. self._scene.sceneChanged.connect(self._onSceneChanged)
  40. # Workaround to disable layer view processing if layer view is not active.
  41. self._layer_view_active = False
  42. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  43. self._onActiveViewChanged()
  44. self._stored_layer_data = None
  45. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onChanged)
  46. self._profile = None
  47. Application.getInstance().getMachineManager().activeProfileChanged.connect(self._onActiveProfileChanged)
  48. self._onActiveProfileChanged()
  49. self._change_timer = QTimer()
  50. self._change_timer.setInterval(500)
  51. self._change_timer.setSingleShot(True)
  52. self._change_timer.timeout.connect(self.slice)
  53. self._message_handlers["cura.proto.SlicedObjectList"] = self._onSlicedObjectListMessage
  54. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  55. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  56. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  57. self._message_handlers["cura.proto.ObjectPrintTime"] = self._onObjectPrintTimeMessage
  58. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  59. self._slicing = False
  60. self._restart = False
  61. self._enabled = True
  62. self._always_restart = True
  63. self._process_layers_job = None #The currently active job to process layers, or None if it is not processing layers.
  64. self._message = None
  65. self.backendQuit.connect(self._onBackendQuit)
  66. self.backendConnected.connect(self._onBackendConnected)
  67. Application.getInstance().getController().toolOperationStarted.connect(self._onToolOperationStarted)
  68. Application.getInstance().getController().toolOperationStopped.connect(self._onToolOperationStopped)
  69. Application.getInstance().getMachineManager().activeMachineInstanceChanged.connect(self._onInstanceChanged)
  70. ## Get the command that is used to call the engine.
  71. # This is usefull for debugging and used to actually start the engine
  72. # \return list of commands and args / parameters.
  73. def getEngineCommand(self):
  74. active_machine = Application.getInstance().getMachineManager().getActiveMachineInstance()
  75. if not active_machine:
  76. return None
  77. return [Preferences.getInstance().getValue("backend/location"), "connect", "127.0.0.1:{0}".format(self._port), "-j", active_machine.getMachineDefinition().getPath(), "-vv"]
  78. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  79. # \param time The amount of time the print will take.
  80. # \param material_amount The amount of material the print will use.
  81. printDurationMessage = Signal()
  82. ## Emitted when the slicing process starts.
  83. slicingStarted = Signal()
  84. ## Emitted whne the slicing process is aborted forcefully.
  85. slicingCancelled = Signal()
  86. ## Perform a slice of the scene.
  87. def slice(self):
  88. if not self._enabled:
  89. return
  90. if self._slicing:
  91. self._terminate()
  92. if self._message:
  93. self._message.hide()
  94. self._message = None
  95. self.slicingCancelled.emit()
  96. return
  97. if self._process_layers_job:
  98. self._process_layers_job.abort()
  99. self._process_layers_job = None
  100. if self._profile.hasErrorValue():
  101. Logger.log("w", "Profile has error values. Aborting slicing")
  102. if self._message:
  103. self._message.hide()
  104. self._message = None
  105. self._message = Message(catalog.i18nc("@info:status", "Unable to slice. Please check your setting values for errors."))
  106. self._message.show()
  107. return #No slicing if we have error values since those are by definition illegal values.
  108. self.processingProgress.emit(0.0)
  109. self.backendStateChange.emit(BackendState.NOT_STARTED)
  110. if self._message:
  111. self._message.setProgress(-1)
  112. #else:
  113. # self._message = Message(catalog.i18nc("@info:status", "Slicing..."), 0, False, -1)
  114. # self._message.show()
  115. self._scene.gcode_list = []
  116. self._slicing = True
  117. self.slicingStarted.emit()
  118. job = StartSliceJob.StartSliceJob(self._profile, self._socket)
  119. job.start()
  120. job.finished.connect(self._onStartSliceCompleted)
  121. def _terminate(self):
  122. self._slicing = False
  123. self._restart = True
  124. self.slicingCancelled.emit()
  125. if self._process is not None:
  126. Logger.log("d", "Killing engine process")
  127. try:
  128. self._process.terminate()
  129. self._process = None
  130. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  131. pass
  132. def _onStartSliceCompleted(self, job):
  133. if job.getError() or job.getResult() != True:
  134. if self._message:
  135. self._message.hide()
  136. self._message = None
  137. return
  138. def _onSceneChanged(self, source):
  139. if type(source) is not SceneNode:
  140. return
  141. if source is self._scene.getRoot():
  142. return
  143. if source.getMeshData() is None:
  144. return
  145. if source.getMeshData().getVertices() is None:
  146. return
  147. self._onChanged()
  148. def _onSocketError(self, error):
  149. super()._onSocketError(error)
  150. self._slicing = False
  151. self.processingProgress.emit(0)
  152. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  153. Logger.log("e", "A socket error caused the connection to be reset")
  154. def _onActiveProfileChanged(self):
  155. if self._profile:
  156. self._profile.settingValueChanged.disconnect(self._onSettingChanged)
  157. self._profile = Application.getInstance().getMachineManager().getWorkingProfile()
  158. if self._profile:
  159. self._profile.settingValueChanged.connect(self._onSettingChanged)
  160. self._onChanged()
  161. def _onSettingChanged(self, setting):
  162. self._onChanged()
  163. def _onSlicedObjectListMessage(self, message):
  164. if self._layer_view_active:
  165. self._process_layers_job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(message)
  166. self._process_layers_job.start()
  167. else :
  168. self._stored_layer_data = message
  169. def _onProgressMessage(self, message):
  170. if self._message:
  171. self._message.setProgress(round(message.amount * 100))
  172. self.processingProgress.emit(message.amount)
  173. self.backendStateChange.emit(BackendState.PROCESSING)
  174. def _onSlicingFinishedMessage(self, message):
  175. self.backendStateChange.emit(BackendState.DONE)
  176. self.processingProgress.emit(1.0)
  177. self._slicing = False
  178. if self._message:
  179. self._message.setProgress(100)
  180. self._message.hide()
  181. self._message = None
  182. def _onGCodeLayerMessage(self, message):
  183. self._scene.gcode_list.append(message.data.decode("utf-8", "replace"))
  184. def _onGCodePrefixMessage(self, message):
  185. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  186. def _onObjectPrintTimeMessage(self, message):
  187. self.printDurationMessage.emit(message.time, message.material_amount)
  188. def _createSocket(self):
  189. super()._createSocket(os.path.abspath(os.path.join(PluginRegistry.getInstance().getPluginPath(self.getPluginId()), "Cura.proto")))
  190. ## Manually triggers a reslice
  191. def forceSlice(self):
  192. self._change_timer.start()
  193. def _onChanged(self):
  194. if not self._profile:
  195. return
  196. self._change_timer.start()
  197. def _onBackendConnected(self):
  198. if self._restart:
  199. self._onChanged()
  200. self._restart = False
  201. def _onToolOperationStarted(self, tool):
  202. self._terminate() # Do not continue slicing once a tool has started
  203. self._enabled = False # Do not reslice when a tool is doing it's 'thing'
  204. def _onToolOperationStopped(self, tool):
  205. self._enabled = True # Tool stop, start listening for changes again.
  206. def _onActiveViewChanged(self):
  207. if Application.getInstance().getController().getActiveView():
  208. view = Application.getInstance().getController().getActiveView()
  209. if view.getPluginId() == "LayerView":
  210. self._layer_view_active = True
  211. # There is data and we're not slicing at the moment
  212. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  213. if self._stored_layer_data and not self._slicing:
  214. self._process_layers_job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(self._stored_layer_data)
  215. self._process_layers_job.start()
  216. self._stored_layer_data = None
  217. else:
  218. self._layer_view_active = False
  219. def _onInstanceChanged(self):
  220. self._terminate()
  221. self.slicingCancelled.emit()
  222. def _onBackendQuit(self):
  223. if not self._restart and self._process:
  224. self._process = None
  225. self._createSocket()