BuildVolume.py 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. from cura.Settings.ExtruderManager import ExtruderManager
  4. from UM.Settings.ContainerRegistry import ContainerRegistry
  5. from UM.i18n import i18nCatalog
  6. from UM.Scene.Platform import Platform
  7. from UM.Scene.Iterator.BreadthFirstIterator import BreadthFirstIterator
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Application import Application
  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 copy
  25. import math
  26. # Setting for clearance around the prime
  27. PRIME_CLEARANCE = 6.5
  28. ## Build volume is a special kind of node that is responsible for rendering the printable area & disallowed areas.
  29. class BuildVolume(SceneNode):
  30. raftThicknessChanged = Signal()
  31. def __init__(self, parent = None):
  32. super().__init__(parent)
  33. self._volume_outline_color = None
  34. self._x_axis_color = None
  35. self._y_axis_color = None
  36. self._z_axis_color = None
  37. self._disallowed_area_color = None
  38. self._error_area_color = None
  39. self._width = 0
  40. self._height = 0
  41. self._depth = 0
  42. self._shape = ""
  43. self._shader = None
  44. self._origin_mesh = None
  45. self._origin_line_length = 20
  46. self._origin_line_width = 0.5
  47. self._grid_mesh = None
  48. self._grid_shader = None
  49. self._disallowed_areas = []
  50. self._disallowed_area_mesh = None
  51. self._error_areas = []
  52. self._error_mesh = None
  53. self.setCalculateBoundingBox(False)
  54. self._volume_aabb = None
  55. self._raft_thickness = 0.0
  56. self._extra_z_clearance = 0.0
  57. self._adhesion_type = None
  58. self._platform = Platform(self)
  59. self._global_container_stack = None
  60. Application.getInstance().globalContainerStackChanged.connect(self._onStackChanged)
  61. self._onStackChanged()
  62. self._engine_ready = False
  63. Application.getInstance().engineCreatedSignal.connect(self._onEngineCreated)
  64. self._has_errors = False
  65. Application.getInstance().getController().getScene().sceneChanged.connect(self._onSceneChanged)
  66. #Objects loaded at the moment. We are connected to the property changed events of these objects.
  67. self._scene_objects = set()
  68. self._change_timer = QTimer()
  69. self._change_timer.setInterval(100)
  70. self._change_timer.setSingleShot(True)
  71. self._change_timer.timeout.connect(self._onChangeTimerFinished)
  72. self._build_volume_message = Message(catalog.i18nc("@info:status",
  73. "The build volume height has been reduced due to the value of the"
  74. " \"Print Sequence\" setting to prevent the gantry from colliding"
  75. " with printed models."))
  76. # Must be after setting _build_volume_message, apparently that is used in getMachineManager.
  77. # activeQualityChanged is always emitted after setActiveVariant, setActiveMaterial and setActiveQuality.
  78. # Therefore this works.
  79. Application.getInstance().getMachineManager().activeQualityChanged.connect(self._onStackChanged)
  80. # This should also ways work, and it is semantically more correct,
  81. # but it does not update the disallowed areas after material change
  82. Application.getInstance().getMachineManager().activeStackChanged.connect(self._onStackChanged)
  83. def _onSceneChanged(self, source):
  84. if self._global_container_stack:
  85. self._change_timer.start()
  86. def _onChangeTimerFinished(self):
  87. root = Application.getInstance().getController().getScene().getRoot()
  88. new_scene_objects = set(node for node in BreadthFirstIterator(root) if node.getMeshData() and type(node) is SceneNode)
  89. if new_scene_objects != self._scene_objects:
  90. for node in new_scene_objects - self._scene_objects: #Nodes that were added to the scene.
  91. node.decoratorsChanged.connect(self._onNodeDecoratorChanged)
  92. for node in self._scene_objects - new_scene_objects: #Nodes that were removed from the scene.
  93. per_mesh_stack = node.callDecoration("getStack")
  94. if per_mesh_stack:
  95. per_mesh_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  96. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  97. if active_extruder_changed is not None:
  98. node.callDecoration("getActiveExtruderChangedSignal").disconnect(self._updateDisallowedAreasAndRebuild)
  99. node.decoratorsChanged.disconnect(self._onNodeDecoratorChanged)
  100. self._scene_objects = new_scene_objects
  101. self._onSettingPropertyChanged("print_sequence", "value") # Create fake event, so right settings are triggered.
  102. ## Updates the listeners that listen for changes in per-mesh stacks.
  103. #
  104. # \param node The node for which the decorators changed.
  105. def _onNodeDecoratorChanged(self, node):
  106. per_mesh_stack = node.callDecoration("getStack")
  107. if per_mesh_stack:
  108. per_mesh_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  109. active_extruder_changed = node.callDecoration("getActiveExtruderChangedSignal")
  110. if active_extruder_changed is not None:
  111. active_extruder_changed.connect(self._updateDisallowedAreasAndRebuild)
  112. self._updateDisallowedAreasAndRebuild()
  113. def setWidth(self, width):
  114. if width: self._width = width
  115. def setHeight(self, height):
  116. if height: self._height = height
  117. def setDepth(self, depth):
  118. if depth: self._depth = depth
  119. def setShape(self, shape):
  120. if shape: self._shape = shape
  121. def getDisallowedAreas(self):
  122. return self._disallowed_areas
  123. def setDisallowedAreas(self, areas):
  124. self._disallowed_areas = areas
  125. def render(self, renderer):
  126. if not self.getMeshData():
  127. return True
  128. if not self._shader:
  129. self._shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "default.shader"))
  130. self._grid_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "grid.shader"))
  131. theme = Application.getInstance().getTheme()
  132. self._grid_shader.setUniformValue("u_gridColor0", Color(*theme.getColor("buildplate").getRgb()))
  133. self._grid_shader.setUniformValue("u_gridColor1", Color(*theme.getColor("buildplate_alt").getRgb()))
  134. renderer.queueNode(self, mode = RenderBatch.RenderMode.Lines)
  135. renderer.queueNode(self, mesh = self._origin_mesh)
  136. renderer.queueNode(self, mesh = self._grid_mesh, shader = self._grid_shader, backface_cull = True)
  137. if self._disallowed_area_mesh:
  138. renderer.queueNode(self, mesh = self._disallowed_area_mesh, shader = self._shader, transparent = True, backface_cull = True, sort = -9)
  139. if self._error_mesh:
  140. renderer.queueNode(self, mesh=self._error_mesh, shader=self._shader, transparent=True,
  141. backface_cull=True, sort=-8)
  142. return True
  143. ## Recalculates the build volume & disallowed areas.
  144. def rebuild(self):
  145. if not self._width or not self._height or not self._depth:
  146. return
  147. if not Application.getInstance()._engine:
  148. return
  149. if not self._volume_outline_color:
  150. theme = Application.getInstance().getTheme()
  151. self._volume_outline_color = Color(*theme.getColor("volume_outline").getRgb())
  152. self._x_axis_color = Color(*theme.getColor("x_axis").getRgb())
  153. self._y_axis_color = Color(*theme.getColor("y_axis").getRgb())
  154. self._z_axis_color = Color(*theme.getColor("z_axis").getRgb())
  155. self._disallowed_area_color = Color(*theme.getColor("disallowed_area").getRgb())
  156. self._error_area_color = Color(*theme.getColor("error_area").getRgb())
  157. min_w = -self._width / 2
  158. max_w = self._width / 2
  159. min_h = 0.0
  160. max_h = self._height
  161. min_d = -self._depth / 2
  162. max_d = self._depth / 2
  163. z_fight_distance = 0.2 # Distance between buildplate and disallowed area meshes to prevent z-fighting
  164. if self._shape != "elliptic":
  165. # Outline 'cube' of the build volume
  166. mb = MeshBuilder()
  167. mb.addLine(Vector(min_w, min_h, min_d), Vector(max_w, min_h, min_d), color = self._volume_outline_color)
  168. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, max_h, min_d), color = self._volume_outline_color)
  169. mb.addLine(Vector(min_w, max_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  170. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, max_h, min_d), color = self._volume_outline_color)
  171. mb.addLine(Vector(min_w, min_h, max_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  172. mb.addLine(Vector(min_w, min_h, max_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  173. mb.addLine(Vector(min_w, max_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  174. mb.addLine(Vector(max_w, min_h, max_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  175. mb.addLine(Vector(min_w, min_h, min_d), Vector(min_w, min_h, max_d), color = self._volume_outline_color)
  176. mb.addLine(Vector(max_w, min_h, min_d), Vector(max_w, min_h, max_d), color = self._volume_outline_color)
  177. mb.addLine(Vector(min_w, max_h, min_d), Vector(min_w, max_h, max_d), color = self._volume_outline_color)
  178. mb.addLine(Vector(max_w, max_h, min_d), Vector(max_w, max_h, max_d), color = self._volume_outline_color)
  179. self.setMeshData(mb.build())
  180. # Build plate grid mesh
  181. mb = MeshBuilder()
  182. mb.addQuad(
  183. Vector(min_w, min_h - z_fight_distance, min_d),
  184. Vector(max_w, min_h - z_fight_distance, min_d),
  185. Vector(max_w, min_h - z_fight_distance, max_d),
  186. Vector(min_w, min_h - z_fight_distance, max_d)
  187. )
  188. for n in range(0, 6):
  189. v = mb.getVertex(n)
  190. mb.setVertexUVCoordinates(n, v[0], v[2])
  191. self._grid_mesh = mb.build()
  192. else:
  193. # Bottom and top 'ellipse' of the build volume
  194. aspect = 1.0
  195. scale_matrix = Matrix()
  196. if self._width != 0:
  197. # Scale circular meshes by aspect ratio if width != height
  198. aspect = self._depth / self._width
  199. scale_matrix.compose(scale = Vector(1, 1, aspect))
  200. mb = MeshBuilder()
  201. mb.addArc(max_w, Vector.Unit_Y, center = (0, min_h - z_fight_distance, 0), color = self._volume_outline_color)
  202. mb.addArc(max_w, Vector.Unit_Y, center = (0, max_h, 0), color = self._volume_outline_color)
  203. self.setMeshData(mb.build().getTransformed(scale_matrix))
  204. # Build plate grid mesh
  205. mb = MeshBuilder()
  206. mb.addVertex(0, min_h - z_fight_distance, 0)
  207. mb.addArc(max_w, Vector.Unit_Y, center = Vector(0, min_h - z_fight_distance, 0))
  208. sections = mb.getVertexCount() - 1 # Center point is not an arc section
  209. indices = []
  210. for n in range(0, sections - 1):
  211. indices.append([0, n + 2, n + 1])
  212. mb.addIndices(numpy.asarray(indices, dtype = numpy.int32))
  213. mb.calculateNormals()
  214. for n in range(0, mb.getVertexCount()):
  215. v = mb.getVertex(n)
  216. mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
  217. self._grid_mesh = mb.build().getTransformed(scale_matrix)
  218. # Indication of the machine origin
  219. if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  220. origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
  221. else:
  222. origin = Vector(min_w, min_h, max_d)
  223. mb = MeshBuilder()
  224. mb.addCube(
  225. width = self._origin_line_length,
  226. height = self._origin_line_width,
  227. depth = self._origin_line_width,
  228. center = origin + Vector(self._origin_line_length / 2, 0, 0),
  229. color = self._x_axis_color
  230. )
  231. mb.addCube(
  232. width = self._origin_line_width,
  233. height = self._origin_line_length,
  234. depth = self._origin_line_width,
  235. center = origin + Vector(0, self._origin_line_length / 2, 0),
  236. color = self._y_axis_color
  237. )
  238. mb.addCube(
  239. width = self._origin_line_width,
  240. height = self._origin_line_width,
  241. depth = self._origin_line_length,
  242. center = origin - Vector(0, 0, self._origin_line_length / 2),
  243. color = self._z_axis_color
  244. )
  245. self._origin_mesh = mb.build()
  246. disallowed_area_height = 0.1
  247. disallowed_area_size = 0
  248. if self._disallowed_areas:
  249. mb = MeshBuilder()
  250. color = self._disallowed_area_color
  251. for polygon in self._disallowed_areas:
  252. points = polygon.getPoints()
  253. if len(points) == 0:
  254. continue
  255. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  256. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  257. for point in points:
  258. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height, self._clamp(point[1], min_d, max_d))
  259. mb.addFace(first, previous_point, new_point, color = color)
  260. previous_point = new_point
  261. # Find the largest disallowed area to exclude it from the maximum scale bounds.
  262. # This is a very nasty hack. This pretty much only works for UM machines.
  263. # This disallowed area_size needs a -lot- of rework at some point in the future: TODO
  264. 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.
  265. size = abs(numpy.max(points[:, 1]) - numpy.min(points[:, 1]))
  266. else:
  267. size = 0
  268. disallowed_area_size = max(size, disallowed_area_size)
  269. self._disallowed_area_mesh = mb.build()
  270. else:
  271. self._disallowed_area_mesh = None
  272. if self._error_areas:
  273. mb = MeshBuilder()
  274. for error_area in self._error_areas:
  275. color = self._error_area_color
  276. points = error_area.getPoints()
  277. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  278. self._clamp(points[0][1], min_d, max_d))
  279. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  280. self._clamp(points[0][1], min_d, max_d))
  281. for point in points:
  282. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  283. self._clamp(point[1], min_d, max_d))
  284. mb.addFace(first, previous_point, new_point, color=color)
  285. previous_point = new_point
  286. self._error_mesh = mb.build()
  287. else:
  288. self._error_mesh = None
  289. self._volume_aabb = AxisAlignedBox(
  290. minimum = Vector(min_w, min_h - 1.0, min_d),
  291. maximum = Vector(max_w, max_h - self._raft_thickness - self._extra_z_clearance, max_d))
  292. bed_adhesion_size = self._getEdgeDisallowedSize()
  293. # As this works better for UM machines, we only add the disallowed_area_size for the z direction.
  294. # This is probably wrong in all other cases. TODO!
  295. # The +1 and -1 is added as there is always a bit of extra room required to work properly.
  296. scale_to_max_bounds = AxisAlignedBox(
  297. minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + disallowed_area_size - bed_adhesion_size + 1),
  298. 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)
  299. )
  300. Application.getInstance().getController().getScene()._maximum_bounds = scale_to_max_bounds
  301. def getBoundingBox(self):
  302. return self._volume_aabb
  303. def getRaftThickness(self):
  304. return self._raft_thickness
  305. def _updateRaftThickness(self):
  306. old_raft_thickness = self._raft_thickness
  307. self._adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  308. self._raft_thickness = 0.0
  309. if self._adhesion_type == "raft":
  310. self._raft_thickness = (
  311. self._global_container_stack.getProperty("raft_base_thickness", "value") +
  312. self._global_container_stack.getProperty("raft_interface_thickness", "value") +
  313. self._global_container_stack.getProperty("raft_surface_layers", "value") *
  314. self._global_container_stack.getProperty("raft_surface_thickness", "value") +
  315. self._global_container_stack.getProperty("raft_airgap", "value"))
  316. # Rounding errors do not matter, we check if raft_thickness has changed at all
  317. if old_raft_thickness != self._raft_thickness:
  318. self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
  319. self.raftThicknessChanged.emit()
  320. def _updateExtraZClearance(self) -> None:
  321. extra_z = 0.0
  322. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  323. use_extruders = False
  324. for extruder in extruders:
  325. if extruder.getProperty("retraction_hop_enabled", "value"):
  326. retraction_hop = extruder.getProperty("retraction_hop", "value")
  327. if extra_z is None or retraction_hop > extra_z:
  328. extra_z = retraction_hop
  329. use_extruders = True
  330. if not use_extruders:
  331. # If no extruders, take global value.
  332. if self._global_container_stack.getProperty("retraction_hop_enabled", "value"):
  333. extra_z = self._global_container_stack.getProperty("retraction_hop", "value")
  334. if extra_z != self._extra_z_clearance:
  335. self._extra_z_clearance = extra_z
  336. ## Update the build volume visualization
  337. def _onStackChanged(self):
  338. if self._global_container_stack:
  339. self._global_container_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  340. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  341. for extruder in extruders:
  342. extruder.propertyChanged.disconnect(self._onSettingPropertyChanged)
  343. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  344. if self._global_container_stack:
  345. self._global_container_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  346. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  347. for extruder in extruders:
  348. extruder.propertyChanged.connect(self._onSettingPropertyChanged)
  349. self._width = self._global_container_stack.getProperty("machine_width", "value")
  350. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  351. if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  352. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  353. if self._height < machine_height:
  354. self._build_volume_message.show()
  355. else:
  356. self._build_volume_message.hide()
  357. else:
  358. self._height = self._global_container_stack.getProperty("machine_height", "value")
  359. self._build_volume_message.hide()
  360. self._depth = self._global_container_stack.getProperty("machine_depth", "value")
  361. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  362. self._updateDisallowedAreas()
  363. self._updateRaftThickness()
  364. if self._engine_ready:
  365. self.rebuild()
  366. def _onEngineCreated(self):
  367. self._engine_ready = True
  368. self.rebuild()
  369. def _onSettingPropertyChanged(self, setting_key, property_name):
  370. if property_name != "value":
  371. return
  372. rebuild_me = False
  373. if setting_key == "print_sequence":
  374. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  375. if Application.getInstance().getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  376. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  377. if self._height < machine_height:
  378. self._build_volume_message.show()
  379. else:
  380. self._build_volume_message.hide()
  381. else:
  382. self._height = self._global_container_stack.getProperty("machine_height", "value")
  383. self._build_volume_message.hide()
  384. rebuild_me = True
  385. if setting_key in self._skirt_settings or setting_key in self._prime_settings or setting_key in self._tower_settings or setting_key == "print_sequence" or setting_key in self._ooze_shield_settings or setting_key in self._distance_settings or setting_key in self._extruder_settings:
  386. self._updateDisallowedAreas()
  387. rebuild_me = True
  388. if setting_key in self._raft_settings:
  389. self._updateRaftThickness()
  390. rebuild_me = True
  391. if setting_key in self._extra_z_settings:
  392. self._updateExtraZClearance()
  393. rebuild_me = True
  394. if rebuild_me:
  395. self.rebuild()
  396. def hasErrors(self):
  397. return self._has_errors
  398. ## Calls _updateDisallowedAreas and makes sure the changes appear in the
  399. # scene.
  400. #
  401. # This is required for a signal to trigger the update in one go. The
  402. # ``_updateDisallowedAreas`` method itself shouldn't call ``rebuild``,
  403. # since there may be other changes before it needs to be rebuilt, which
  404. # would hit performance.
  405. def _updateDisallowedAreasAndRebuild(self):
  406. self._updateDisallowedAreas()
  407. self.rebuild()
  408. def _updateDisallowedAreas(self):
  409. if not self._global_container_stack:
  410. return
  411. self._error_areas = []
  412. extruder_manager = ExtruderManager.getInstance()
  413. used_extruders = extruder_manager.getUsedExtruderStacks()
  414. disallowed_border_size = self._getEdgeDisallowedSize()
  415. if not used_extruders:
  416. # If no extruder is used, assume that the active extruder is used (else nothing is drawn)
  417. if extruder_manager.getActiveExtruderStack():
  418. used_extruders = [extruder_manager.getActiveExtruderStack()]
  419. else:
  420. used_extruders = [self._global_container_stack]
  421. result_areas = self._computeDisallowedAreasStatic(disallowed_border_size, used_extruders) #Normal machine disallowed areas can always be added.
  422. prime_areas = self._computeDisallowedAreasPrime(disallowed_border_size, used_extruders)
  423. prime_disallowed_areas = self._computeDisallowedAreasStatic(0, used_extruders) #Where the priming is not allowed to happen. This is not added to the result, just for collision checking.
  424. #Check if prime positions intersect with disallowed areas.
  425. for extruder in used_extruders:
  426. extruder_id = extruder.getId()
  427. collision = False
  428. for prime_polygon in prime_areas[extruder_id]:
  429. for disallowed_polygon in prime_disallowed_areas[extruder_id]:
  430. if prime_polygon.intersectsPolygon(disallowed_polygon) is not None:
  431. collision = True
  432. break
  433. if collision:
  434. break
  435. #Also check other prime positions (without additional offset).
  436. for other_extruder_id in prime_areas:
  437. if extruder_id == other_extruder_id: #It is allowed to collide with itself.
  438. continue
  439. for other_prime_polygon in prime_areas[other_extruder_id]:
  440. if prime_polygon.intersectsPolygon(other_prime_polygon):
  441. collision = True
  442. break
  443. if collision:
  444. break
  445. if collision:
  446. break
  447. result_areas[extruder_id].extend(prime_areas[extruder_id])
  448. nozzle_disallowed_areas = extruder.getProperty("nozzle_disallowed_areas", "value")
  449. for area in nozzle_disallowed_areas:
  450. polygon = Polygon(numpy.array(area, numpy.float32))
  451. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(disallowed_border_size))
  452. result_areas[extruder_id].append(polygon) #Don't perform the offset on these.
  453. # Add prime tower location as disallowed area.
  454. prime_tower_collision = False
  455. prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
  456. for extruder_id in prime_tower_areas:
  457. for prime_tower_area in prime_tower_areas[extruder_id]:
  458. for area in result_areas[extruder_id]:
  459. if prime_tower_area.intersectsPolygon(area) is not None:
  460. prime_tower_collision = True
  461. break
  462. if prime_tower_collision: #Already found a collision.
  463. break
  464. if not prime_tower_collision:
  465. result_areas[extruder_id].extend(prime_tower_areas[extruder_id])
  466. else:
  467. self._error_areas.extend(prime_tower_areas[extruder_id])
  468. self._has_errors = len(self._error_areas) > 0
  469. self._disallowed_areas = []
  470. for extruder_id in result_areas:
  471. self._disallowed_areas.extend(result_areas[extruder_id])
  472. ## Computes the disallowed areas for objects that are printed with print
  473. # features.
  474. #
  475. # This means that the brim, travel avoidance and such will be applied to
  476. # these features.
  477. #
  478. # \return A dictionary with for each used extruder ID the disallowed areas
  479. # where that extruder may not print.
  480. def _computeDisallowedAreasPrinted(self, used_extruders):
  481. result = {}
  482. for extruder in used_extruders:
  483. result[extruder.getId()] = []
  484. #Currently, the only normally printed object is the prime tower.
  485. if ExtruderManager.getInstance().getResolveOrValue("prime_tower_enable") == True:
  486. prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
  487. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  488. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  489. prime_tower_x = self._global_container_stack.getProperty("prime_tower_position_x", "value")
  490. prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value")
  491. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  492. prime_tower_x = prime_tower_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  493. prime_tower_y = prime_tower_y + machine_depth / 2
  494. prime_tower_area = Polygon([
  495. [prime_tower_x - prime_tower_size, prime_tower_y - prime_tower_size],
  496. [prime_tower_x, prime_tower_y - prime_tower_size],
  497. [prime_tower_x, prime_tower_y],
  498. [prime_tower_x - prime_tower_size, prime_tower_y],
  499. ])
  500. prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
  501. for extruder in used_extruders:
  502. result[extruder.getId()].append(prime_tower_area) #The prime tower location is the same for each extruder, regardless of offset.
  503. return result
  504. ## Computes the disallowed areas for the prime locations.
  505. #
  506. # These are special because they are not subject to things like brim or
  507. # travel avoidance. They do get a dilute with the border size though
  508. # because they may not intersect with brims and such of other objects.
  509. #
  510. # \param border_size The size with which to offset the disallowed areas
  511. # due to skirt, brim, travel avoid distance, etc.
  512. # \param used_extruders The extruder stacks to generate disallowed areas
  513. # for.
  514. # \return A dictionary with for each used extruder ID the prime areas.
  515. def _computeDisallowedAreasPrime(self, border_size, used_extruders):
  516. result = {}
  517. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  518. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  519. for extruder in used_extruders:
  520. prime_x = extruder.getProperty("extruder_prime_pos_x", "value")
  521. prime_y = - extruder.getProperty("extruder_prime_pos_y", "value")
  522. #Ignore extruder prime position if it is not set
  523. if prime_x == 0 and prime_y == 0:
  524. result[extruder.getId()] = []
  525. continue
  526. if not self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  527. prime_x = prime_x - machine_width / 2 #Offset by half machine_width and _depth to put the origin in the front-left.
  528. prime_y = prime_y + machine_depth / 2
  529. prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
  530. prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  531. prime_polygon = prime_polygon.translate(prime_x, prime_y)
  532. result[extruder.getId()] = [prime_polygon]
  533. return result
  534. ## Computes the disallowed areas that are statically placed in the machine.
  535. #
  536. # It computes different disallowed areas depending on the offset of the
  537. # extruder. The resulting dictionary will therefore have an entry for each
  538. # extruder that is used.
  539. #
  540. # \param border_size The size with which to offset the disallowed areas
  541. # due to skirt, brim, travel avoid distance, etc.
  542. # \param used_extruders The extruder stacks to generate disallowed areas
  543. # for.
  544. # \return A dictionary with for each used extruder ID the disallowed areas
  545. # where that extruder may not print.
  546. def _computeDisallowedAreasStatic(self, border_size, used_extruders):
  547. #Convert disallowed areas to polygons and dilate them.
  548. machine_disallowed_polygons = []
  549. for area in self._global_container_stack.getProperty("machine_disallowed_areas", "value"):
  550. polygon = Polygon(numpy.array(area, numpy.float32))
  551. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  552. machine_disallowed_polygons.append(polygon)
  553. result = {}
  554. for extruder in used_extruders:
  555. extruder_id = extruder.getId()
  556. offset_x = extruder.getProperty("machine_nozzle_offset_x", "value")
  557. if offset_x is None:
  558. offset_x = 0
  559. offset_y = extruder.getProperty("machine_nozzle_offset_y", "value")
  560. if offset_y is None:
  561. offset_y = 0
  562. result[extruder_id] = []
  563. for polygon in machine_disallowed_polygons:
  564. result[extruder_id].append(polygon.translate(offset_x, offset_y)) #Compensate for the nozzle offset of this extruder.
  565. #Add the border around the edge of the build volume.
  566. left_unreachable_border = 0
  567. right_unreachable_border = 0
  568. top_unreachable_border = 0
  569. bottom_unreachable_border = 0
  570. #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.
  571. for other_extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  572. other_offset_x = other_extruder.getProperty("machine_nozzle_offset_x", "value")
  573. other_offset_y = other_extruder.getProperty("machine_nozzle_offset_y", "value")
  574. left_unreachable_border = min(left_unreachable_border, other_offset_x - offset_x)
  575. right_unreachable_border = max(right_unreachable_border, other_offset_x - offset_x)
  576. top_unreachable_border = min(top_unreachable_border, other_offset_y - offset_y)
  577. bottom_unreachable_border = max(bottom_unreachable_border, other_offset_y - offset_y)
  578. half_machine_width = self._global_container_stack.getProperty("machine_width", "value") / 2
  579. half_machine_depth = self._global_container_stack.getProperty("machine_depth", "value") / 2
  580. if self._shape != "elliptic":
  581. if border_size - left_unreachable_border > 0:
  582. result[extruder_id].append(Polygon(numpy.array([
  583. [-half_machine_width, -half_machine_depth],
  584. [-half_machine_width, half_machine_depth],
  585. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  586. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  587. ], numpy.float32)))
  588. if border_size + right_unreachable_border > 0:
  589. result[extruder_id].append(Polygon(numpy.array([
  590. [half_machine_width, half_machine_depth],
  591. [half_machine_width, -half_machine_depth],
  592. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  593. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  594. ], numpy.float32)))
  595. if border_size + bottom_unreachable_border > 0:
  596. result[extruder_id].append(Polygon(numpy.array([
  597. [-half_machine_width, half_machine_depth],
  598. [half_machine_width, half_machine_depth],
  599. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  600. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  601. ], numpy.float32)))
  602. if border_size - top_unreachable_border > 0:
  603. result[extruder_id].append(Polygon(numpy.array([
  604. [half_machine_width, -half_machine_depth],
  605. [-half_machine_width, -half_machine_depth],
  606. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  607. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  608. ], numpy.float32)))
  609. else:
  610. sections = 32
  611. arc_vertex = [0, half_machine_depth - border_size]
  612. for i in range(0, sections):
  613. quadrant = math.floor(4 * i / sections)
  614. vertices = []
  615. if quadrant == 0:
  616. vertices.append([-half_machine_width, half_machine_depth])
  617. elif quadrant == 1:
  618. vertices.append([-half_machine_width, -half_machine_depth])
  619. elif quadrant == 2:
  620. vertices.append([half_machine_width, -half_machine_depth])
  621. elif quadrant == 3:
  622. vertices.append([half_machine_width, half_machine_depth])
  623. vertices.append(arc_vertex)
  624. angle = 2 * math.pi * (i + 1) / sections
  625. arc_vertex = [-(half_machine_width - border_size) * math.sin(angle), (half_machine_depth - border_size) * math.cos(angle)]
  626. vertices.append(arc_vertex)
  627. result[extruder_id].append(Polygon(numpy.array(vertices, numpy.float32)))
  628. if border_size > 0:
  629. result[extruder_id].append(Polygon(numpy.array([
  630. [-half_machine_width, -half_machine_depth],
  631. [-half_machine_width, half_machine_depth],
  632. [-half_machine_width + border_size, 0]
  633. ], numpy.float32)))
  634. result[extruder_id].append(Polygon(numpy.array([
  635. [-half_machine_width, half_machine_depth],
  636. [ half_machine_width, half_machine_depth],
  637. [ 0, half_machine_depth - border_size]
  638. ], numpy.float32)))
  639. result[extruder_id].append(Polygon(numpy.array([
  640. [ half_machine_width, half_machine_depth],
  641. [ half_machine_width, -half_machine_depth],
  642. [ half_machine_width - border_size, 0]
  643. ], numpy.float32)))
  644. result[extruder_id].append(Polygon(numpy.array([
  645. [ half_machine_width,-half_machine_depth],
  646. [-half_machine_width,-half_machine_depth],
  647. [ 0, -half_machine_depth + border_size]
  648. ], numpy.float32)))
  649. return result
  650. ## Private convenience function to get a setting from the adhesion
  651. # extruder.
  652. #
  653. # \param setting_key The key of the setting to get.
  654. # \param property The property to get from the setting.
  655. # \return The property of the specified setting in the adhesion extruder.
  656. def _getSettingFromAdhesionExtruder(self, setting_key, property = "value"):
  657. return self._getSettingFromExtruder(setting_key, "adhesion_extruder_nr", property)
  658. ## Private convenience function to get a setting from every extruder.
  659. #
  660. # For single extrusion machines, this gets the setting from the global
  661. # stack.
  662. #
  663. # \return A sequence of setting values, one for each extruder.
  664. def _getSettingFromAllExtruders(self, setting_key, property = "value"):
  665. all_values = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, property)
  666. all_types = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "type")
  667. for i in range(len(all_values)):
  668. if not all_values[i] and (all_types[i] == "int" or all_types[i] == "float"):
  669. all_values[i] = 0
  670. return all_values
  671. ## Private convenience function to get a setting from the support infill
  672. # extruder.
  673. #
  674. # \param setting_key The key of the setting to get.
  675. # \param property The property to get from the setting.
  676. # \return The property of the specified setting in the support infill
  677. # extruder.
  678. def _getSettingFromSupportInfillExtruder(self, setting_key, property = "value"):
  679. return self._getSettingFromExtruder(setting_key, "support_infill_extruder_nr", property)
  680. ## Helper function to get a setting from an extruder specified in another
  681. # setting.
  682. #
  683. # \param setting_key The key of the setting to get.
  684. # \param extruder_setting_key The key of the setting that specifies from
  685. # which extruder to get the setting, if there are multiple extruders.
  686. # \param property The property to get from the setting.
  687. # \return The property of the specified setting in the specified extruder.
  688. def _getSettingFromExtruder(self, setting_key, extruder_setting_key, property = "value"):
  689. multi_extrusion = self._global_container_stack.getProperty("machine_extruder_count", "value") > 1
  690. if not multi_extrusion:
  691. stack = self._global_container_stack
  692. else:
  693. extruder_index = self._global_container_stack.getProperty(extruder_setting_key, "value")
  694. if extruder_index == "-1": # If extruder index is -1 use global instead
  695. stack = self._global_container_stack
  696. else:
  697. extruder_stack_id = ExtruderManager.getInstance().extruderIds[str(extruder_index)]
  698. stack = ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  699. value = stack.getProperty(setting_key, property)
  700. setting_type = stack.getProperty(setting_key, "type")
  701. if not value and (setting_type == "int" or setting_type == "float"):
  702. return 0
  703. return value
  704. ## Convenience function to calculate the disallowed radius around the edge.
  705. #
  706. # This disallowed radius is to allow for space around the models that is
  707. # not part of the collision radius, such as bed adhesion (skirt/brim/raft)
  708. # and travel avoid distance.
  709. def _getEdgeDisallowedSize(self):
  710. if not self._global_container_stack:
  711. return 0
  712. container_stack = self._global_container_stack
  713. # If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
  714. if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  715. return 0.1 # Return a very small value, so we do draw disallowed area's near the edges.
  716. adhesion_type = container_stack.getProperty("adhesion_type", "value")
  717. if adhesion_type == "skirt":
  718. skirt_distance = self._getSettingFromAdhesionExtruder("skirt_gap")
  719. skirt_line_count = self._getSettingFromAdhesionExtruder("skirt_line_count")
  720. bed_adhesion_size = skirt_distance + (skirt_line_count * self._getSettingFromAdhesionExtruder("skirt_brim_line_width"))
  721. if len(ExtruderManager.getInstance().getUsedExtruderStacks()) > 1:
  722. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  723. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  724. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  725. for value in extruder_values:
  726. bed_adhesion_size += value
  727. elif adhesion_type == "brim":
  728. bed_adhesion_size = self._getSettingFromAdhesionExtruder("brim_line_count") * self._getSettingFromAdhesionExtruder("skirt_brim_line_width")
  729. if self._global_container_stack.getProperty("machine_extruder_count", "value") > 1:
  730. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  731. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  732. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  733. for value in extruder_values:
  734. bed_adhesion_size += value
  735. elif adhesion_type == "raft":
  736. bed_adhesion_size = self._getSettingFromAdhesionExtruder("raft_margin")
  737. elif adhesion_type == "none":
  738. bed_adhesion_size = 0
  739. else:
  740. raise Exception("Unknown bed adhesion type. Did you forget to update the build volume calculations for your new bed adhesion type?")
  741. support_expansion = 0
  742. if self._getSettingFromSupportInfillExtruder("support_offset") and self._global_container_stack.getProperty("support_enable", "value"):
  743. support_expansion += self._getSettingFromSupportInfillExtruder("support_offset")
  744. farthest_shield_distance = 0
  745. if container_stack.getProperty("draft_shield_enabled", "value"):
  746. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("draft_shield_dist", "value"))
  747. if container_stack.getProperty("ooze_shield_enabled", "value"):
  748. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("ooze_shield_dist", "value"))
  749. move_from_wall_radius = 0 # Moves that start from outer wall.
  750. move_from_wall_radius = max(move_from_wall_radius, max(self._getSettingFromAllExtruders("infill_wipe_dist")))
  751. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  752. avoid_enabled_per_extruder = [stack.getProperty("travel_avoid_other_parts","value") for stack in used_extruders]
  753. travel_avoid_distance_per_extruder = [stack.getProperty("travel_avoid_distance", "value") for stack in used_extruders]
  754. for avoid_other_parts_enabled, avoid_distance in zip(avoid_enabled_per_extruder, travel_avoid_distance_per_extruder): #For each extruder (or just global).
  755. if avoid_other_parts_enabled:
  756. move_from_wall_radius = max(move_from_wall_radius, avoid_distance)
  757. # Now combine our different pieces of data to get the final border size.
  758. # Support expansion is added to the bed adhesion, since the bed adhesion goes around support.
  759. # Support expansion is added to farthest shield distance, since the shields go around support.
  760. border_size = max(move_from_wall_radius, support_expansion + farthest_shield_distance, support_expansion + bed_adhesion_size)
  761. return border_size
  762. def _clamp(self, value, min_value, max_value):
  763. return max(min(value, max_value), min_value)
  764. _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"]
  765. _raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap"]
  766. _extra_z_settings = ["retraction_hop_enabled", "retraction_hop"]
  767. _prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "extruder_prime_pos_z"]
  768. _tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y"]
  769. _ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
  770. _distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts"]
  771. _extruder_settings = ["support_enable", "support_interface_enable", "support_infill_extruder_nr", "support_extruder_nr_layer_0", "support_interface_extruder_nr", "brim_line_count", "adhesion_extruder_nr", "adhesion_type"] #Settings that can affect which extruders are used.