CuraEngineBackend.py 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  1. # Copyright (c) 2021-2022 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import argparse #To run the engine in debug mode if the front-end is in debug mode.
  4. from collections import defaultdict
  5. import os
  6. from PyQt6.QtCore import QObject, QTimer, QUrl, pyqtSlot
  7. import sys
  8. from time import time
  9. from typing import Any, cast, Dict, List, Optional, Set, TYPE_CHECKING
  10. from PyQt6.QtGui import QDesktopServices, QImage
  11. from UM.Backend.Backend import Backend, BackendState
  12. from UM.Scene.SceneNode import SceneNode
  13. from UM.Signal import Signal
  14. from UM.Logger import Logger
  15. from UM.Message import Message
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Platform import Platform
  18. from UM.Qt.Duration import DurationFormat
  19. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  20. from UM.Settings.Interfaces import DefinitionContainerInterface
  21. from UM.Settings.SettingInstance import SettingInstance #For typing.
  22. from UM.Tool import Tool #For typing.
  23. from cura.CuraApplication import CuraApplication
  24. from cura.Settings.ExtruderManager import ExtruderManager
  25. from cura.Snapshot import Snapshot
  26. from cura.Utils.Threading import call_on_qt_thread
  27. from .ProcessSlicedLayersJob import ProcessSlicedLayersJob
  28. from .StartSliceJob import StartSliceJob, StartJobResult
  29. import pyArcus as Arcus
  30. if TYPE_CHECKING:
  31. from cura.Machines.Models.MultiBuildPlateModel import MultiBuildPlateModel
  32. from cura.Machines.MachineErrorChecker import MachineErrorChecker
  33. from UM.Scene.Scene import Scene
  34. from UM.Settings.ContainerStack import ContainerStack
  35. from UM.i18n import i18nCatalog
  36. catalog = i18nCatalog("cura")
  37. class CuraEngineBackend(QObject, Backend):
  38. backendError = Signal()
  39. def __init__(self) -> None:
  40. """Starts the back-end plug-in.
  41. This registers all the signal listeners and prepares for communication
  42. with the back-end in general.
  43. CuraEngineBackend is exposed to qml as well.
  44. """
  45. super().__init__()
  46. # Find out where the engine is located, and how it is called.
  47. # This depends on how Cura is packaged and which OS we are running on.
  48. executable_name = "CuraEngine"
  49. if Platform.isWindows():
  50. executable_name += ".exe"
  51. self._default_engine_location = executable_name
  52. search_path = [
  53. os.path.abspath(os.path.dirname(sys.executable)),
  54. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "bin")),
  55. os.path.abspath(os.path.join(os.path.dirname(sys.executable), "..")),
  56. os.path.join(CuraApplication.getInstallPrefix(), "bin"),
  57. os.path.dirname(os.path.abspath(sys.executable)),
  58. ]
  59. for path in search_path:
  60. engine_path = os.path.join(path, executable_name)
  61. if os.path.isfile(engine_path):
  62. self._default_engine_location = engine_path
  63. break
  64. if Platform.isLinux() and not self._default_engine_location:
  65. if not os.getenv("PATH"):
  66. raise OSError("There is something wrong with your Linux installation.")
  67. for pathdir in cast(str, os.getenv("PATH")).split(os.pathsep):
  68. execpath = os.path.join(pathdir, executable_name)
  69. if os.path.exists(execpath):
  70. self._default_engine_location = execpath
  71. break
  72. application = CuraApplication.getInstance() #type: CuraApplication
  73. self._multi_build_plate_model = None #type: Optional[MultiBuildPlateModel]
  74. self._machine_error_checker = None #type: Optional[MachineErrorChecker]
  75. if not self._default_engine_location:
  76. raise EnvironmentError("Could not find CuraEngine")
  77. Logger.log("i", "Found CuraEngine at: %s", self._default_engine_location)
  78. self._default_engine_location = os.path.abspath(self._default_engine_location)
  79. application.getPreferences().addPreference("backend/location", self._default_engine_location)
  80. # Workaround to disable layer view processing if layer view is not active.
  81. self._layer_view_active = False #type: bool
  82. self._onActiveViewChanged()
  83. self._stored_layer_data = [] # type: List[Arcus.PythonMessage]
  84. self._stored_optimized_layer_data = {} # type: Dict[int, List[Arcus.PythonMessage]] # key is build plate number, then arrays are stored until they go to the ProcessSlicesLayersJob
  85. self._scene = application.getController().getScene() #type: Scene
  86. self._scene.sceneChanged.connect(self._onSceneChanged)
  87. # Triggers for auto-slicing. Auto-slicing is triggered as follows:
  88. # - auto-slicing is started with a timer
  89. # - whenever there is a value change, we start the timer
  90. # - sometimes an error check can get scheduled for a value change, in that case, we ONLY want to start the
  91. # auto-slicing timer when that error check is finished
  92. # If there is an error check, stop the auto-slicing timer, and only wait for the error check to be finished
  93. # to start the auto-slicing timer again.
  94. #
  95. self._global_container_stack = None #type: Optional[ContainerStack]
  96. # Listeners for receiving messages from the back-end.
  97. self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
  98. self._message_handlers["cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
  99. self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
  100. self._message_handlers["cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
  101. self._message_handlers["cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
  102. self._message_handlers["cura.proto.SliceUUID"] = self._onSliceUUIDMessage
  103. self._message_handlers["cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
  104. self._message_handlers["cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage
  105. self._start_slice_job = None #type: Optional[StartSliceJob]
  106. self._start_slice_job_build_plate = None #type: Optional[int]
  107. self._slicing = False #type: bool # Are we currently slicing?
  108. self._restart = False #type: bool # Back-end is currently restarting?
  109. self._tool_active = False #type: bool # If a tool is active, some tasks do not have to do anything
  110. self._always_restart = True #type: bool # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
  111. self._process_layers_job = None #type: Optional[ProcessSlicedLayersJob] # The currently active job to process layers, or None if it is not processing layers.
  112. self._build_plates_to_be_sliced = [] #type: List[int] # what needs slicing?
  113. self._engine_is_fresh = True #type: bool # Is the newly started engine used before or not?
  114. self._backend_log_max_lines = 20000 #type: int # Maximum number of lines to buffer
  115. self._error_message = None #type: Optional[Message] # Pop-up message that shows errors.
  116. self._last_num_objects = defaultdict(int) #type: Dict[int, int] # Count number of objects to see if there is something changed
  117. self._postponed_scene_change_sources = [] #type: List[SceneNode] # scene change is postponed (by a tool)
  118. self._slice_start_time = None #type: Optional[float]
  119. self._is_disabled = False #type: bool
  120. application.getPreferences().addPreference("general/auto_slice", False)
  121. self._use_timer = False #type: bool
  122. # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
  123. # This timer will group them up, and only slice for the last setting changed signal.
  124. # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
  125. self._change_timer = QTimer() #type: QTimer
  126. self._change_timer.setSingleShot(True)
  127. self._change_timer.setInterval(500)
  128. self.determineAutoSlicing()
  129. application.getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  130. self._slicing_error_message = Message(
  131. text = catalog.i18nc("@message", "Slicing failed with an unexpected error. Please consider reporting a bug on our issue tracker."),
  132. title = catalog.i18nc("@message:title", "Slicing failed"),
  133. message_type = Message.MessageType.ERROR
  134. )
  135. self._slicing_error_message.addAction(
  136. action_id = "report_bug",
  137. name = catalog.i18nc("@message:button", "Report a bug"),
  138. description = catalog.i18nc("@message:description", "Report a bug on Ultimaker Cura's issue tracker."),
  139. icon = "[no_icon]"
  140. )
  141. self._slicing_error_message.actionTriggered.connect(self._reportBackendError)
  142. self._snapshot = None #type: Optional[QImage]
  143. application.initializationFinished.connect(self.initialize)
  144. def initialize(self) -> None:
  145. application = CuraApplication.getInstance()
  146. self._multi_build_plate_model = application.getMultiBuildPlateModel()
  147. application.getController().activeViewChanged.connect(self._onActiveViewChanged)
  148. if self._multi_build_plate_model:
  149. self._multi_build_plate_model.activeBuildPlateChanged.connect(self._onActiveViewChanged)
  150. application.getMachineManager().globalContainerChanged.connect(self._onGlobalStackChanged)
  151. self._onGlobalStackChanged()
  152. # extruder enable / disable. Actually wanted to use machine manager here, but the initialization order causes it to crash
  153. ExtruderManager.getInstance().extrudersChanged.connect(self._extruderChanged)
  154. self.backendQuit.connect(self._onBackendQuit)
  155. self.backendConnected.connect(self._onBackendConnected)
  156. # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
  157. application.getController().toolOperationStarted.connect(self._onToolOperationStarted)
  158. application.getController().toolOperationStopped.connect(self._onToolOperationStopped)
  159. self._machine_error_checker = application.getMachineErrorChecker()
  160. self._machine_error_checker.errorCheckFinished.connect(self._onStackErrorCheckFinished)
  161. def close(self) -> None:
  162. """Terminate the engine process.
  163. This function should terminate the engine process.
  164. Called when closing the application.
  165. """
  166. # Terminate CuraEngine if it is still running at this point
  167. self._terminate()
  168. def getEngineCommand(self) -> List[str]:
  169. """Get the command that is used to call the engine.
  170. This is useful for debugging and used to actually start the engine.
  171. :return: list of commands and args / parameters.
  172. """
  173. from cura import ApplicationMetadata
  174. if ApplicationMetadata.IsEnterpriseVersion:
  175. command = [self._default_engine_location]
  176. else:
  177. command = [CuraApplication.getInstance().getPreferences().getValue("backend/location")]
  178. command += ["connect", "127.0.0.1:{0}".format(self._port), ""]
  179. parser = argparse.ArgumentParser(prog = "cura", add_help = False)
  180. parser.add_argument("--debug", action = "store_true", default = False, help = "Turn on the debug mode by setting this option.")
  181. known_args = vars(parser.parse_known_args()[0])
  182. if known_args["debug"]:
  183. command.append("-vvv")
  184. return command
  185. printDurationMessage = Signal()
  186. """Emitted when we get a message containing print duration and material amount.
  187. This also implies the slicing has finished.
  188. :param time: The amount of time the print will take.
  189. :param material_amount: The amount of material the print will use.
  190. """
  191. slicingStarted = Signal()
  192. """Emitted when the slicing process starts."""
  193. slicingCancelled = Signal()
  194. """Emitted when the slicing process is aborted forcefully."""
  195. @pyqtSlot()
  196. def stopSlicing(self) -> None:
  197. self.setState(BackendState.NotStarted)
  198. if self._slicing: # We were already slicing. Stop the old job.
  199. self._terminate()
  200. self._createSocket()
  201. if self._process_layers_job is not None: # We were processing layers. Stop that, the layers are going to change soon.
  202. Logger.log("i", "Aborting process layers job...")
  203. self._process_layers_job.abort()
  204. self._process_layers_job = None
  205. if self._error_message:
  206. self._error_message.hide()
  207. @pyqtSlot()
  208. def forceSlice(self) -> None:
  209. """Manually triggers a reslice"""
  210. self.markSliceAll()
  211. self.slice()
  212. @call_on_qt_thread # must be called from the main thread because of OpenGL
  213. def _createSnapshot(self) -> None:
  214. self._snapshot = None
  215. if not CuraApplication.getInstance().isVisible:
  216. Logger.log("w", "Can't create snapshot when renderer not initialized.")
  217. return
  218. Logger.log("i", "Creating thumbnail image (just before slice)...")
  219. try:
  220. self._snapshot = Snapshot.snapshot(width = 300, height = 300)
  221. except:
  222. Logger.logException("w", "Failed to create snapshot image")
  223. self._snapshot = None # Failing to create thumbnail should not fail creation of UFP
  224. def getLatestSnapshot(self) -> Optional[QImage]:
  225. return self._snapshot
  226. def slice(self) -> None:
  227. """Perform a slice of the scene."""
  228. self._createSnapshot()
  229. Logger.log("i", "Starting to slice...")
  230. self._slice_start_time = time()
  231. if not self._build_plates_to_be_sliced:
  232. self.processingProgress.emit(1.0)
  233. Logger.log("w", "Slice unnecessary, nothing has changed that needs reslicing.")
  234. self.setState(BackendState.Done)
  235. return
  236. if self._process_layers_job:
  237. Logger.log("d", "Process layers job still busy, trying later.")
  238. return
  239. if not hasattr(self._scene, "gcode_dict"):
  240. self._scene.gcode_dict = {} #type: ignore #Because we are creating the missing attribute here.
  241. # see if we really have to slice
  242. application = CuraApplication.getInstance()
  243. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  244. build_plate_to_be_sliced = self._build_plates_to_be_sliced.pop(0)
  245. Logger.log("d", "Going to slice build plate [%s]!" % build_plate_to_be_sliced)
  246. num_objects = self._numObjectsPerBuildPlate()
  247. self._stored_layer_data = []
  248. if build_plate_to_be_sliced not in num_objects or num_objects[build_plate_to_be_sliced] == 0:
  249. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #Because we created this attribute above.
  250. Logger.log("d", "Build plate %s has no objects to be sliced, skipping", build_plate_to_be_sliced)
  251. if self._build_plates_to_be_sliced:
  252. self.slice()
  253. return
  254. self._stored_optimized_layer_data[build_plate_to_be_sliced] = []
  255. if application.getPrintInformation() and build_plate_to_be_sliced == active_build_plate:
  256. application.getPrintInformation().setToZeroPrintInformation(build_plate_to_be_sliced)
  257. if self._process is None: # type: ignore
  258. self._createSocket()
  259. self.stopSlicing()
  260. self._engine_is_fresh = False # Yes we're going to use the engine
  261. self.processingProgress.emit(0.0)
  262. self.backendStateChange.emit(BackendState.NotStarted)
  263. self._scene.gcode_dict[build_plate_to_be_sliced] = [] #type: ignore #[] indexed by build plate number
  264. self._slicing = True
  265. self.slicingStarted.emit()
  266. self.determineAutoSlicing() # Switch timer on or off if appropriate
  267. slice_message = self._socket.createMessage("cura.proto.Slice")
  268. self._start_slice_job = StartSliceJob(slice_message)
  269. self._start_slice_job_build_plate = build_plate_to_be_sliced
  270. self._start_slice_job.setBuildPlate(self._start_slice_job_build_plate)
  271. self._start_slice_job.start()
  272. self._start_slice_job.finished.connect(self._onStartSliceCompleted)
  273. def _terminate(self) -> None:
  274. """Terminate the engine process.
  275. Start the engine process by calling _createSocket()
  276. """
  277. self._slicing = False
  278. self._stored_layer_data = []
  279. if self._start_slice_job_build_plate in self._stored_optimized_layer_data:
  280. del self._stored_optimized_layer_data[self._start_slice_job_build_plate]
  281. if self._start_slice_job is not None:
  282. self._start_slice_job.cancel()
  283. self.slicingCancelled.emit()
  284. self.processingProgress.emit(0)
  285. Logger.log("d", "Attempting to kill the engine process")
  286. if CuraApplication.getInstance().getUseExternalBackend():
  287. return
  288. if self._process is not None: # type: ignore
  289. Logger.log("d", "Killing engine process")
  290. try:
  291. self._process.terminate() # type: ignore
  292. Logger.log("d", "Engine process is killed. Received return code %s", self._process.wait()) # type: ignore
  293. self._process = None # type: ignore
  294. except Exception as e: # terminating a process that is already terminating causes an exception, silently ignore this.
  295. Logger.log("d", "Exception occurred while trying to kill the engine %s", str(e))
  296. def _onStartSliceCompleted(self, job: StartSliceJob) -> None:
  297. """Event handler to call when the job to initiate the slicing process is
  298. completed.
  299. When the start slice job is successfully completed, it will be happily
  300. slicing. This function handles any errors that may occur during the
  301. bootstrapping of a slice job.
  302. :param job: The start slice job that was just finished.
  303. """
  304. if self._error_message:
  305. self._error_message.hide()
  306. # Note that cancelled slice jobs can still call this method.
  307. if self._start_slice_job is job:
  308. self._start_slice_job = None
  309. if job.isCancelled() or job.getError() or job.getResult() == StartJobResult.Error:
  310. self.setState(BackendState.Error)
  311. self.backendError.emit(job)
  312. return
  313. application = CuraApplication.getInstance()
  314. if job.getResult() == StartJobResult.MaterialIncompatible:
  315. if application.platformActivity:
  316. self._error_message = Message(catalog.i18nc("@info:status",
  317. "Unable to slice with the current material as it is incompatible with the selected machine or configuration."),
  318. title = catalog.i18nc("@info:title", "Unable to slice"),
  319. message_type = Message.MessageType.WARNING)
  320. self._error_message.show()
  321. self.setState(BackendState.Error)
  322. self.backendError.emit(job)
  323. else:
  324. self.setState(BackendState.NotStarted)
  325. return
  326. if job.getResult() == StartJobResult.SettingError:
  327. if application.platformActivity:
  328. if not self._global_container_stack:
  329. Logger.log("w", "Global container stack not assigned to CuraEngineBackend!")
  330. return
  331. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  332. error_keys = [] #type: List[str]
  333. for extruder in extruders:
  334. error_keys.extend(extruder.getErrorKeys())
  335. if not extruders:
  336. error_keys = self._global_container_stack.getErrorKeys()
  337. error_labels = set()
  338. for key in error_keys:
  339. for stack in [self._global_container_stack] + extruders: #Search all container stacks for the definition of this setting. Some are only in an extruder stack.
  340. definitions = cast(DefinitionContainerInterface, stack.getBottom()).findDefinitions(key = key)
  341. if definitions:
  342. break #Found it! No need to continue search.
  343. else: #No stack has a definition for this setting.
  344. Logger.log("w", "When checking settings for errors, unable to find definition for key: {key}".format(key = key))
  345. continue
  346. error_labels.add(definitions[0].label)
  347. self._error_message = Message(catalog.i18nc("@info:status",
  348. "Unable to slice with the current settings. The following settings have errors: {0}").format(", ".join(error_labels)),
  349. title = catalog.i18nc("@info:title", "Unable to slice"),
  350. message_type = Message.MessageType.WARNING)
  351. Logger.warning(f"Unable to slice with the current settings. The following settings have errors: {', '.join(error_labels)}")
  352. self._error_message.show()
  353. self.setState(BackendState.Error)
  354. self.backendError.emit(job)
  355. else:
  356. self.setState(BackendState.NotStarted)
  357. return
  358. elif job.getResult() == StartJobResult.ObjectSettingError:
  359. errors = {}
  360. for node in DepthFirstIterator(application.getController().getScene().getRoot()):
  361. stack = node.callDecoration("getStack")
  362. if not stack:
  363. continue
  364. for key in stack.getErrorKeys():
  365. if not self._global_container_stack:
  366. Logger.log("e", "CuraEngineBackend does not have global_container_stack assigned.")
  367. continue
  368. definition = cast(DefinitionContainerInterface, self._global_container_stack.getBottom()).findDefinitions(key = key)
  369. if not definition:
  370. Logger.log("e", "When checking settings for errors, unable to find definition for key {key} in per-object stack.".format(key = key))
  371. continue
  372. errors[key] = definition[0].label
  373. self._error_message = Message(catalog.i18nc("@info:status",
  374. "Unable to slice due to some per-model settings. The following settings have errors on one or more models: {error_labels}").format(error_labels = ", ".join(errors.values())),
  375. title = catalog.i18nc("@info:title", "Unable to slice"),
  376. message_type = Message.MessageType.WARNING)
  377. Logger.warning(f"Unable to slice due to per-object settings. The following settings have errors on one or more models: {', '.join(errors.values())}")
  378. self._error_message.show()
  379. self.setState(BackendState.Error)
  380. self.backendError.emit(job)
  381. return
  382. if job.getResult() == StartJobResult.BuildPlateError:
  383. if application.platformActivity:
  384. self._error_message = Message(catalog.i18nc("@info:status",
  385. "Unable to slice because the prime tower or prime position(s) are invalid."),
  386. title = catalog.i18nc("@info:title", "Unable to slice"),
  387. message_type = Message.MessageType.WARNING)
  388. self._error_message.show()
  389. self.setState(BackendState.Error)
  390. self.backendError.emit(job)
  391. return
  392. else:
  393. self.setState(BackendState.NotStarted)
  394. if job.getResult() == StartJobResult.ObjectsWithDisabledExtruder:
  395. self._error_message = Message(catalog.i18nc("@info:status",
  396. "Unable to slice because there are objects associated with disabled Extruder %s.") % job.getMessage(),
  397. title = catalog.i18nc("@info:title", "Unable to slice"),
  398. message_type = Message.MessageType.WARNING)
  399. self._error_message.show()
  400. self.setState(BackendState.Error)
  401. self.backendError.emit(job)
  402. return
  403. if job.getResult() == StartJobResult.NothingToSlice:
  404. if application.platformActivity:
  405. self._error_message = Message(catalog.i18nc("@info:status", "Please review settings and check if your models:"
  406. "\n- Fit within the build volume"
  407. "\n- Are assigned to an enabled extruder"
  408. "\n- Are not all set as modifier meshes"),
  409. title = catalog.i18nc("@info:title", "Unable to slice"),
  410. message_type = Message.MessageType.WARNING)
  411. self._error_message.show()
  412. self.setState(BackendState.Error)
  413. self.backendError.emit(job)
  414. else:
  415. self.setState(BackendState.NotStarted)
  416. self._invokeSlice()
  417. return
  418. # Preparation completed, send it to the backend.
  419. self._socket.sendMessage(job.getSliceMessage())
  420. # Notify the user that it's now up to the backend to do it's job
  421. self.setState(BackendState.Processing)
  422. if self._slice_start_time:
  423. Logger.log("d", "Sending slice message took %s seconds", time() - self._slice_start_time )
  424. def determineAutoSlicing(self) -> bool:
  425. """Determine enable or disable auto slicing. Return True for enable timer and False otherwise.
  426. It disables when:
  427. - preference auto slice is off
  428. - decorator isBlockSlicing is found (used in g-code reader)
  429. """
  430. enable_timer = True
  431. self._is_disabled = False
  432. if not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice"):
  433. enable_timer = False
  434. for node in DepthFirstIterator(self._scene.getRoot()):
  435. if node.callDecoration("isBlockSlicing"):
  436. enable_timer = False
  437. self.setState(BackendState.Disabled)
  438. self._is_disabled = True
  439. gcode_list = node.callDecoration("getGCodeList")
  440. if gcode_list is not None:
  441. self._scene.gcode_dict[node.callDecoration("getBuildPlateNumber")] = gcode_list #type: ignore #Because we generate this attribute dynamically.
  442. if self._use_timer == enable_timer:
  443. return self._use_timer
  444. if enable_timer:
  445. self.setState(BackendState.NotStarted)
  446. self.enableTimer()
  447. return True
  448. else:
  449. self.disableTimer()
  450. return False
  451. def _numObjectsPerBuildPlate(self) -> Dict[int, int]:
  452. """Return a dict with number of objects per build plate"""
  453. num_objects = defaultdict(int) #type: Dict[int, int]
  454. for node in DepthFirstIterator(self._scene.getRoot()):
  455. # Only count sliceable objects
  456. if node.callDecoration("isSliceable"):
  457. build_plate_number = node.callDecoration("getBuildPlateNumber")
  458. if build_plate_number is not None:
  459. num_objects[build_plate_number] += 1
  460. return num_objects
  461. def _onSceneChanged(self, source: SceneNode) -> None:
  462. """Listener for when the scene has changed.
  463. This should start a slice if the scene is now ready to slice.
  464. :param source: The scene node that was changed.
  465. """
  466. if not source.callDecoration("isSliceable") and source != self._scene.getRoot():
  467. return
  468. # This case checks if the source node is a node that contains GCode. In this case the
  469. # current layer data is removed so the previous data is not rendered - CURA-4821
  470. if source.callDecoration("isBlockSlicing") and source.callDecoration("getLayerData"):
  471. self._stored_optimized_layer_data = {}
  472. build_plate_changed = set()
  473. source_build_plate_number = source.callDecoration("getBuildPlateNumber")
  474. if source == self._scene.getRoot():
  475. # we got the root node
  476. num_objects = self._numObjectsPerBuildPlate()
  477. for build_plate_number in list(self._last_num_objects.keys()) + list(num_objects.keys()):
  478. if build_plate_number not in self._last_num_objects or num_objects[build_plate_number] != self._last_num_objects[build_plate_number]:
  479. self._last_num_objects[build_plate_number] = num_objects[build_plate_number]
  480. build_plate_changed.add(build_plate_number)
  481. else:
  482. # we got a single scenenode
  483. if not source.callDecoration("isGroup"):
  484. mesh_data = source.getMeshData()
  485. if mesh_data is None or mesh_data.getVertices() is None:
  486. return
  487. # There are some SceneNodes that do not have any build plate associated, then do not add to the list.
  488. if source_build_plate_number is not None:
  489. build_plate_changed.add(source_build_plate_number)
  490. if not build_plate_changed:
  491. return
  492. if self._tool_active:
  493. # do it later, each source only has to be done once
  494. if source not in self._postponed_scene_change_sources:
  495. self._postponed_scene_change_sources.append(source)
  496. return
  497. self.stopSlicing()
  498. for build_plate_number in build_plate_changed:
  499. if build_plate_number not in self._build_plates_to_be_sliced:
  500. self._build_plates_to_be_sliced.append(build_plate_number)
  501. self.printDurationMessage.emit(source_build_plate_number, {}, [])
  502. self.processingProgress.emit(0.0)
  503. self._clearLayerData(build_plate_changed)
  504. self._invokeSlice()
  505. def _onSocketError(self, error: Arcus.Error) -> None:
  506. """Called when an error occurs in the socket connection towards the engine.
  507. :param error: The exception that occurred.
  508. """
  509. if CuraApplication.getInstance().isShuttingDown():
  510. return
  511. super()._onSocketError(error)
  512. if error.getErrorCode() == Arcus.ErrorCode.Debug:
  513. return
  514. self._terminate()
  515. self._createSocket()
  516. if error.getErrorCode() not in [Arcus.ErrorCode.BindFailedError, Arcus.ErrorCode.ConnectionResetError, Arcus.ErrorCode.Debug]:
  517. Logger.log("w", "A socket error caused the connection to be reset")
  518. # _terminate()' function sets the job status to 'cancel', after reconnecting to another Port the job status
  519. # needs to be updated. Otherwise backendState is "Unable To Slice"
  520. if error.getErrorCode() == Arcus.ErrorCode.BindFailedError and self._start_slice_job is not None:
  521. self._start_slice_job.setIsCancelled(False)
  522. # Check if there's any slicable object in the scene.
  523. def hasSlicableObject(self) -> bool:
  524. has_slicable = False
  525. for node in DepthFirstIterator(self._scene.getRoot()):
  526. if node.callDecoration("isSliceable"):
  527. has_slicable = True
  528. break
  529. return has_slicable
  530. def _clearLayerData(self, build_plate_numbers: Set = None) -> None:
  531. """Remove old layer data (if any)"""
  532. # Clear out any old gcode
  533. self._scene.gcode_dict = {} # type: ignore
  534. for node in DepthFirstIterator(self._scene.getRoot()):
  535. if node.callDecoration("getLayerData"):
  536. if not build_plate_numbers or node.callDecoration("getBuildPlateNumber") in build_plate_numbers:
  537. # We can assume that all nodes have a parent as we're looping through the scene (and filter out root)
  538. cast(SceneNode, node.getParent()).removeChild(node)
  539. def markSliceAll(self) -> None:
  540. for build_plate_number in range(CuraApplication.getInstance().getMultiBuildPlateModel().maxBuildPlate + 1):
  541. if build_plate_number not in self._build_plates_to_be_sliced:
  542. self._build_plates_to_be_sliced.append(build_plate_number)
  543. def needsSlicing(self) -> None:
  544. """Convenient function: mark everything to slice, emit state and clear layer data"""
  545. # CURA-6604: If there's no slicable object, do not (try to) trigger slice, which will clear all the current
  546. # gcode. This can break Gcode file loading if it tries to remove it afterwards.
  547. if not self.hasSlicableObject():
  548. return
  549. self.determineAutoSlicing()
  550. self.stopSlicing()
  551. self.markSliceAll()
  552. self.processingProgress.emit(0.0)
  553. if not self._use_timer:
  554. # With manually having to slice, we want to clear the old invalid layer data.
  555. self._clearLayerData()
  556. def _onSettingChanged(self, instance: SettingInstance, property: str) -> None:
  557. """A setting has changed, so check if we must reslice.
  558. :param instance: The setting instance that has changed.
  559. :param property: The property of the setting instance that has changed.
  560. """
  561. if property == "value": # Only reslice if the value has changed.
  562. self.needsSlicing()
  563. self._onChanged()
  564. elif property == "validationState":
  565. if self._use_timer:
  566. self._change_timer.stop()
  567. def _onStackErrorCheckFinished(self) -> None:
  568. self.determineAutoSlicing()
  569. if self._is_disabled:
  570. return
  571. if not self._slicing and self._build_plates_to_be_sliced:
  572. self.needsSlicing()
  573. self._onChanged()
  574. def _onLayerMessage(self, message: Arcus.PythonMessage) -> None:
  575. """Called when a sliced layer data message is received from the engine.
  576. :param message: The protobuf message containing sliced layer data.
  577. """
  578. self._stored_layer_data.append(message)
  579. def _onOptimizedLayerMessage(self, message: Arcus.PythonMessage) -> None:
  580. """Called when an optimized sliced layer data message is received from the engine.
  581. :param message: The protobuf message containing sliced layer data.
  582. """
  583. if self._start_slice_job_build_plate is not None:
  584. if self._start_slice_job_build_plate not in self._stored_optimized_layer_data:
  585. self._stored_optimized_layer_data[self._start_slice_job_build_plate] = []
  586. self._stored_optimized_layer_data[self._start_slice_job_build_plate].append(message)
  587. def _onProgressMessage(self, message: Arcus.PythonMessage) -> None:
  588. """Called when a progress message is received from the engine.
  589. :param message: The protobuf message containing the slicing progress.
  590. """
  591. self.processingProgress.emit(message.amount)
  592. self.setState(BackendState.Processing)
  593. def _invokeSlice(self) -> None:
  594. if self._use_timer:
  595. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  596. # otherwise business as usual
  597. if self._machine_error_checker is None:
  598. self._change_timer.stop()
  599. return
  600. if self._machine_error_checker.needToWaitForResult:
  601. self._change_timer.stop()
  602. else:
  603. self._change_timer.start()
  604. def _onSlicingFinishedMessage(self, message: Arcus.PythonMessage) -> None:
  605. """Called when the engine sends a message that slicing is finished.
  606. :param message: The protobuf message signalling that slicing is finished.
  607. """
  608. self.setState(BackendState.Done)
  609. self.processingProgress.emit(1.0)
  610. try:
  611. gcode_list = self._scene.gcode_dict[self._start_slice_job_build_plate] #type: ignore #Because we generate this attribute dynamically.
  612. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  613. gcode_list = []
  614. application = CuraApplication.getInstance()
  615. for index, line in enumerate(gcode_list):
  616. replaced = line.replace("{print_time}", str(application.getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)))
  617. replaced = replaced.replace("{filament_amount}", str(application.getPrintInformation().materialLengths))
  618. replaced = replaced.replace("{filament_weight}", str(application.getPrintInformation().materialWeights))
  619. replaced = replaced.replace("{filament_cost}", str(application.getPrintInformation().materialCosts))
  620. replaced = replaced.replace("{jobname}", str(application.getPrintInformation().jobName))
  621. gcode_list[index] = replaced
  622. self._slicing = False
  623. if self._slice_start_time:
  624. Logger.log("d", "Slicing took %s seconds", time() - self._slice_start_time )
  625. Logger.log("d", "Number of models per buildplate: %s", dict(self._numObjectsPerBuildPlate()))
  626. # See if we need to process the sliced layers job.
  627. active_build_plate = application.getMultiBuildPlateModel().activeBuildPlate
  628. if (
  629. self._layer_view_active and
  630. (self._process_layers_job is None or not self._process_layers_job.isRunning()) and
  631. active_build_plate == self._start_slice_job_build_plate and
  632. active_build_plate not in self._build_plates_to_be_sliced):
  633. self._startProcessSlicedLayersJob(active_build_plate)
  634. # self._onActiveViewChanged()
  635. self._start_slice_job_build_plate = None
  636. Logger.log("d", "See if there is more to slice...")
  637. # Somehow this results in an Arcus Error
  638. # self.slice()
  639. # Call slice again using the timer, allowing the backend to restart
  640. if self._build_plates_to_be_sliced:
  641. self.enableTimer() # manually enable timer to be able to invoke slice, also when in manual slice mode
  642. self._invokeSlice()
  643. def _onGCodeLayerMessage(self, message: Arcus.PythonMessage) -> None:
  644. """Called when a g-code message is received from the engine.
  645. :param message: The protobuf message containing g-code, encoded as UTF-8.
  646. """
  647. try:
  648. self._scene.gcode_dict[self._start_slice_job_build_plate].append(message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  649. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  650. pass # Throw the message away.
  651. def _onGCodePrefixMessage(self, message: Arcus.PythonMessage) -> None:
  652. """Called when a g-code prefix message is received from the engine.
  653. :param message: The protobuf message containing the g-code prefix,
  654. encoded as UTF-8.
  655. """
  656. try:
  657. self._scene.gcode_dict[self._start_slice_job_build_plate].insert(0, message.data.decode("utf-8", "replace")) #type: ignore #Because we generate this attribute dynamically.
  658. except KeyError: # Can occur if the g-code has been cleared while a slice message is still arriving from the other end.
  659. pass # Throw the message away.
  660. def _onSliceUUIDMessage(self, message: Arcus.PythonMessage) -> None:
  661. application = CuraApplication.getInstance()
  662. application.getPrintInformation().slice_uuid = message.slice_uuid
  663. def _createSocket(self, protocol_file: str = None) -> None:
  664. """Creates a new socket connection."""
  665. if not protocol_file:
  666. if not self.getPluginId():
  667. Logger.error("Can't create socket before CuraEngineBackend plug-in is registered.")
  668. return
  669. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  670. if not plugin_path:
  671. Logger.error("Could not get plugin path!", self.getPluginId())
  672. return
  673. protocol_file = os.path.abspath(os.path.join(plugin_path, "Cura.proto"))
  674. super()._createSocket(protocol_file)
  675. self._engine_is_fresh = True
  676. def _onChanged(self, *args: Any, **kwargs: Any) -> None:
  677. """Called when anything has changed to the stuff that needs to be sliced.
  678. This indicates that we should probably re-slice soon.
  679. """
  680. self.needsSlicing()
  681. if self._use_timer:
  682. # if the error check is scheduled, wait for the error check finish signal to trigger auto-slice,
  683. # otherwise business as usual
  684. if self._machine_error_checker is None:
  685. self._change_timer.stop()
  686. return
  687. if self._machine_error_checker.needToWaitForResult:
  688. self._change_timer.stop()
  689. else:
  690. self._change_timer.start()
  691. def _onPrintTimeMaterialEstimates(self, message: Arcus.PythonMessage) -> None:
  692. """Called when a print time message is received from the engine.
  693. :param message: The protobuf message containing the print time per feature and
  694. material amount per extruder
  695. """
  696. material_amounts = []
  697. for index in range(message.repeatedMessageCount("materialEstimates")):
  698. material_amounts.append(message.getRepeatedMessage("materialEstimates", index).material_amount)
  699. times = self._parseMessagePrintTimes(message)
  700. self.printDurationMessage.emit(self._start_slice_job_build_plate, times, material_amounts)
  701. def _parseMessagePrintTimes(self, message: Arcus.PythonMessage) -> Dict[str, float]:
  702. """Called for parsing message to retrieve estimated time per feature
  703. :param message: The protobuf message containing the print time per feature
  704. """
  705. result = {
  706. "inset_0": message.time_inset_0,
  707. "inset_x": message.time_inset_x,
  708. "skin": message.time_skin,
  709. "infill": message.time_infill,
  710. "support_infill": message.time_support_infill,
  711. "support_interface": message.time_support_interface,
  712. "support": message.time_support,
  713. "skirt": message.time_skirt,
  714. "prime_tower": message.time_prime_tower,
  715. "travel": message.time_travel,
  716. "retract": message.time_retract,
  717. "none": message.time_none
  718. }
  719. return result
  720. def _onBackendConnected(self) -> None:
  721. """Called when the back-end connects to the front-end."""
  722. if self._restart:
  723. self._restart = False
  724. self._onChanged()
  725. def _onToolOperationStarted(self, tool: Tool) -> None:
  726. """Called when the user starts using some tool.
  727. When the user starts using a tool, we should pause slicing to prevent
  728. continuously slicing while the user is dragging some tool handle.
  729. :param tool: The tool that the user is using.
  730. """
  731. self._tool_active = True # Do not react on scene change
  732. self.disableTimer()
  733. # Restart engine as soon as possible, we know we want to slice afterwards
  734. if not self._engine_is_fresh:
  735. self._terminate()
  736. self._createSocket()
  737. def _onToolOperationStopped(self, tool: Tool) -> None:
  738. """Called when the user stops using some tool.
  739. This indicates that we can safely start slicing again.
  740. :param tool: The tool that the user was using.
  741. """
  742. self._tool_active = False # React on scene change again
  743. self.determineAutoSlicing() # Switch timer on if appropriate
  744. # Process all the postponed scene changes
  745. while self._postponed_scene_change_sources:
  746. source = self._postponed_scene_change_sources.pop(0)
  747. self._onSceneChanged(source)
  748. def _startProcessSlicedLayersJob(self, build_plate_number: int) -> None:
  749. self._process_layers_job = ProcessSlicedLayersJob(self._stored_optimized_layer_data[build_plate_number])
  750. self._process_layers_job.setBuildPlate(build_plate_number)
  751. self._process_layers_job.finished.connect(self._onProcessLayersFinished)
  752. self._process_layers_job.start()
  753. def _onActiveViewChanged(self) -> None:
  754. """Called when the user changes the active view mode."""
  755. view = CuraApplication.getInstance().getController().getActiveView()
  756. if view:
  757. active_build_plate = CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  758. if view.getPluginId() == "SimulationView": # If switching to layer view, we should process the layers if that hasn't been done yet.
  759. self._layer_view_active = True
  760. # There is data and we're not slicing at the moment
  761. # if we are slicing, there is no need to re-calculate the data as it will be invalid in a moment.
  762. # TODO: what build plate I am slicing
  763. if (active_build_plate in self._stored_optimized_layer_data and
  764. not self._slicing and
  765. not self._process_layers_job and
  766. active_build_plate not in self._build_plates_to_be_sliced):
  767. self._startProcessSlicedLayersJob(active_build_plate)
  768. else:
  769. self._layer_view_active = False
  770. def _onBackendQuit(self) -> None:
  771. """Called when the back-end self-terminates.
  772. We should reset our state and start listening for new connections.
  773. """
  774. if not self._restart:
  775. if self._process: # type: ignore
  776. return_code = self._process.wait()
  777. if return_code != 0:
  778. Logger.log("e", f"Backend exited abnormally with return code {return_code}!")
  779. self._slicing_error_message.show()
  780. self.setState(BackendState.Error)
  781. self.stopSlicing()
  782. else:
  783. Logger.log("d", "Backend finished slicing. Resetting process and socket.")
  784. self._process = None # type: ignore
  785. def _reportBackendError(self, _message_id: str, _action_id: str) -> None:
  786. """
  787. Triggered when the user wants to report an error in the back-end.
  788. """
  789. QDesktopServices.openUrl(QUrl("https://github.com/Ultimaker/Cura/issues/new/choose"))
  790. def _onGlobalStackChanged(self) -> None:
  791. """Called when the global container stack changes"""
  792. if self._global_container_stack:
  793. self._global_container_stack.propertyChanged.disconnect(self._onSettingChanged)
  794. self._global_container_stack.containersChanged.disconnect(self._onChanged)
  795. for extruder in self._global_container_stack.extruderList:
  796. extruder.propertyChanged.disconnect(self._onSettingChanged)
  797. extruder.containersChanged.disconnect(self._onChanged)
  798. self._global_container_stack = CuraApplication.getInstance().getMachineManager().activeMachine
  799. if self._global_container_stack:
  800. self._global_container_stack.propertyChanged.connect(self._onSettingChanged) # Note: Only starts slicing when the value changed.
  801. self._global_container_stack.containersChanged.connect(self._onChanged)
  802. for extruder in self._global_container_stack.extruderList:
  803. extruder.propertyChanged.connect(self._onSettingChanged)
  804. extruder.containersChanged.connect(self._onChanged)
  805. self._onChanged()
  806. def _onProcessLayersFinished(self, job: ProcessSlicedLayersJob) -> None:
  807. if job.getBuildPlate() in self._stored_optimized_layer_data:
  808. del self._stored_optimized_layer_data[job.getBuildPlate()]
  809. else:
  810. Logger.log("w", "The optimized layer data was already deleted for buildplate %s", job.getBuildPlate())
  811. self._process_layers_job = None
  812. Logger.log("d", "See if there is more to slice(2)...")
  813. self._invokeSlice()
  814. def enableTimer(self) -> None:
  815. """Connect slice function to timer."""
  816. if not self._use_timer:
  817. self._change_timer.timeout.connect(self.slice)
  818. self._use_timer = True
  819. def disableTimer(self) -> None:
  820. """Disconnect slice function from timer.
  821. This means that slicing will not be triggered automatically
  822. """
  823. if self._use_timer:
  824. self._use_timer = False
  825. self._change_timer.timeout.disconnect(self.slice)
  826. def _onPreferencesChanged(self, preference: str) -> None:
  827. if preference != "general/auto_slice":
  828. return
  829. auto_slice = self.determineAutoSlicing()
  830. if auto_slice:
  831. self._change_timer.start()
  832. def tickle(self) -> None:
  833. """Tickle the backend so in case of auto slicing, it starts the timer."""
  834. if self._use_timer:
  835. self._change_timer.start()
  836. def _extruderChanged(self) -> None:
  837. if not self._multi_build_plate_model:
  838. Logger.log("w", "CuraEngineBackend does not have multi_build_plate_model assigned!")
  839. return
  840. for build_plate_number in range(self._multi_build_plate_model.maxBuildPlate + 1):
  841. if build_plate_number not in self._build_plates_to_be_sliced:
  842. self._build_plates_to_be_sliced.append(build_plate_number)
  843. self._invokeSlice()