CuraEngineBackend.py 52 KB

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