BuildVolume.py 43 KB

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