BuildVolume.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. # Copyright (c) 2021 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import numpy
  4. import math
  5. from typing import List, Optional, TYPE_CHECKING, Any, Set, cast, Iterable, Dict
  6. from UM.Logger import Logger
  7. from UM.Mesh.MeshData import MeshData
  8. from UM.Mesh.MeshBuilder import MeshBuilder
  9. from UM.Application import Application #To modify the maximum zoom level.
  10. from UM.i18n import i18nCatalog
  11. from UM.Scene.Platform import Platform
  12. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  13. from UM.Scene.SceneNode import SceneNode
  14. from UM.Resources import Resources
  15. from UM.Math.Vector import Vector
  16. from UM.Math.Matrix import Matrix
  17. from UM.Math.Color import Color
  18. from UM.Math.AxisAlignedBox import AxisAlignedBox
  19. from UM.Math.Polygon import Polygon
  20. from UM.Message import Message
  21. from UM.Signal import Signal
  22. from UM.View.RenderBatch import RenderBatch
  23. from UM.View.GL.OpenGL import OpenGL
  24. from cura.Settings.GlobalStack import GlobalStack
  25. from cura.Scene.CuraSceneNode import CuraSceneNode
  26. from cura.Settings.ExtruderManager import ExtruderManager
  27. from PyQt6.QtCore import QTimer
  28. if TYPE_CHECKING:
  29. from cura.CuraApplication import CuraApplication
  30. from cura.Settings.ExtruderStack import ExtruderStack
  31. from UM.Settings.ContainerStack import ContainerStack
  32. catalog = i18nCatalog("cura")
  33. # Radius of disallowed area in mm around prime. I.e. how much distance to keep from prime position.
  34. PRIME_CLEARANCE = 6.5
  35. class BuildVolume(SceneNode):
  36. """Build volume is a special kind of node that is responsible for rendering the printable area & disallowed areas."""
  37. raftThicknessChanged = Signal()
  38. def __init__(self, application: "CuraApplication", parent: Optional[SceneNode] = None) -> None:
  39. super().__init__(parent)
  40. self._application = application
  41. self._machine_manager = self._application.getMachineManager()
  42. self._volume_outline_color = None # type: Optional[Color]
  43. self._x_axis_color = None # type: Optional[Color]
  44. self._y_axis_color = None # type: Optional[Color]
  45. self._z_axis_color = None # type: Optional[Color]
  46. self._disallowed_area_color = None # type: Optional[Color]
  47. self._error_area_color = None # type: Optional[Color]
  48. self._width = 0 # type: float
  49. self._height = 0 # type: float
  50. self._depth = 0 # type: float
  51. self._shape = "" # type: str
  52. self._scale_vector = Vector(1.0, 1.0, 1.0)
  53. self._shader = None
  54. self._origin_mesh = None # type: Optional[MeshData]
  55. self._origin_line_length = 20
  56. self._origin_line_width = 1
  57. self._enabled = False
  58. self._grid_mesh = None # type: Optional[MeshData]
  59. self._grid_shader = None
  60. self._disallowed_areas = [] # type: List[Polygon]
  61. self._disallowed_areas_no_brim = [] # type: List[Polygon]
  62. self._disallowed_area_mesh = None # type: Optional[MeshData]
  63. self._disallowed_area_size = 0.
  64. self._error_areas = [] # type: List[Polygon]
  65. self._error_mesh = None # type: Optional[MeshData]
  66. self.setCalculateBoundingBox(False)
  67. self._volume_aabb = None # type: Optional[AxisAlignedBox]
  68. self._raft_thickness = 0.0
  69. self._extra_z_clearance = 0.0
  70. self._adhesion_type = None # type: Any
  71. self._platform = Platform(self)
  72. self._edge_disallowed_size = None
  73. self._build_volume_message = Message(catalog.i18nc("@info:status",
  74. "The build volume height has been reduced due to the value of the"
  75. " \"Print Sequence\" setting to prevent the gantry from colliding"
  76. " with printed models."),
  77. title = catalog.i18nc("@info:title", "Build Volume"),
  78. message_type = Message.MessageType.WARNING)
  79. self._global_container_stack = None # type: Optional[GlobalStack]
  80. self._stack_change_timer = QTimer()
  81. self._stack_change_timer.setInterval(100)
  82. self._stack_change_timer.setSingleShot(True)
  83. self._stack_change_timer.timeout.connect(self._onStackChangeTimerFinished)
  84. self._application.globalContainerStackChanged.connect(self._onStackChanged)
  85. self._engine_ready = False
  86. self._application.engineCreatedSignal.connect(self._onEngineCreated)
  87. self._has_errors = False
  88. self._application.getController().getScene().sceneChanged.connect(self._onSceneChanged)
  89. # Objects loaded at the moment. We are connected to the property changed events of these objects.
  90. self._scene_objects = set() # type: Set[SceneNode]
  91. # Number of toplevel printable meshes. If there is more than one, the build volume needs to take account of the gantry height in One at a Time printing.
  92. self._root_printable_object_count = 0
  93. self._scene_change_timer = QTimer()
  94. self._scene_change_timer.setInterval(200)
  95. self._scene_change_timer.setSingleShot(True)
  96. self._scene_change_timer.timeout.connect(self._onSceneChangeTimerFinished)
  97. self._setting_change_timer = QTimer()
  98. self._setting_change_timer.setInterval(150)
  99. self._setting_change_timer.setSingleShot(True)
  100. self._setting_change_timer.timeout.connect(self._onSettingChangeTimerFinished)
  101. # Must be after setting _build_volume_message, apparently that is used in getMachineManager.
  102. # activeQualityChanged is always emitted after setActiveVariant, setActiveMaterial and setActiveQuality.
  103. # Therefore this works.
  104. self._machine_manager.activeQualityChanged.connect(self._onStackChanged)
  105. # Enable and disable extruder
  106. self._machine_manager.extruderChanged.connect(self.updateNodeBoundaryCheck)
  107. # List of settings which were updated
  108. self._changed_settings_since_last_rebuild = [] # type: List[str]
  109. def _onSceneChanged(self, source):
  110. if self._global_container_stack:
  111. # Ignore anything that is not something we can slice in the first place!
  112. if source.callDecoration("isSliceable"):
  113. self._scene_change_timer.start()
  114. def _onSceneChangeTimerFinished(self):
  115. root = self._application.getController().getScene().getRoot()
  116. new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable"))
  117. if new_scene_objects != self._scene_objects:
  118. for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
  119. self._updateNodeListeners(node)
  120. node.decoratorsChanged.connect(self._updateNodeListeners) # Make sure that decoration changes afterwards also receive the same treatment
  121. for node in self._scene_objects - new_scene_objects: #Nodes that were removed from the scene.
  122. per_mesh_stack = node.callDecoration("getStack")
  123. if per_mesh_stack:
  124. per_mesh_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  125. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  126. if active_extruder_changed is not None:
  127. node.callDecoration("getActiveExtruderChangedSignal").disconnect(self._updateDisallowedAreasAndRebuild)
  128. node.decoratorsChanged.disconnect(self._updateNodeListeners)
  129. self.rebuild()
  130. self._scene_objects = new_scene_objects
  131. # This also needs to be called when objects are grouped/ungrouped,
  132. # which is not reflected in a change in self._scene_objects
  133. self._updateRootPrintableObjectCount()
  134. def _updateRootPrintableObjectCount(self):
  135. # Get the number of models in the scene root, excluding modifier meshes and counting grouped models as 1
  136. root = self._application.getController().getScene().getRoot()
  137. scene_objects = set(node for node in BreadthFirstIterator(root) if node.callDecoration("isSliceable") or node.callDecoration("isGroup"))
  138. new_root_printable_object_count = len(list(node for node in scene_objects if node.getParent() == root and not (
  139. node_stack := node.callDecoration("getStack") and (
  140. node.callDecoration("getStack").getProperty("anti_overhang_mesh", "value") or
  141. node.callDecoration("getStack").getProperty("support_mesh", "value") or
  142. node.callDecoration("getStack").getProperty("cutting_mesh", "value") or
  143. node.callDecoration("getStack").getProperty("infill_mesh", "value")
  144. ))
  145. ))
  146. if new_root_printable_object_count != self._root_printable_object_count:
  147. self._root_printable_object_count = new_root_printable_object_count
  148. self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
  149. def _updateNodeListeners(self, node: SceneNode):
  150. """Updates the listeners that listen for changes in per-mesh stacks.
  151. :param node: The node for which the decorators changed.
  152. """
  153. per_mesh_stack = node.callDecoration("getStack")
  154. if per_mesh_stack:
  155. per_mesh_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  156. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  157. if active_extruder_changed is not None:
  158. active_extruder_changed.connect(self._updateDisallowedAreasAndRebuild)
  159. def setWidth(self, width: float) -> None:
  160. self._width = width
  161. def getWidth(self) -> float:
  162. return self._width
  163. def setHeight(self, height: float) -> None:
  164. self._height = height
  165. def getHeight(self) -> float:
  166. return self._height
  167. def setDepth(self, depth: float) -> None:
  168. self._depth = depth
  169. def getDepth(self) -> float:
  170. return self._depth
  171. def setShape(self, shape: str) -> None:
  172. if shape:
  173. self._shape = shape
  174. def getShape(self) -> str:
  175. return self._shape
  176. def getDiagonalSize(self) -> float:
  177. """Get the length of the 3D diagonal through the build volume.
  178. This gives a sense of the scale of the build volume in general.
  179. :return: length of the 3D diagonal through the build volume
  180. """
  181. return math.sqrt(self._width * self._width + self._height * self._height + self._depth * self._depth)
  182. def getDisallowedAreas(self) -> List[Polygon]:
  183. return self._disallowed_areas
  184. def getDisallowedAreasNoBrim(self) -> List[Polygon]:
  185. return self._disallowed_areas_no_brim
  186. def setDisallowedAreas(self, areas: List[Polygon]):
  187. self._disallowed_areas = areas
  188. def render(self, renderer):
  189. if not self.getMeshData() or not self.isVisible():
  190. return True
  191. theme = self._application.getTheme()
  192. if not self._shader:
  193. self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
  194. self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
  195. self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate_grid").getRgb()))
  196. self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_grid_minor").getRgb()))
  197. plate_color = Color(*theme.getColor("buildplate").getRgb())
  198. if self._global_container_stack.getMetaDataEntry("has_textured_buildplate", False):
  199. plate_color.setA(0.5)
  200. self._grid_shader.setUniformValue("u_plateColor", plate_color)
  201. renderer.queueNode(self, mode = RenderBatch.RenderMode.Lines)
  202. renderer.queueNode(self, mesh = self._origin_mesh, backface_cull = True)
  203. renderer.queueNode(self, mesh = self._grid_mesh, shader = self._grid_shader, backface_cull = True, transparent = True, sort = -10)
  204. if self._disallowed_area_mesh:
  205. renderer.queueNode(self, mesh = self._disallowed_area_mesh, shader = self._shader, transparent = True, backface_cull = True, sort = -5)
  206. if self._error_mesh:
  207. renderer.queueNode(self, mesh=self._error_mesh, shader=self._shader, transparent=True,
  208. backface_cull=True, sort=-8)
  209. return True
  210. def updateNodeBoundaryCheck(self):
  211. """For every sliceable node, update node._outside_buildarea"""
  212. if not self._global_container_stack:
  213. return
  214. root = self._application.getController().getScene().getRoot()
  215. nodes = cast(List[SceneNode], list(cast(Iterable, BreadthFirstIterator(root))))
  216. group_nodes = [] # type: List[SceneNode]
  217. build_volume_bounding_box = self.getBoundingBox()
  218. if build_volume_bounding_box:
  219. # It's over 9000!
  220. # We set this to a very low number, as we do allow models to intersect the build plate.
  221. # This means the model gets cut off at the build plate.
  222. build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
  223. else:
  224. # No bounding box. This is triggered when running Cura from command line with a model for the first time
  225. # In that situation there is a model, but no machine (and therefore no build volume.
  226. return
  227. for node in nodes:
  228. # Need to check group nodes later
  229. if node.callDecoration("isGroup"):
  230. group_nodes.append(node) # Keep list of affected group_nodes
  231. if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
  232. if not isinstance(node, CuraSceneNode):
  233. continue
  234. if node.collidesWithBbox(build_volume_bounding_box):
  235. node.setOutsideBuildArea(True)
  236. continue
  237. if node.collidesWithAreas(self.getDisallowedAreas()):
  238. node.setOutsideBuildArea(True)
  239. continue
  240. # If the entire node is below the build plate, still mark it as outside.
  241. node_bounding_box = node.getBoundingBox()
  242. if node_bounding_box and node_bounding_box.top < 0 and not node.getParent().callDecoration("isGroup"):
  243. node.setOutsideBuildArea(True)
  244. continue
  245. # Mark the node as outside build volume if the set extruder is disabled
  246. extruder_position = node.callDecoration("getActiveExtruderPosition")
  247. try:
  248. if not self._global_container_stack.extruderList[int(extruder_position)].isEnabled and not node.callDecoration("isGroup"):
  249. node.setOutsideBuildArea(True)
  250. continue
  251. except IndexError: # Happens when the extruder list is too short. We're not done building the printer in memory yet.
  252. continue
  253. except TypeError: # Happens when extruder_position is None. This object has no extruder decoration.
  254. continue
  255. node.setOutsideBuildArea(False)
  256. # Group nodes should override the _outside_buildarea property of their children.
  257. for group_node in group_nodes:
  258. children = group_node.getAllChildren()
  259. # Check if one or more children are non-printable and if so, set the parent as non-printable:
  260. for child_node in children:
  261. if child_node.isOutsideBuildArea():
  262. group_node.setOutsideBuildArea(True)
  263. break
  264. # Apply results of the check to all children of the group:
  265. for child_node in children:
  266. child_node.setOutsideBuildArea(group_node.isOutsideBuildArea())
  267. def checkBoundsAndUpdate(self, node: CuraSceneNode, bounds: Optional[AxisAlignedBox] = None) -> None:
  268. """Update the outsideBuildArea of a single node, given bounds or current build volume
  269. :param node: single node
  270. :param bounds: bounds or current build volume
  271. """
  272. if not isinstance(node, CuraSceneNode) or self._global_container_stack is None:
  273. return
  274. if bounds is None:
  275. build_volume_bounding_box = self.getBoundingBox()
  276. if build_volume_bounding_box:
  277. # It's over 9000!
  278. build_volume_bounding_box = build_volume_bounding_box.set(bottom=-9001)
  279. else:
  280. # No bounding box. This is triggered when running Cura from command line with a model for the first time
  281. # In that situation there is a model, but no machine (and therefore no build volume.
  282. return
  283. else:
  284. build_volume_bounding_box = bounds
  285. if node.callDecoration("isSliceable") or node.callDecoration("isGroup"):
  286. if node.collidesWithBbox(build_volume_bounding_box):
  287. node.setOutsideBuildArea(True)
  288. return
  289. if node.collidesWithAreas(self.getDisallowedAreas()):
  290. node.setOutsideBuildArea(True)
  291. return
  292. # Mark the node as outside build volume if the set extruder is disabled
  293. extruder_position = node.callDecoration("getActiveExtruderPosition")
  294. try:
  295. if not self._global_container_stack.extruderList[int(extruder_position)].isEnabled:
  296. node.setOutsideBuildArea(True)
  297. return
  298. except IndexError:
  299. # If the extruder doesn't exist, also mark it as unprintable.
  300. node.setOutsideBuildArea(True)
  301. return
  302. node.setOutsideBuildArea(False)
  303. def _buildGridMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d:float, z_fight_distance: float) -> MeshData:
  304. mb = MeshBuilder()
  305. if self._shape != "elliptic":
  306. # Build plate grid mesh
  307. mb.addQuad(
  308. Vector(min_w, min_h - z_fight_distance, min_d),
  309. Vector(max_w, min_h - z_fight_distance, min_d),
  310. Vector(max_w, min_h - z_fight_distance, max_d),
  311. Vector(min_w, min_h - z_fight_distance, max_d)
  312. )
  313. for n in range(0, 6):
  314. v = mb.getVertex(n)
  315. mb.setVertexUVCoordinates(n, v[0], v[2])
  316. return mb.build()
  317. else:
  318. aspect = 1.0
  319. scale_matrix = Matrix()
  320. if self._width != 0:
  321. # Scale circular meshes by aspect ratio if width != height
  322. aspect = self._depth / self._width
  323. scale_matrix.compose(scale=Vector(1, 1, aspect))
  324. mb.addVertex(0, min_h - z_fight_distance, 0)
  325. mb.addArc(max_w, Vector.Unit_Y, center=Vector(0, min_h - z_fight_distance, 0))
  326. sections = mb.getVertexCount() - 1 # Center point is not an arc section
  327. indices = []
  328. for n in range(0, sections - 1):
  329. indices.append([0, n + 2, n + 1])
  330. mb.addIndices(numpy.asarray(indices, dtype=numpy.int32))
  331. mb.calculateNormals()
  332. for n in range(0, mb.getVertexCount()):
  333. v = mb.getVertex(n)
  334. mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
  335. return mb.build().getTransformed(scale_matrix)
  336. def _buildMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d:float, z_fight_distance: float) -> MeshData:
  337. if self._shape != "elliptic":
  338. # Outline 'cube' of the build volume
  339. mb = MeshBuilder()
  340. mb.addLine(Vector(min_w, min_h, min_d), Vector(max_w, min_h, min_d), color = self._volume_outline_color)
  341. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, max_h, min_d), color = self._volume_outline_color)
  342. mb.addLine(Vector(min_w, max_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  343. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  344. mb.addLine(Vector(min_w, min_h, max_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  345. mb.addLine(Vector(min_w, min_h, max_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  346. mb.addLine(Vector(min_w, max_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  347. mb.addLine(Vector(max_w, min_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  348. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, min_h, max_d), color = self._volume_outline_color)
  349. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  350. mb.addLine(Vector(min_w, max_h, min_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  351. mb.addLine(Vector(max_w, max_h, min_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  352. return mb.build()
  353. else:
  354. # Bottom and top 'ellipse' of the build volume
  355. scale_matrix = Matrix()
  356. if self._width != 0:
  357. # Scale circular meshes by aspect ratio if width != height
  358. aspect = self._depth / self._width
  359. scale_matrix.compose(scale = Vector(1, 1, aspect))
  360. mb = MeshBuilder()
  361. mb.addArc(max_w, Vector.Unit_Y, center = (0, min_h - z_fight_distance, 0), color = self._volume_outline_color)
  362. mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self._volume_outline_color)
  363. return mb.build().getTransformed(scale_matrix)
  364. def _buildOriginMesh(self, origin: Vector) -> MeshData:
  365. mb = MeshBuilder()
  366. mb.addCube(
  367. width=self._origin_line_length,
  368. height=self._origin_line_width,
  369. depth=self._origin_line_width,
  370. center=origin + Vector(self._origin_line_length / 2, 0, 0),
  371. color=self._x_axis_color
  372. )
  373. mb.addCube(
  374. width=self._origin_line_width,
  375. height=self._origin_line_length,
  376. depth=self._origin_line_width,
  377. center=origin + Vector(0, self._origin_line_length / 2, 0),
  378. color=self._y_axis_color
  379. )
  380. mb.addCube(
  381. width=self._origin_line_width,
  382. height=self._origin_line_width,
  383. depth=self._origin_line_length,
  384. center=origin - Vector(0, 0, self._origin_line_length / 2),
  385. color=self._z_axis_color
  386. )
  387. return mb.build()
  388. def _updateColors(self):
  389. theme = self._application.getTheme()
  390. if theme is None:
  391. return
  392. self._volume_outline_color = Color(*theme.getColor("volume_outline").getRgb())
  393. self._x_axis_color = Color(*theme.getColor("x_axis").getRgb())
  394. self._y_axis_color = Color(*theme.getColor("y_axis").getRgb())
  395. self._z_axis_color = Color(*theme.getColor("z_axis").getRgb())
  396. self._disallowed_area_color = Color(*theme.getColor("disallowed_area").getRgb())
  397. self._error_area_color = Color(*theme.getColor("error_area").getRgb())
  398. def _buildErrorMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d: float, disallowed_area_height: float) -> Optional[MeshData]:
  399. if not self._error_areas:
  400. return None
  401. mb = MeshBuilder()
  402. for error_area in self._error_areas:
  403. color = self._error_area_color
  404. points = error_area.getPoints()
  405. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  406. self._clamp(points[0][1], min_d, max_d))
  407. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  408. self._clamp(points[0][1], min_d, max_d))
  409. for point in points:
  410. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  411. self._clamp(point[1], min_d, max_d))
  412. mb.addFace(first, previous_point, new_point, color=color)
  413. previous_point = new_point
  414. return mb.build()
  415. def _buildDisallowedAreaMesh(self, min_w: float, max_w: float, min_h: float, max_h: float, min_d: float, max_d: float, disallowed_area_height: float) -> Optional[MeshData]:
  416. if not self._disallowed_areas:
  417. return None
  418. bounding_box = Polygon(numpy.array([[min_w, min_d], [min_w, max_d], [max_w, max_d], [max_w, min_d]], numpy.float32))
  419. mb = MeshBuilder()
  420. color = self._disallowed_area_color
  421. for polygon in self._disallowed_areas:
  422. intersection = polygon.intersectionConvexHulls(bounding_box)
  423. points = numpy.flipud(intersection.getPoints())
  424. if len(points) < 3:
  425. continue
  426. first = Vector(points[0][0], disallowed_area_height, points[0][1])
  427. previous_point = Vector(points[1][0], disallowed_area_height, points[1][1])
  428. for point in points[2:]:
  429. new_point = Vector(point[0], disallowed_area_height, point[1])
  430. mb.addFace(first, previous_point, new_point, color=color)
  431. previous_point = new_point
  432. # Find the largest disallowed area to exclude it from the maximum scale bounds.
  433. # This is a very nasty hack. This pretty much only works for UM machines.
  434. # This disallowed area_size needs a -lot- of rework at some point in the future: TODO
  435. if numpy.min(points[:,
  436. 1]) >= 0: # This filters out all areas that have points to the left of the centre. This is done to filter the skirt area.
  437. size = abs(numpy.max(points[:, 1]) - numpy.min(points[:, 1]))
  438. else:
  439. size = 0
  440. self._disallowed_area_size = max(size, self._disallowed_area_size)
  441. return mb.build()
  442. def _updateScaleFactor(self) -> None:
  443. if not self._global_container_stack:
  444. return
  445. scale_xy = 100.0 / max(100.0, self._global_container_stack.getProperty("material_shrinkage_percentage_xy", "value"))
  446. scale_z = 100.0 / max(100.0, self._global_container_stack.getProperty("material_shrinkage_percentage_z" , "value"))
  447. self._scale_vector = Vector(scale_xy, scale_xy, scale_z)
  448. def rebuild(self) -> None:
  449. """Recalculates the build volume & disallowed areas."""
  450. if not self._width or not self._height or not self._depth:
  451. return
  452. if not self._engine_ready:
  453. return
  454. if not self._global_container_stack:
  455. return
  456. if not self._volume_outline_color:
  457. self._updateColors()
  458. min_w = -self._width / 2
  459. max_w = self._width / 2
  460. min_h = 0.0
  461. max_h = self._height
  462. min_d = -self._depth / 2
  463. max_d = self._depth / 2
  464. z_fight_distance = 0.2 # Distance between buildplate and disallowed area meshes to prevent z-fighting
  465. self._grid_mesh = self._buildGridMesh(min_w, max_w, min_h, max_h, min_d, max_d, z_fight_distance)
  466. self.setMeshData(self._buildMesh(min_w, max_w, min_h, max_h, min_d, max_d, z_fight_distance))
  467. # Indication of the machine origin
  468. if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  469. origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
  470. else:
  471. origin = Vector(min_w, min_h, max_d)
  472. self._origin_mesh = self._buildOriginMesh(origin)
  473. disallowed_area_height = 0.1
  474. self._disallowed_area_size = 0.
  475. self._disallowed_area_mesh = self._buildDisallowedAreaMesh(min_w, max_w, min_h, max_h, min_d, max_d, disallowed_area_height)
  476. self._error_mesh = self._buildErrorMesh(min_w, max_w, min_h, max_h, min_d, max_d, disallowed_area_height)
  477. self._updateScaleFactor()
  478. self._volume_aabb = AxisAlignedBox(
  479. minimum = Vector(min_w, min_h - 1.0, min_d),
  480. maximum = Vector(max_w, max_h - self._raft_thickness - self._extra_z_clearance, max_d)
  481. )
  482. bed_adhesion_size = self.getEdgeDisallowedSize()
  483. # As this works better for UM machines, we only add the disallowed_area_size for the z direction.
  484. # This is probably wrong in all other cases. TODO!
  485. # The +1 and -1 is added as there is always a bit of extra room required to work properly.
  486. scale_to_max_bounds = AxisAlignedBox(
  487. minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + self._disallowed_area_size - bed_adhesion_size + 1),
  488. maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness - self._extra_z_clearance, max_d - self._disallowed_area_size + bed_adhesion_size - 1)
  489. )
  490. self._application.getController().getScene()._maximum_bounds = scale_to_max_bounds # type: ignore
  491. self.updateNodeBoundaryCheck()
  492. def getBoundingBox(self) -> Optional[AxisAlignedBox]:
  493. return self._volume_aabb
  494. def getRaftThickness(self) -> float:
  495. return self._raft_thickness
  496. def _updateRaftThickness(self) -> None:
  497. if not self._global_container_stack:
  498. return
  499. old_raft_thickness = self._raft_thickness
  500. if self._global_container_stack.extruderList:
  501. # This might be called before the extruder stacks have initialised, in which case getting the adhesion_type fails
  502. self._adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  503. self._raft_thickness = 0.0
  504. if self._adhesion_type == "raft":
  505. self._raft_thickness = (
  506. self._global_container_stack.getProperty("raft_base_thickness", "value") +
  507. self._global_container_stack.getProperty("raft_interface_layers", "value") *
  508. self._global_container_stack.getProperty("raft_interface_thickness", "value") +
  509. self._global_container_stack.getProperty("raft_surface_layers", "value") *
  510. self._global_container_stack.getProperty("raft_surface_thickness", "value") +
  511. self._global_container_stack.getProperty("raft_airgap", "value") -
  512. self._global_container_stack.getProperty("layer_0_z_overlap", "value"))
  513. # Rounding errors do not matter, we check if raft_thickness has changed at all
  514. if old_raft_thickness != self._raft_thickness:
  515. self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
  516. self.raftThicknessChanged.emit()
  517. def _calculateExtraZClearance(self, extruders: List["ContainerStack"]) -> float:
  518. if not self._global_container_stack:
  519. return 0
  520. extra_z = 0.0
  521. for extruder in extruders:
  522. if extruder.getProperty("retraction_hop_enabled", "value"):
  523. retraction_hop = extruder.getProperty("retraction_hop", "value")
  524. if extra_z is None or retraction_hop > extra_z:
  525. extra_z = retraction_hop
  526. return extra_z
  527. def _onStackChanged(self):
  528. self._stack_change_timer.start()
  529. def _onStackChangeTimerFinished(self) -> None:
  530. """Update the build volume visualization"""
  531. if self._global_container_stack:
  532. self._global_container_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  533. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  534. for extruder in extruders:
  535. extruder.propertyChanged.disconnect(self._onSettingPropertyChanged)
  536. self._global_container_stack = self._application.getGlobalContainerStack()
  537. if self._global_container_stack:
  538. self._global_container_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  539. extruders = ExtruderManager.getInstance().getActiveExtruderStacks()
  540. for extruder in extruders:
  541. extruder.propertyChanged.connect(self._onSettingPropertyChanged)
  542. self._width = self._global_container_stack.getProperty("machine_width", "value")
  543. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  544. if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and self._root_printable_object_count > 1:
  545. new_height = min(self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z, machine_height)
  546. if self._height > new_height:
  547. self._build_volume_message.show()
  548. elif self._height < new_height:
  549. self._build_volume_message.hide()
  550. self._height = new_height
  551. else:
  552. self._height = self._global_container_stack.getProperty("machine_height", "value")
  553. self._build_volume_message.hide()
  554. self._depth = self._global_container_stack.getProperty("machine_depth", "value")
  555. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  556. self._updateDisallowedAreas()
  557. self._updateRaftThickness()
  558. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  559. if self._engine_ready:
  560. self.rebuild()
  561. camera = Application.getInstance().getController().getCameraTool()
  562. if camera:
  563. diagonal = self.getDiagonalSize()
  564. if diagonal > 1:
  565. # You can zoom out up to 5 times the diagonal. This gives some space around the volume.
  566. camera.setZoomRange(min = 0.1, max = diagonal * 5) # type: ignore
  567. def _onEngineCreated(self) -> None:
  568. self._engine_ready = True
  569. self.rebuild()
  570. def _onSettingChangeTimerFinished(self) -> None:
  571. if not self._global_container_stack:
  572. return
  573. rebuild_me = False
  574. update_disallowed_areas = False
  575. update_raft_thickness = False
  576. update_extra_z_clearance = True
  577. for setting_key in self._changed_settings_since_last_rebuild:
  578. if setting_key in ["print_sequence", "support_mesh", "infill_mesh", "cutting_mesh", "anti_overhang_mesh"]:
  579. self._updateRootPrintableObjectCount()
  580. if setting_key == "print_sequence":
  581. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  582. if self._application.getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and self._root_printable_object_count > 1:
  583. new_height = min(
  584. self._global_container_stack.getProperty("gantry_height", "value") * self._scale_vector.z,
  585. machine_height)
  586. if self._height > new_height:
  587. self._build_volume_message.show()
  588. elif self._height < new_height:
  589. self._build_volume_message.hide()
  590. self._height = new_height
  591. else:
  592. self._height = self._global_container_stack.getProperty("machine_height", "value") * self._scale_vector.z
  593. self._build_volume_message.hide()
  594. update_disallowed_areas = True
  595. # sometimes the machine size or shape settings are adjusted on the active machine, we should reflect this
  596. if setting_key in self._machine_settings or setting_key in self._material_size_settings:
  597. self._updateMachineSizeProperties()
  598. update_extra_z_clearance = True
  599. update_disallowed_areas = True
  600. if setting_key in self._disallowed_area_settings:
  601. update_disallowed_areas = True
  602. if setting_key in self._raft_settings:
  603. update_raft_thickness = True
  604. if setting_key in self._extra_z_settings:
  605. update_extra_z_clearance = True
  606. if setting_key in self._limit_to_extruder_settings:
  607. update_disallowed_areas = True
  608. rebuild_me = update_extra_z_clearance or update_disallowed_areas or update_raft_thickness
  609. # We only want to update all of them once.
  610. if update_disallowed_areas:
  611. self._updateDisallowedAreas()
  612. if update_raft_thickness:
  613. self._updateRaftThickness()
  614. if update_extra_z_clearance:
  615. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  616. if rebuild_me:
  617. self.rebuild()
  618. # We just did a rebuild, reset the list.
  619. self._changed_settings_since_last_rebuild = []
  620. def _onSettingPropertyChanged(self, setting_key: str, property_name: str) -> None:
  621. if property_name != "value":
  622. return
  623. if setting_key not in self._changed_settings_since_last_rebuild:
  624. self._changed_settings_since_last_rebuild.append(setting_key)
  625. self._setting_change_timer.start()
  626. def hasErrors(self) -> bool:
  627. return self._has_errors
  628. def _updateMachineSizeProperties(self) -> None:
  629. if not self._global_container_stack:
  630. return
  631. self._updateScaleFactor()
  632. self._height = self._global_container_stack.getProperty("machine_height", "value") * self._scale_vector.z
  633. self._width = self._global_container_stack.getProperty("machine_width", "value")
  634. self._depth = self._global_container_stack.getProperty("machine_depth", "value")
  635. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  636. def _updateDisallowedAreasAndRebuild(self):
  637. """Calls :py:meth:`cura.BuildVolume._updateDisallowedAreas` and makes sure the changes appear in the scene.
  638. This is required for a signal to trigger the update in one go. The
  639. :py:meth:`cura.BuildVolume._updateDisallowedAreas` method itself shouldn't call
  640. :py:meth:`cura.BuildVolume.rebuild`, since there may be other changes before it needs to be rebuilt,
  641. which would hit performance.
  642. """
  643. self._updateDisallowedAreas()
  644. self._updateRaftThickness()
  645. self._extra_z_clearance = self._calculateExtraZClearance(ExtruderManager.getInstance().getUsedExtruderStacks())
  646. self.rebuild()
  647. def _updateDisallowedAreas(self) -> None:
  648. if not self._global_container_stack:
  649. return
  650. self._error_areas = []
  651. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  652. self._edge_disallowed_size = None # Force a recalculation
  653. disallowed_border_size = self.getEdgeDisallowedSize()
  654. result_areas = self._computeDisallowedAreasStatic(disallowed_border_size, used_extruders) # Normal machine disallowed areas can always be added.
  655. prime_areas = self._computeDisallowedAreasPrimeBlob(disallowed_border_size, used_extruders)
  656. result_areas_no_brim = self._computeDisallowedAreasStatic(0, used_extruders) # Where the priming is not allowed to happen. This is not added to the result, just for collision checking.
  657. # Check if prime positions intersect with disallowed areas.
  658. for extruder in used_extruders:
  659. extruder_id = extruder.getId()
  660. result_areas[extruder_id].extend(prime_areas[extruder_id])
  661. result_areas_no_brim[extruder_id].extend(prime_areas[extruder_id])
  662. nozzle_disallowed_areas = extruder.getProperty("nozzle_disallowed_areas", "value")
  663. for area in nozzle_disallowed_areas:
  664. polygon = Polygon(numpy.array(area, numpy.float32))
  665. polygon_disallowed_border = polygon.getMinkowskiHull(Polygon.approximatedCircle(disallowed_border_size))
  666. result_areas[extruder_id].append(polygon_disallowed_border) # Don't perform the offset on these.
  667. result_areas_no_brim[extruder_id].append(polygon) # No brim
  668. # Add prime tower location as disallowed area.
  669. if len([x for x in used_extruders if x.isEnabled]) > 1: # No prime tower if only one extruder is enabled
  670. prime_tower_collision = False
  671. prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
  672. for extruder_id in prime_tower_areas:
  673. for area_index, prime_tower_area in enumerate(prime_tower_areas[extruder_id]):
  674. for area in result_areas_no_brim[extruder_id]:
  675. if prime_tower_area.intersectsPolygon(area) is not None:
  676. prime_tower_collision = True
  677. break
  678. if prime_tower_collision: # Already found a collision.
  679. break
  680. if not prime_tower_collision:
  681. result_areas[extruder_id].extend(prime_tower_areas[extruder_id])
  682. result_areas_no_brim[extruder_id].extend(prime_tower_areas[extruder_id])
  683. else:
  684. self._error_areas.extend(prime_tower_areas[extruder_id])
  685. self._has_errors = len(self._error_areas) > 0
  686. self._disallowed_areas = []
  687. for extruder_id in result_areas:
  688. self._disallowed_areas.extend(result_areas[extruder_id])
  689. self._disallowed_areas_no_brim = []
  690. for extruder_id in result_areas_no_brim:
  691. self._disallowed_areas_no_brim.extend(result_areas_no_brim[extruder_id])
  692. def _computeDisallowedAreasPrinted(self, used_extruders):
  693. """Computes the disallowed areas for objects that are printed with print features.
  694. This means that the brim, travel avoidance and such will be applied to these features.
  695. :return: A dictionary with for each used extruder ID the disallowed areas where that extruder may not print.
  696. """
  697. result = {}
  698. skirt_brim_extruder: ExtruderStack = None
  699. skirt_brim_extruder_nr = self._global_container_stack.getProperty("skirt_brim_extruder_nr", "value")
  700. for extruder in used_extruders:
  701. if skirt_brim_extruder_nr == -1:
  702. skirt_brim_extruder = used_extruders[0] # The prime tower brim is always printed with the first extruder
  703. elif int(extruder.getProperty("extruder_nr", "value")) == int(skirt_brim_extruder_nr):
  704. skirt_brim_extruder = extruder
  705. result[extruder.getId()] = []
  706. # Currently, the only normally printed object is the prime tower.
  707. if self._global_container_stack.getProperty("prime_tower_enable", "value"):
  708. prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
  709. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  710. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  711. prime_tower_x = self._global_container_stack.getProperty("prime_tower_position_x", "value")
  712. prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value")
  713. prime_tower_brim_enable = self._global_container_stack.getProperty("prime_tower_brim_enable", "value")
  714. prime_tower_base_size = self._global_container_stack.getProperty("prime_tower_base_size", "value")
  715. prime_tower_base_height = self._global_container_stack.getProperty("prime_tower_base_height", "value")
  716. adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  717. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  718. prime_tower_x = prime_tower_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  719. prime_tower_y = prime_tower_y + machine_depth / 2
  720. radius = prime_tower_size / 2
  721. delta_x = -radius
  722. delta_y = -radius
  723. if prime_tower_base_size > 0 and ((prime_tower_brim_enable and prime_tower_base_height > 0) or adhesion_type == "raft"):
  724. radius += prime_tower_base_size
  725. prime_tower_area = Polygon.approximatedCircle(radius, num_segments = 32)
  726. prime_tower_area = prime_tower_area.translate(prime_tower_x + delta_x, prime_tower_y + delta_y)
  727. prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
  728. for extruder in used_extruders:
  729. result[extruder.getId()].append(prime_tower_area) #The prime tower location is the same for each extruder, regardless of offset.
  730. return result
  731. def _computeDisallowedAreasPrimeBlob(self, border_size: float, used_extruders: List["ExtruderStack"]) -> Dict[str, List[Polygon]]:
  732. """Computes the disallowed areas for the prime blobs.
  733. These are special because they are not subject to things like brim or travel avoidance. They do get a dilute
  734. with the border size though because they may not intersect with brims and such of other objects.
  735. :param border_size: The size with which to offset the disallowed areas due to skirt, brim, travel avoid distance
  736. , etc.
  737. :param used_extruders: The extruder stacks to generate disallowed areas for.
  738. :return: A dictionary with for each used extruder ID the prime areas.
  739. """
  740. result = {} # type: Dict[str, List[Polygon]]
  741. if not self._global_container_stack:
  742. return result
  743. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  744. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  745. for extruder in used_extruders:
  746. prime_blob_enabled = extruder.getProperty("prime_blob_enable", "value")
  747. prime_x = extruder.getProperty("extruder_prime_pos_x", "value")
  748. prime_y = -extruder.getProperty("extruder_prime_pos_y", "value")
  749. # Ignore extruder prime position if it is not set or if blob is disabled
  750. if (prime_x == 0 and prime_y == 0) or not prime_blob_enabled:
  751. result[extruder.getId()] = []
  752. continue
  753. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  754. prime_x = prime_x - machine_width / 2 # Offset by half machine_width and _depth to put the origin in the front-left.
  755. prime_y = prime_y + machine_depth / 2
  756. prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
  757. prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  758. prime_polygon = prime_polygon.translate(prime_x, prime_y)
  759. result[extruder.getId()] = [prime_polygon]
  760. return result
  761. def _computeDisallowedAreasStatic(self, border_size:float, used_extruders: List["ExtruderStack"]) -> Dict[str, List[Polygon]]:
  762. """Computes the disallowed areas that are statically placed in the machine.
  763. It computes different disallowed areas depending on the offset of the extruder. The resulting dictionary will
  764. therefore have an entry for each extruder that is used.
  765. :param border_size: The size with which to offset the disallowed areas due to skirt, brim, travel avoid distance
  766. , etc.
  767. :param used_extruders: The extruder stacks to generate disallowed areas for.
  768. :return: A dictionary with for each used extruder ID the disallowed areas where that extruder may not print.
  769. """
  770. # Convert disallowed areas to polygons and dilate them.
  771. machine_disallowed_polygons = []
  772. if self._global_container_stack is None:
  773. return {}
  774. for area in self._global_container_stack.getProperty("machine_disallowed_areas", "value"):
  775. if len(area) == 0:
  776. continue # Numpy doesn't deal well with 0-length arrays, since it can't determine the dimensionality of them.
  777. polygon = Polygon(numpy.array(area, numpy.float32))
  778. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  779. machine_disallowed_polygons.append(polygon)
  780. # For certain machines we don't need to compute disallowed areas for each nozzle.
  781. # So we check here and only do the nozzle offsetting if needed.
  782. nozzle_offsetting_for_disallowed_areas = self._global_container_stack.getMetaDataEntry(
  783. "nozzle_offsetting_for_disallowed_areas", True)
  784. result = {} # type: Dict[str, List[Polygon]]
  785. for extruder in used_extruders:
  786. extruder_id = extruder.getId()
  787. offset_x = extruder.getProperty("machine_nozzle_offset_x", "value")
  788. if offset_x is None:
  789. offset_x = 0
  790. offset_y = extruder.getProperty("machine_nozzle_offset_y", "value")
  791. if offset_y is None:
  792. offset_y = 0
  793. offset_y = -offset_y # Y direction of g-code is the inverse of Y direction of Cura's scene space.
  794. result[extruder_id] = []
  795. for polygon in machine_disallowed_polygons:
  796. result[extruder_id].append(polygon.translate(offset_x, offset_y)) # Compensate for the nozzle offset of this extruder.
  797. # Add the border around the edge of the build volume.
  798. left_unreachable_border = 0
  799. right_unreachable_border = 0
  800. top_unreachable_border = 0
  801. bottom_unreachable_border = 0
  802. # Only do nozzle offsetting if needed
  803. if nozzle_offsetting_for_disallowed_areas:
  804. # The build volume is defined as the union of the area that all extruders can reach, so we need to know
  805. # the relative offset to all extruders.
  806. for other_extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  807. other_offset_x = other_extruder.getProperty("machine_nozzle_offset_x", "value")
  808. if other_offset_x is None:
  809. other_offset_x = 0
  810. other_offset_y = other_extruder.getProperty("machine_nozzle_offset_y", "value")
  811. if other_offset_y is None:
  812. other_offset_y = 0
  813. other_offset_y = -other_offset_y
  814. left_unreachable_border = min(left_unreachable_border, other_offset_x - offset_x)
  815. right_unreachable_border = max(right_unreachable_border, other_offset_x - offset_x)
  816. top_unreachable_border = min(top_unreachable_border, other_offset_y - offset_y)
  817. bottom_unreachable_border = max(bottom_unreachable_border, other_offset_y - offset_y)
  818. half_machine_width = self._global_container_stack.getProperty("machine_width", "value") / 2
  819. half_machine_depth = self._global_container_stack.getProperty("machine_depth", "value") / 2
  820. # We need at a minimum a very small border around the edge so that models can't go off the build plate
  821. border_size = max(border_size, 0.1)
  822. if self._shape != "elliptic":
  823. if border_size - left_unreachable_border > 0:
  824. result[extruder_id].append(Polygon(numpy.array([
  825. [-half_machine_width, -half_machine_depth],
  826. [-half_machine_width, half_machine_depth],
  827. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  828. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  829. ], numpy.float32)))
  830. if border_size + right_unreachable_border > 0:
  831. result[extruder_id].append(Polygon(numpy.array([
  832. [half_machine_width, half_machine_depth],
  833. [half_machine_width, -half_machine_depth],
  834. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  835. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  836. ], numpy.float32)))
  837. if border_size + bottom_unreachable_border > 0:
  838. result[extruder_id].append(Polygon(numpy.array([
  839. [-half_machine_width, half_machine_depth],
  840. [half_machine_width, half_machine_depth],
  841. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  842. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  843. ], numpy.float32)))
  844. if border_size - top_unreachable_border > 0:
  845. result[extruder_id].append(Polygon(numpy.array([
  846. [half_machine_width, -half_machine_depth],
  847. [-half_machine_width, -half_machine_depth],
  848. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  849. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  850. ], numpy.float32)))
  851. else:
  852. sections = 32
  853. arc_vertex = [0, half_machine_depth - border_size]
  854. for i in range(0, sections):
  855. quadrant = math.floor(4 * i / sections)
  856. vertices = []
  857. if quadrant == 0:
  858. vertices.append([-half_machine_width, half_machine_depth])
  859. elif quadrant == 1:
  860. vertices.append([-half_machine_width, -half_machine_depth])
  861. elif quadrant == 2:
  862. vertices.append([half_machine_width, -half_machine_depth])
  863. elif quadrant == 3:
  864. vertices.append([half_machine_width, half_machine_depth])
  865. vertices.append(arc_vertex)
  866. angle = 2 * math.pi * (i + 1) / sections
  867. arc_vertex = [-(half_machine_width - border_size) * math.sin(angle), (half_machine_depth - border_size) * math.cos(angle)]
  868. vertices.append(arc_vertex)
  869. result[extruder_id].append(Polygon(numpy.array(vertices, numpy.float32)))
  870. if border_size > 0:
  871. result[extruder_id].append(Polygon(numpy.array([
  872. [-half_machine_width, -half_machine_depth],
  873. [-half_machine_width, half_machine_depth],
  874. [-half_machine_width + border_size, 0]
  875. ], numpy.float32)))
  876. result[extruder_id].append(Polygon(numpy.array([
  877. [-half_machine_width, half_machine_depth],
  878. [ half_machine_width, half_machine_depth],
  879. [ 0, half_machine_depth - border_size]
  880. ], numpy.float32)))
  881. result[extruder_id].append(Polygon(numpy.array([
  882. [ half_machine_width, half_machine_depth],
  883. [ half_machine_width, -half_machine_depth],
  884. [ half_machine_width - border_size, 0]
  885. ], numpy.float32)))
  886. result[extruder_id].append(Polygon(numpy.array([
  887. [ half_machine_width, -half_machine_depth],
  888. [-half_machine_width, -half_machine_depth],
  889. [ 0, -half_machine_depth + border_size]
  890. ], numpy.float32)))
  891. return result
  892. def _getSettingFromAllExtruders(self, setting_key: str) -> List[Any]:
  893. """Private convenience function to get a setting from every extruder.
  894. For single extrusion machines, this gets the setting from the global stack.
  895. :return: A sequence of setting values, one for each extruder.
  896. """
  897. all_values = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "value")
  898. all_types = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "type")
  899. for i, (setting_value, setting_type) in enumerate(zip(all_values, all_types)):
  900. if not setting_value and setting_type in ["int", "float"]:
  901. all_values[i] = 0
  902. return all_values
  903. def _calculateBedAdhesionSize(self, used_extruders):
  904. """Get the bed adhesion size for the global container stack and used extruders
  905. :param adhesion_override: override adhesion type.
  906. Use None to use the global stack default, "none" for no adhesion, "brim" for brim etc.
  907. """
  908. if self._global_container_stack is None:
  909. return None
  910. container_stack = self._global_container_stack
  911. adhesion_type = container_stack.getProperty("adhesion_type", "value")
  912. if adhesion_type == "raft":
  913. bed_adhesion_size = self._global_container_stack.getProperty("raft_margin", "value") # Should refer to the raft extruder if set.
  914. else: # raft, brim or skirt. Those last two are handled by CuraEngine.
  915. bed_adhesion_size = 0
  916. max_length_available = 0.5 * min(
  917. self._global_container_stack.getProperty("machine_width", "value"),
  918. self._global_container_stack.getProperty("machine_depth", "value")
  919. )
  920. bed_adhesion_size = min(bed_adhesion_size, max_length_available)
  921. return bed_adhesion_size
  922. def _calculateFarthestShieldDistance(self, container_stack):
  923. farthest_shield_distance = 0
  924. if container_stack.getProperty("draft_shield_enabled", "value"):
  925. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("draft_shield_dist", "value"))
  926. if container_stack.getProperty("ooze_shield_enabled", "value"):
  927. farthest_shield_distance = max(farthest_shield_distance,container_stack.getProperty("ooze_shield_dist", "value"))
  928. return farthest_shield_distance
  929. def _calculateSupportExpansion(self, container_stack):
  930. support_expansion = 0
  931. support_enabled = self._global_container_stack.getProperty("support_enable", "value")
  932. support_offset = self._global_container_stack.getProperty("support_offset", "value")
  933. if support_enabled and support_offset:
  934. support_expansion += support_offset
  935. return support_expansion
  936. def _calculateMoveFromWallRadius(self, used_extruders):
  937. move_from_wall_radius = 0 # Moves that start from outer wall.
  938. for stack in used_extruders:
  939. if stack.getProperty("travel_avoid_other_parts", "value"):
  940. move_from_wall_radius = max(move_from_wall_radius, stack.getProperty("travel_avoid_distance", "value"))
  941. infill_wipe_distance = stack.getProperty("infill_wipe_dist", "value")
  942. num_walls = stack.getProperty("wall_line_count", "value")
  943. if num_walls >= 1: # Infill wipes start from the infill, so subtract the total wall thickness from this.
  944. infill_wipe_distance -= stack.getProperty("wall_line_width_0", "value")
  945. if num_walls >= 2:
  946. infill_wipe_distance -= stack.getProperty("wall_line_width_x", "value") * (num_walls - 1)
  947. move_from_wall_radius = max(move_from_wall_radius, infill_wipe_distance)
  948. return move_from_wall_radius
  949. def getEdgeDisallowedSize(self):
  950. """Calculate the disallowed radius around the edge.
  951. This disallowed radius is to allow for space around the models that is not part of the collision radius,
  952. such as bed adhesion (skirt/brim/raft) and travel avoid distance.
  953. """
  954. if not self._global_container_stack or not self._global_container_stack.extruderList:
  955. return 0
  956. if self._edge_disallowed_size is not None:
  957. return self._edge_disallowed_size
  958. container_stack = self._global_container_stack
  959. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  960. # If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
  961. if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  962. return 0.1
  963. bed_adhesion_size = self._calculateBedAdhesionSize(used_extruders)
  964. support_expansion = self._calculateSupportExpansion(self._global_container_stack)
  965. farthest_shield_distance = self._calculateFarthestShieldDistance(self._global_container_stack)
  966. move_from_wall_radius = self._calculateMoveFromWallRadius(used_extruders)
  967. # Now combine our different pieces of data to get the final border size.
  968. # Support expansion is added to the bed adhesion, since the bed adhesion goes around support.
  969. # Support expansion is added to farthest shield distance, since the shields go around support.
  970. self._edge_disallowed_size = max(move_from_wall_radius, support_expansion + farthest_shield_distance, support_expansion + bed_adhesion_size)
  971. return self._edge_disallowed_size
  972. def _clamp(self, value, min_value, max_value):
  973. return max(min(value, max_value), min_value)
  974. _machine_settings = ["machine_width", "machine_depth", "machine_height", "machine_shape", "machine_center_is_zero"]
  975. _skirt_settings = ["adhesion_type", "skirt_gap", "skirt_line_count", "skirt_brim_line_width", "brim_gap", "brim_width", "brim_line_count", "raft_margin", "draft_shield_enabled", "draft_shield_dist", "initial_layer_line_width_factor"]
  976. _raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_layers", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap", "layer_0_z_overlap"]
  977. _extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
  978. _prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "prime_blob_enable"]
  979. _tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y", "prime_tower_brim_enable", "prime_tower_base_size", "prime_tower_base_height"]
  980. _ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
  981. _distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts", "travel_avoid_supports", "wall_line_count", "wall_line_width_0", "wall_line_width_x"]
  982. _extruder_settings = ["support_enable", "support_bottom_enable", "support_roof_enable", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_bottom_extruder_nr", "support_roof_extruder_nr", "brim_line_count", "skirt_brim_extruder_nr", "raft_base_extruder_nr", "raft_interface_extruder_nr", "raft_surface_extruder_nr", "adhesion_type"] #Settings that can affect which extruders are used.
  983. _limit_to_extruder_settings = ["wall_extruder_nr", "wall_0_extruder_nr", "wall_x_extruder_nr", "top_bottom_extruder_nr", "infill_extruder_nr", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_bottom_extruder_nr", "support_roof_extruder_nr", "skirt_brim_extruder_nr", "raft_base_extruder_nr", "raft_interface_extruder_nr", "raft_surface_extruder_nr"]
  984. _material_size_settings = ["material_shrinkage_percentage", "material_shrinkage_percentage_xy", "material_shrinkage_percentage_z"]
  985. _disallowed_area_settings = _skirt_settings + _prime_settings + _tower_settings + _ooze_shield_settings + _distance_settings + _extruder_settings + _material_size_settings