BuildVolume.py 58 KB

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