BuildVolume.py 62 KB

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