CuraEngineBackend.py 52 KB

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