BuildVolume.py 60 KB

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