CuraEngineBackend.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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.Resources import Resources
  12. from cura.OneAtATimeIterator import OneAtATimeIterator
  13. from . import Cura_pb2
  14. from . import ProcessSlicedObjectListJob
  15. from . import ProcessGCodeJob
  16. import os
  17. import sys
  18. import numpy
  19. from PyQt5.QtCore import QTimer
  20. class CuraEngineBackend(Backend):
  21. def __init__(self):
  22. super().__init__()
  23. # 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.
  24. default_engine_location = os.path.join(Application.getInstallPrefix(), "bin", "CuraEngine")
  25. if hasattr(sys, "frozen"):
  26. default_engine_location = os.path.join(os.path.dirname(os.path.abspath(sys.executable)), "CuraEngine")
  27. if sys.platform == "win32":
  28. default_engine_location += ".exe"
  29. default_engine_location = os.path.abspath(default_engine_location)
  30. Preferences.getInstance().addPreference("backend/location", default_engine_location)
  31. self._scene = Application.getInstance().getController().getScene()
  32. self._scene.sceneChanged.connect(self._onSceneChanged)
  33. # Workaround to disable layer view processing if layer view is not active.
  34. self._layer_view_active = False
  35. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  36. self._onActiveViewChanged()
  37. self._stored_layer_data = None
  38. self._settings = None
  39. Application.getInstance().activeMachineChanged.connect(self._onActiveMachineChanged)
  40. self._onActiveMachineChanged()
  41. self._change_timer = QTimer()
  42. self._change_timer.setInterval(500)
  43. self._change_timer.setSingleShot(True)
  44. self._change_timer.timeout.connect(self.slice)
  45. self._message_handlers[Cura_pb2.SlicedObjectList] = self._onSlicedObjectListMessage
  46. self._message_handlers[Cura_pb2.Progress] = self._onProgressMessage
  47. self._message_handlers[Cura_pb2.GCodeLayer] = self._onGCodeLayerMessage
  48. self._message_handlers[Cura_pb2.GCodePrefix] = self._onGCodePrefixMessage
  49. self._message_handlers[Cura_pb2.ObjectPrintTime] = self._onObjectPrintTimeMessage
  50. self._slicing = False
  51. self._restart = False
  52. self._save_gcode = True
  53. self._save_polygons = True
  54. self._report_progress = True
  55. self._enabled = True
  56. self.backendConnected.connect(self._onBackendConnected)
  57. def getEngineCommand(self):
  58. return [Preferences.getInstance().getValue("backend/location"), "-j", Resources.getPath(Resources.SettingsLocation, "fdmprinter.json"), "-vv", "--connect", "127.0.0.1:{0}".format(self._port)]
  59. ## Emitted when we get a message containing print duration and material amount. This also implies the slicing has finished.
  60. # \param time The amount of time the print will take.
  61. # \param material_amount The amount of material the print will use.
  62. printDurationMessage = Signal()
  63. ## Emitted when the slicing process starts.
  64. slicingStarted = Signal()
  65. ## Emitted whne the slicing process is aborted forcefully.
  66. slicingCancelled = Signal()
  67. ## Perform a slice of the scene with the given set of settings.
  68. #
  69. # \param kwargs Keyword arguments.
  70. # Valid values are:
  71. # - settings: The settings to use for the slice. The default is the active machine.
  72. # - save_gcode: True if the generated gcode should be saved, False if not. True by default.
  73. # - save_polygons: True if the generated polygon data should be saved, False if not. True by default.
  74. # - force_restart: True if the slicing process should be forcefully restarted if it is already slicing.
  75. # If False, this method will do nothing when already slicing. True by default.
  76. # - report_progress: True if the slicing progress should be reported, False if not. Default is True.
  77. def slice(self, **kwargs):
  78. if not self._enabled:
  79. return
  80. if self._slicing:
  81. if not kwargs.get("force_restart", True):
  82. return
  83. self._slicing = False
  84. self._restart = True
  85. if self._process is not None:
  86. Logger.log("d", "Killing engine process")
  87. try:
  88. self._process.terminate()
  89. except: # terminating a process that is already terminating causes an exception, silently ignore this.
  90. pass
  91. self.slicingCancelled.emit()
  92. return
  93. objects = []
  94. for node in DepthFirstIterator(self._scene.getRoot()):
  95. if type(node) is SceneNode and node.getMeshData() and node.getMeshData().getVertices() is not None:
  96. if not getattr(node, "_outside_buildarea", False):
  97. objects.append(node)
  98. if not objects:
  99. return #No point in slicing an empty build plate
  100. if kwargs.get("settings", self._settings).hasErrorValue():
  101. return #No slicing if we have error values since those are by definition illegal values.
  102. self._slicing = True
  103. self.slicingStarted.emit()
  104. self._report_progress = kwargs.get("report_progress", True)
  105. if self._report_progress:
  106. self.processingProgress.emit(0.0)
  107. self._sendSettings(kwargs.get("settings", self._settings))
  108. self._scene.acquireLock()
  109. # Set the gcode as an empty list. This will be filled with strings by GCodeLayer messages.
  110. # This is done so the gcode can be fragmented in memory and does not need a continues memory space.
  111. # (AKA. This prevents MemoryErrors)
  112. self._save_gcode = kwargs.get("save_gcode", True)
  113. if self._save_gcode:
  114. setattr(self._scene, "gcode_list", [])
  115. self._save_polygons = kwargs.get("save_polygons", True)
  116. msg = Cura_pb2.ObjectList()
  117. #TODO: All at once/one at a time mode
  118. #print("Iterator time! ", OneAtATimeIterator(self._scene.getRoot()))
  119. #for item in OneAtATimeIterator(self._scene.getRoot()):
  120. # print(item)
  121. center = Vector()
  122. for object in objects:
  123. center += object.getPosition()
  124. mesh_data = object.getMeshData().getTransformed(object.getWorldTransformation())
  125. obj = msg.objects.add()
  126. obj.id = id(object)
  127. verts = numpy.array(mesh_data.getVertices())
  128. verts[:,[1,2]] = verts[:,[2,1]]
  129. verts[:,1] *= -1
  130. obj.vertices = verts.tostring()
  131. #if meshData.hasNormals():
  132. #obj.normals = meshData.getNormalsAsByteArray()
  133. #if meshData.hasIndices():
  134. #obj.indices = meshData.getIndicesAsByteArray()
  135. self._scene.releaseLock()
  136. self._socket.sendMessage(msg)
  137. def _onSceneChanged(self, source):
  138. if (type(source) is not SceneNode) or (source is self._scene.getRoot()) or (source.getMeshData() is None):
  139. return
  140. if(source.getMeshData().getVertices() is None):
  141. return
  142. self._onChanged()
  143. def _onActiveMachineChanged(self):
  144. if self._settings:
  145. self._settings.settingChanged.disconnect(self._onSettingChanged)
  146. self._settings = Application.getInstance().getActiveMachine()
  147. if self._settings:
  148. self._settings.settingChanged.connect(self._onSettingChanged)
  149. self._onChanged()
  150. def _onSettingChanged(self, setting):
  151. self._onChanged()
  152. def _onSlicedObjectListMessage(self, message):
  153. if self._save_polygons:
  154. if self._layer_view_active:
  155. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(message)
  156. job.start()
  157. else :
  158. self._stored_layer_data = message
  159. def _onProgressMessage(self, message):
  160. if message.amount >= 0.99:
  161. self._slicing = False
  162. if self._report_progress:
  163. self.processingProgress.emit(message.amount)
  164. def _onGCodeLayerMessage(self, message):
  165. if self._save_gcode:
  166. job = ProcessGCodeJob.ProcessGCodeLayerJob(message)
  167. job.start()
  168. def _onGCodePrefixMessage(self, message):
  169. if self._save_gcode:
  170. self._scene.gcode_list.insert(0, message.data.decode("utf-8", "replace"))
  171. def _onObjectPrintTimeMessage(self, message):
  172. self.printDurationMessage.emit(message.time, message.material_amount)
  173. self.processingProgress.emit(1.0)
  174. def _createSocket(self):
  175. super()._createSocket()
  176. self._socket.registerMessageType(1, Cura_pb2.ObjectList)
  177. self._socket.registerMessageType(2, Cura_pb2.SlicedObjectList)
  178. self._socket.registerMessageType(3, Cura_pb2.Progress)
  179. self._socket.registerMessageType(4, Cura_pb2.GCodeLayer)
  180. self._socket.registerMessageType(5, Cura_pb2.ObjectPrintTime)
  181. self._socket.registerMessageType(6, Cura_pb2.SettingList)
  182. self._socket.registerMessageType(7, Cura_pb2.GCodePrefix)
  183. def _onChanged(self):
  184. if not self._settings:
  185. return
  186. self._change_timer.start()
  187. def _sendSettings(self, settings):
  188. msg = Cura_pb2.SettingList()
  189. for setting in settings.getAllSettings(include_machine=True):
  190. s = msg.settings.add()
  191. s.name = setting.getKey()
  192. s.value = str(setting.getValue()).encode("utf-8")
  193. self._socket.sendMessage(msg)
  194. def _onBackendConnected(self):
  195. if self._restart:
  196. self._onChanged()
  197. self._restart = False
  198. def _onToolOperationStarted(self, tool):
  199. self._enabled = False
  200. def _onToolOperationStopped(self, tool):
  201. self._enabled = True
  202. self._onChanged()
  203. def _onActiveViewChanged(self):
  204. if Application.getInstance().getController().getActiveView():
  205. view = Application.getInstance().getController().getActiveView()
  206. if view.getPluginId() == "LayerView":
  207. self._layer_view_active = True
  208. if self._stored_layer_data:
  209. job = ProcessSlicedObjectListJob.ProcessSlicedObjectListJob(self._stored_layer_data)
  210. job.start()
  211. else:
  212. self._layer_view_active = False