CuraEngineBackend.py 51 KB

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