BuildVolume.py 60 KB

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