BuildVolume.py 61 KB

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