BuildVolume.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  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._depth / 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.addVertex(0, min_h - z_fight_distance, 0)
  189. mb.addArc(max_w, Vector.Unit_Y, center = Vector(0, min_h - z_fight_distance, 0))
  190. sections = mb.getVertexCount() - 1 # Center point is not an arc section
  191. indices = []
  192. for n in range(0, sections - 1):
  193. indices.append([0, n + 2, n + 1])
  194. mb.addIndices(numpy.asarray(indices, dtype = numpy.int32))
  195. mb.calculateNormals()
  196. for n in range(0, mb.getVertexCount()):
  197. v = mb.getVertex(n)
  198. mb.setVertexUVCoordinates(n, v[0], v[2] * aspect)
  199. self._grid_mesh = mb.build().getTransformed(scale_matrix)
  200. # Indication of the machine origin
  201. if self._global_container_stack.getProperty("machine_center_is_zero", "value"):
  202. origin = (Vector(min_w, min_h, min_d) + Vector(max_w, min_h, max_d)) / 2
  203. else:
  204. origin = Vector(min_w, min_h, max_d)
  205. mb = MeshBuilder()
  206. mb.addCube(
  207. width = self._origin_line_length,
  208. height = self._origin_line_width,
  209. depth = self._origin_line_width,
  210. center = origin + Vector(self._origin_line_length / 2, 0, 0),
  211. color = self.XAxisColor
  212. )
  213. mb.addCube(
  214. width = self._origin_line_width,
  215. height = self._origin_line_length,
  216. depth = self._origin_line_width,
  217. center = origin + Vector(0, self._origin_line_length / 2, 0),
  218. color = self.YAxisColor
  219. )
  220. mb.addCube(
  221. width = self._origin_line_width,
  222. height = self._origin_line_width,
  223. depth = self._origin_line_length,
  224. center = origin - Vector(0, 0, self._origin_line_length / 2),
  225. color = self.ZAxisColor
  226. )
  227. self._origin_mesh = mb.build()
  228. disallowed_area_height = 0.1
  229. disallowed_area_size = 0
  230. if self._disallowed_areas:
  231. mb = MeshBuilder()
  232. color = Color(0.0, 0.0, 0.0, 0.15)
  233. for polygon in self._disallowed_areas:
  234. points = polygon.getPoints()
  235. if len(points) == 0:
  236. continue
  237. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  238. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height, self._clamp(points[0][1], min_d, max_d))
  239. for point in points:
  240. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height, self._clamp(point[1], min_d, max_d))
  241. mb.addFace(first, previous_point, new_point, color = color)
  242. previous_point = new_point
  243. # Find the largest disallowed area to exclude it from the maximum scale bounds.
  244. # This is a very nasty hack. This pretty much only works for UM machines.
  245. # This disallowed area_size needs a -lot- of rework at some point in the future: TODO
  246. 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.
  247. size = abs(numpy.max(points[:, 1]) - numpy.min(points[:, 1]))
  248. else:
  249. size = 0
  250. disallowed_area_size = max(size, disallowed_area_size)
  251. self._disallowed_area_mesh = mb.build()
  252. else:
  253. self._disallowed_area_mesh = None
  254. if self._error_areas:
  255. mb = MeshBuilder()
  256. for error_area in self._error_areas:
  257. color = Color(1.0, 0.0, 0.0, 0.5)
  258. points = error_area.getPoints()
  259. first = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  260. self._clamp(points[0][1], min_d, max_d))
  261. previous_point = Vector(self._clamp(points[0][0], min_w, max_w), disallowed_area_height,
  262. self._clamp(points[0][1], min_d, max_d))
  263. for point in points:
  264. new_point = Vector(self._clamp(point[0], min_w, max_w), disallowed_area_height,
  265. self._clamp(point[1], min_d, max_d))
  266. mb.addFace(first, previous_point, new_point, color=color)
  267. previous_point = new_point
  268. self._error_mesh = mb.build()
  269. else:
  270. self._error_mesh = None
  271. self._volume_aabb = AxisAlignedBox(
  272. minimum = Vector(min_w, min_h - 1.0, min_d),
  273. maximum = Vector(max_w, max_h - self._raft_thickness, max_d))
  274. bed_adhesion_size = self._getEdgeDisallowedSize()
  275. # As this works better for UM machines, we only add the disallowed_area_size for the z direction.
  276. # This is probably wrong in all other cases. TODO!
  277. # The +1 and -1 is added as there is always a bit of extra room required to work properly.
  278. scale_to_max_bounds = AxisAlignedBox(
  279. minimum = Vector(min_w + bed_adhesion_size + 1, min_h, min_d + disallowed_area_size - bed_adhesion_size + 1),
  280. maximum = Vector(max_w - bed_adhesion_size - 1, max_h - self._raft_thickness, max_d - disallowed_area_size + bed_adhesion_size - 1)
  281. )
  282. Application.getInstance().getController().getScene()._maximum_bounds = scale_to_max_bounds
  283. def getBoundingBox(self):
  284. return self._volume_aabb
  285. def getRaftThickness(self):
  286. return self._raft_thickness
  287. def _updateRaftThickness(self):
  288. old_raft_thickness = self._raft_thickness
  289. self._adhesion_type = self._global_container_stack.getProperty("adhesion_type", "value")
  290. self._raft_thickness = 0.0
  291. if self._adhesion_type == "raft":
  292. self._raft_thickness = (
  293. self._global_container_stack.getProperty("raft_base_thickness", "value") +
  294. self._global_container_stack.getProperty("raft_interface_thickness", "value") +
  295. self._global_container_stack.getProperty("raft_surface_layers", "value") *
  296. self._global_container_stack.getProperty("raft_surface_thickness", "value") +
  297. self._global_container_stack.getProperty("raft_airgap", "value"))
  298. # Rounding errors do not matter, we check if raft_thickness has changed at all
  299. if old_raft_thickness != self._raft_thickness:
  300. self.setPosition(Vector(0, -self._raft_thickness, 0), SceneNode.TransformSpace.World)
  301. self.raftThicknessChanged.emit()
  302. ## Update the build volume visualization
  303. def _onStackChanged(self):
  304. if self._global_container_stack:
  305. self._global_container_stack.propertyChanged.disconnect(self._onSettingPropertyChanged)
  306. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  307. for extruder in extruders:
  308. extruder.propertyChanged.disconnect(self._onSettingPropertyChanged)
  309. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  310. if self._global_container_stack:
  311. self._global_container_stack.propertyChanged.connect(self._onSettingPropertyChanged)
  312. extruders = ExtruderManager.getInstance().getMachineExtruders(self._global_container_stack.getId())
  313. for extruder in extruders:
  314. extruder.propertyChanged.connect(self._onSettingPropertyChanged)
  315. self._width = self._global_container_stack.getProperty("machine_width", "value")
  316. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  317. if self._global_container_stack.getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  318. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  319. if self._height < machine_height:
  320. self._build_volume_message.show()
  321. else:
  322. self._build_volume_message.hide()
  323. else:
  324. self._height = self._global_container_stack.getProperty("machine_height", "value")
  325. self._build_volume_message.hide()
  326. self._depth = self._global_container_stack.getProperty("machine_depth", "value")
  327. self._shape = self._global_container_stack.getProperty("machine_shape", "value")
  328. self._updateDisallowedAreas()
  329. self._updateRaftThickness()
  330. self.rebuild()
  331. def _onSettingPropertyChanged(self, setting_key, property_name):
  332. if property_name != "value":
  333. return
  334. rebuild_me = False
  335. if setting_key == "print_sequence":
  336. machine_height = self._global_container_stack.getProperty("machine_height", "value")
  337. if Application.getInstance().getGlobalContainerStack().getProperty("print_sequence", "value") == "one_at_a_time" and len(self._scene_objects) > 1:
  338. self._height = min(self._global_container_stack.getProperty("gantry_height", "value"), machine_height)
  339. if self._height < machine_height:
  340. self._build_volume_message.show()
  341. else:
  342. self._build_volume_message.hide()
  343. else:
  344. self._height = self._global_container_stack.getProperty("machine_height", "value")
  345. self._build_volume_message.hide()
  346. rebuild_me = True
  347. 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:
  348. self._updateDisallowedAreas()
  349. rebuild_me = True
  350. if setting_key in self._raft_settings:
  351. self._updateRaftThickness()
  352. rebuild_me = True
  353. if rebuild_me:
  354. self.rebuild()
  355. def hasErrors(self):
  356. return self._has_errors
  357. ## Calls _updateDisallowedAreas and makes sure the changes appear in the
  358. # scene.
  359. #
  360. # This is required for a signal to trigger the update in one go. The
  361. # ``_updateDisallowedAreas`` method itself shouldn't call ``rebuild``,
  362. # since there may be other changes before it needs to be rebuilt, which
  363. # would hit performance.
  364. def _updateDisallowedAreasAndRebuild(self):
  365. self._updateDisallowedAreas()
  366. self.rebuild()
  367. def _updateDisallowedAreas(self):
  368. if not self._global_container_stack:
  369. return
  370. self._error_areas = []
  371. extruder_manager = ExtruderManager.getInstance()
  372. used_extruders = extruder_manager.getUsedExtruderStacks()
  373. disallowed_border_size = self._getEdgeDisallowedSize()
  374. if not used_extruders:
  375. # If no extruder is used, assume that the active extruder is used (else nothing is drawn)
  376. if extruder_manager.getActiveExtruderStack():
  377. used_extruders = [extruder_manager.getActiveExtruderStack()]
  378. else:
  379. used_extruders = [self._global_container_stack]
  380. result_areas = self._computeDisallowedAreasStatic(disallowed_border_size, used_extruders) #Normal machine disallowed areas can always be added.
  381. prime_areas = self._computeDisallowedAreasPrime(disallowed_border_size, used_extruders)
  382. 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.
  383. #Check if prime positions intersect with disallowed areas.
  384. for extruder in used_extruders:
  385. extruder_id = extruder.getId()
  386. collision = False
  387. for prime_polygon in prime_areas[extruder_id]:
  388. for disallowed_polygon in prime_disallowed_areas[extruder_id]:
  389. if prime_polygon.intersectsPolygon(disallowed_polygon) is not None:
  390. collision = True
  391. break
  392. if collision:
  393. break
  394. #Also check other prime positions (without additional offset).
  395. for other_extruder_id in prime_areas:
  396. if extruder_id == other_extruder_id: #It is allowed to collide with itself.
  397. continue
  398. for other_prime_polygon in prime_areas[other_extruder_id]:
  399. if prime_polygon.intersectsPolygon(other_prime_polygon):
  400. collision = True
  401. break
  402. if collision:
  403. break
  404. if collision:
  405. break
  406. result_areas[extruder_id].extend(prime_areas[extruder_id])
  407. nozzle_disallowed_areas = extruder.getProperty("nozzle_disallowed_areas", "value")
  408. for area in nozzle_disallowed_areas:
  409. polygon = Polygon(numpy.array(area, numpy.float32))
  410. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(disallowed_border_size))
  411. result_areas[extruder_id].append(polygon) #Don't perform the offset on these.
  412. # Add prime tower location as disallowed area.
  413. prime_tower_collision = False
  414. prime_tower_areas = self._computeDisallowedAreasPrinted(used_extruders)
  415. for extruder_id in prime_tower_areas:
  416. for prime_tower_area in prime_tower_areas[extruder_id]:
  417. for area in result_areas[extruder_id]:
  418. if prime_tower_area.intersectsPolygon(area) is not None:
  419. prime_tower_collision = True
  420. break
  421. if prime_tower_collision: #Already found a collision.
  422. break
  423. if not prime_tower_collision:
  424. result_areas[extruder_id].extend(prime_tower_areas[extruder_id])
  425. else:
  426. self._error_areas.extend(prime_tower_areas[extruder_id])
  427. self._has_errors = len(self._error_areas) > 0
  428. self._disallowed_areas = []
  429. for extruder_id in result_areas:
  430. self._disallowed_areas.extend(result_areas[extruder_id])
  431. ## Computes the disallowed areas for objects that are printed with print
  432. # features.
  433. #
  434. # This means that the brim, travel avoidance and such will be applied to
  435. # these features.
  436. #
  437. # \return A dictionary with for each used extruder ID the disallowed areas
  438. # where that extruder may not print.
  439. def _computeDisallowedAreasPrinted(self, used_extruders):
  440. result = {}
  441. for extruder in used_extruders:
  442. result[extruder.getId()] = []
  443. #Currently, the only normally printed object is the prime tower.
  444. if ExtruderManager.getInstance().getResolveOrValue("prime_tower_enable") == True:
  445. prime_tower_size = self._global_container_stack.getProperty("prime_tower_size", "value")
  446. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  447. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  448. 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.
  449. prime_tower_y = - self._global_container_stack.getProperty("prime_tower_position_y", "value") + machine_depth / 2
  450. prime_tower_area = Polygon([
  451. [prime_tower_x - prime_tower_size, prime_tower_y - prime_tower_size],
  452. [prime_tower_x, prime_tower_y - prime_tower_size],
  453. [prime_tower_x, prime_tower_y],
  454. [prime_tower_x - prime_tower_size, prime_tower_y],
  455. ])
  456. prime_tower_area = prime_tower_area.getMinkowskiHull(Polygon.approximatedCircle(0))
  457. for extruder in used_extruders:
  458. result[extruder.getId()].append(prime_tower_area) #The prime tower location is the same for each extruder, regardless of offset.
  459. return result
  460. ## Computes the disallowed areas for the prime locations.
  461. #
  462. # These are special because they are not subject to things like brim or
  463. # travel avoidance. They do get a dilute with the border size though
  464. # because they may not intersect with brims and such of other objects.
  465. #
  466. # \param border_size The size with which to offset the disallowed areas
  467. # due to skirt, brim, travel avoid distance, etc.
  468. # \param used_extruders The extruder stacks to generate disallowed areas
  469. # for.
  470. # \return A dictionary with for each used extruder ID the prime areas.
  471. def _computeDisallowedAreasPrime(self, border_size, used_extruders):
  472. result = {}
  473. machine_width = self._global_container_stack.getProperty("machine_width", "value")
  474. machine_depth = self._global_container_stack.getProperty("machine_depth", "value")
  475. for extruder in used_extruders:
  476. 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.
  477. prime_y = machine_depth / 2 - extruder.getProperty("extruder_prime_pos_y", "value")
  478. prime_polygon = Polygon.approximatedCircle(PRIME_CLEARANCE)
  479. prime_polygon = prime_polygon.translate(prime_x, prime_y)
  480. prime_polygon = prime_polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  481. result[extruder.getId()] = [prime_polygon]
  482. return result
  483. ## Computes the disallowed areas that are statically placed in the machine.
  484. #
  485. # It computes different disallowed areas depending on the offset of the
  486. # extruder. The resulting dictionary will therefore have an entry for each
  487. # extruder that is used.
  488. #
  489. # \param border_size The size with which to offset the disallowed areas
  490. # due to skirt, brim, travel avoid distance, etc.
  491. # \param used_extruders The extruder stacks to generate disallowed areas
  492. # for.
  493. # \return A dictionary with for each used extruder ID the disallowed areas
  494. # where that extruder may not print.
  495. def _computeDisallowedAreasStatic(self, border_size, used_extruders):
  496. #Convert disallowed areas to polygons and dilate them.
  497. machine_disallowed_polygons = []
  498. for area in self._global_container_stack.getProperty("machine_disallowed_areas", "value"):
  499. polygon = Polygon(numpy.array(area, numpy.float32))
  500. polygon = polygon.getMinkowskiHull(Polygon.approximatedCircle(border_size))
  501. machine_disallowed_polygons.append(polygon)
  502. result = {}
  503. for extruder in used_extruders:
  504. extruder_id = extruder.getId()
  505. offset_x = extruder.getProperty("machine_nozzle_offset_x", "value")
  506. if offset_x is None:
  507. offset_x = 0
  508. offset_y = extruder.getProperty("machine_nozzle_offset_y", "value")
  509. if offset_y is None:
  510. offset_y = 0
  511. result[extruder_id] = []
  512. for polygon in machine_disallowed_polygons:
  513. result[extruder_id].append(polygon.translate(offset_x, offset_y)) #Compensate for the nozzle offset of this extruder.
  514. #Add the border around the edge of the build volume.
  515. left_unreachable_border = 0
  516. right_unreachable_border = 0
  517. top_unreachable_border = 0
  518. bottom_unreachable_border = 0
  519. #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.
  520. for other_extruder in ExtruderManager.getInstance().getActiveExtruderStacks():
  521. other_offset_x = other_extruder.getProperty("machine_nozzle_offset_x", "value")
  522. other_offset_y = other_extruder.getProperty("machine_nozzle_offset_y", "value")
  523. left_unreachable_border = min(left_unreachable_border, other_offset_x - offset_x)
  524. right_unreachable_border = max(right_unreachable_border, other_offset_x - offset_x)
  525. top_unreachable_border = min(top_unreachable_border, other_offset_y - offset_y)
  526. bottom_unreachable_border = max(bottom_unreachable_border, other_offset_y - offset_y)
  527. half_machine_width = self._global_container_stack.getProperty("machine_width", "value") / 2
  528. half_machine_depth = self._global_container_stack.getProperty("machine_depth", "value") / 2
  529. if self._shape != "elliptic":
  530. if border_size - left_unreachable_border > 0:
  531. result[extruder_id].append(Polygon(numpy.array([
  532. [-half_machine_width, -half_machine_depth],
  533. [-half_machine_width, half_machine_depth],
  534. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  535. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  536. ], numpy.float32)))
  537. if border_size + right_unreachable_border > 0:
  538. result[extruder_id].append(Polygon(numpy.array([
  539. [half_machine_width, half_machine_depth],
  540. [half_machine_width, -half_machine_depth],
  541. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  542. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  543. ], numpy.float32)))
  544. if border_size + bottom_unreachable_border > 0:
  545. result[extruder_id].append(Polygon(numpy.array([
  546. [-half_machine_width, half_machine_depth],
  547. [half_machine_width, half_machine_depth],
  548. [half_machine_width - border_size - right_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border],
  549. [-half_machine_width + border_size - left_unreachable_border, half_machine_depth - border_size - bottom_unreachable_border]
  550. ], numpy.float32)))
  551. if border_size - top_unreachable_border > 0:
  552. result[extruder_id].append(Polygon(numpy.array([
  553. [half_machine_width, -half_machine_depth],
  554. [-half_machine_width, -half_machine_depth],
  555. [-half_machine_width + border_size - left_unreachable_border, -half_machine_depth + border_size - top_unreachable_border],
  556. [half_machine_width - border_size - right_unreachable_border, -half_machine_depth + border_size - top_unreachable_border]
  557. ], numpy.float32)))
  558. else:
  559. sections = 32
  560. arc_vertex = [0, half_machine_depth - border_size]
  561. for i in range(0, sections):
  562. quadrant = math.floor(4 * i / sections)
  563. vertices = []
  564. if quadrant == 0:
  565. vertices.append([-half_machine_width, half_machine_depth])
  566. elif quadrant == 1:
  567. vertices.append([-half_machine_width, -half_machine_depth])
  568. elif quadrant == 2:
  569. vertices.append([half_machine_width, -half_machine_depth])
  570. elif quadrant == 3:
  571. vertices.append([half_machine_width, half_machine_depth])
  572. vertices.append(arc_vertex)
  573. angle = 2 * math.pi * (i + 1) / sections
  574. arc_vertex = [-(half_machine_width - border_size) * math.sin(angle), (half_machine_depth - border_size) * math.cos(angle)]
  575. vertices.append(arc_vertex)
  576. result[extruder_id].append(Polygon(numpy.array(vertices, numpy.float32)))
  577. if border_size > 0:
  578. result[extruder_id].append(Polygon(numpy.array([
  579. [-half_machine_width, -half_machine_depth],
  580. [-half_machine_width, half_machine_depth],
  581. [-half_machine_width + border_size, 0]
  582. ], numpy.float32)))
  583. result[extruder_id].append(Polygon(numpy.array([
  584. [-half_machine_width, half_machine_depth],
  585. [ half_machine_width, half_machine_depth],
  586. [ 0, half_machine_depth - border_size]
  587. ], numpy.float32)))
  588. result[extruder_id].append(Polygon(numpy.array([
  589. [ half_machine_width, half_machine_depth],
  590. [ half_machine_width, -half_machine_depth],
  591. [ half_machine_width - border_size, 0]
  592. ], numpy.float32)))
  593. result[extruder_id].append(Polygon(numpy.array([
  594. [ half_machine_width,-half_machine_depth],
  595. [-half_machine_width,-half_machine_depth],
  596. [ 0, -half_machine_depth + border_size]
  597. ], numpy.float32)))
  598. return result
  599. ## Private convenience function to get a setting from the adhesion
  600. # extruder.
  601. #
  602. # \param setting_key The key of the setting to get.
  603. # \param property The property to get from the setting.
  604. # \return The property of the specified setting in the adhesion extruder.
  605. def _getSettingFromAdhesionExtruder(self, setting_key, property = "value"):
  606. return self._getSettingFromExtruder(setting_key, "adhesion_extruder_nr", property)
  607. ## Private convenience function to get a setting from every extruder.
  608. #
  609. # For single extrusion machines, this gets the setting from the global
  610. # stack.
  611. #
  612. # \return A sequence of setting values, one for each extruder.
  613. def _getSettingFromAllExtruders(self, setting_key, property = "value"):
  614. all_values = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, property)
  615. all_types = ExtruderManager.getInstance().getAllExtruderSettings(setting_key, "type")
  616. for i in range(len(all_values)):
  617. if not all_values[i] and (all_types[i] == "int" or all_types[i] == "float"):
  618. all_values[i] = 0
  619. return all_values
  620. ## Private convenience function to get a setting from the support infill
  621. # extruder.
  622. #
  623. # \param setting_key The key of the setting to get.
  624. # \param property The property to get from the setting.
  625. # \return The property of the specified setting in the support infill
  626. # extruder.
  627. def _getSettingFromSupportInfillExtruder(self, setting_key, property = "value"):
  628. return self._getSettingFromExtruder(setting_key, "support_infill_extruder_nr", property)
  629. ## Helper function to get a setting from an extruder specified in another
  630. # setting.
  631. #
  632. # \param setting_key The key of the setting to get.
  633. # \param extruder_setting_key The key of the setting that specifies from
  634. # which extruder to get the setting, if there are multiple extruders.
  635. # \param property The property to get from the setting.
  636. # \return The property of the specified setting in the specified extruder.
  637. def _getSettingFromExtruder(self, setting_key, extruder_setting_key, property = "value"):
  638. multi_extrusion = self._global_container_stack.getProperty("machine_extruder_count", "value") > 1
  639. if not multi_extrusion:
  640. stack = self._global_container_stack
  641. else:
  642. extruder_index = self._global_container_stack.getProperty(extruder_setting_key, "value")
  643. if extruder_index == "-1": # If extruder index is -1 use global instead
  644. stack = self._global_container_stack
  645. else:
  646. extruder_stack_id = ExtruderManager.getInstance().extruderIds[str(extruder_index)]
  647. stack = UM.Settings.ContainerRegistry.getInstance().findContainerStacks(id = extruder_stack_id)[0]
  648. value = stack.getProperty(setting_key, property)
  649. setting_type = stack.getProperty(setting_key, "type")
  650. if not value and (setting_type == "int" or setting_type == "float"):
  651. return 0
  652. return value
  653. ## Convenience function to calculate the disallowed radius around the edge.
  654. #
  655. # This disallowed radius is to allow for space around the models that is
  656. # not part of the collision radius, such as bed adhesion (skirt/brim/raft)
  657. # and travel avoid distance.
  658. def _getEdgeDisallowedSize(self):
  659. if not self._global_container_stack:
  660. return 0
  661. container_stack = self._global_container_stack
  662. # If we are printing one at a time, we need to add the bed adhesion size to the disallowed areas of the objects
  663. if container_stack.getProperty("print_sequence", "value") == "one_at_a_time":
  664. return 0.1 # Return a very small value, so we do draw disallowed area's near the edges.
  665. adhesion_type = container_stack.getProperty("adhesion_type", "value")
  666. if adhesion_type == "skirt":
  667. skirt_distance = self._getSettingFromAdhesionExtruder("skirt_gap")
  668. skirt_line_count = self._getSettingFromAdhesionExtruder("skirt_line_count")
  669. bed_adhesion_size = skirt_distance + (skirt_line_count * self._getSettingFromAdhesionExtruder("skirt_brim_line_width"))
  670. if len(ExtruderManager.getInstance().getUsedExtruderStacks()) > 1:
  671. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  672. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  673. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  674. for value in extruder_values:
  675. bed_adhesion_size += value
  676. elif adhesion_type == "brim":
  677. bed_adhesion_size = self._getSettingFromAdhesionExtruder("brim_line_count") * self._getSettingFromAdhesionExtruder("skirt_brim_line_width")
  678. if self._global_container_stack.getProperty("machine_extruder_count", "value") > 1:
  679. adhesion_extruder_nr = int(self._global_container_stack.getProperty("adhesion_extruder_nr", "value"))
  680. extruder_values = ExtruderManager.getInstance().getAllExtruderValues("skirt_brim_line_width")
  681. del extruder_values[adhesion_extruder_nr] # Remove the value of the adhesion extruder nr.
  682. for value in extruder_values:
  683. bed_adhesion_size += value
  684. elif adhesion_type == "raft":
  685. bed_adhesion_size = self._getSettingFromAdhesionExtruder("raft_margin")
  686. elif adhesion_type == "none":
  687. bed_adhesion_size = 0
  688. else:
  689. raise Exception("Unknown bed adhesion type. Did you forget to update the build volume calculations for your new bed adhesion type?")
  690. support_expansion = 0
  691. if self._getSettingFromSupportInfillExtruder("support_offset") and self._global_container_stack.getProperty("support_enable", "value"):
  692. support_expansion += self._getSettingFromSupportInfillExtruder("support_offset")
  693. farthest_shield_distance = 0
  694. if container_stack.getProperty("draft_shield_enabled", "value"):
  695. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("draft_shield_dist", "value"))
  696. if container_stack.getProperty("ooze_shield_enabled", "value"):
  697. farthest_shield_distance = max(farthest_shield_distance, container_stack.getProperty("ooze_shield_dist", "value"))
  698. move_from_wall_radius = 0 # Moves that start from outer wall.
  699. move_from_wall_radius = max(move_from_wall_radius, max(self._getSettingFromAllExtruders("infill_wipe_dist")))
  700. used_extruders = ExtruderManager.getInstance().getUsedExtruderStacks()
  701. avoid_enabled_per_extruder = [stack.getProperty("travel_avoid_other_parts","value") for stack in used_extruders]
  702. travel_avoid_distance_per_extruder = [stack.getProperty("travel_avoid_distance", "value") for stack in used_extruders]
  703. for avoid_other_parts_enabled, avoid_distance in zip(avoid_enabled_per_extruder, travel_avoid_distance_per_extruder): #For each extruder (or just global).
  704. if avoid_other_parts_enabled:
  705. move_from_wall_radius = max(move_from_wall_radius, avoid_distance)
  706. # Now combine our different pieces of data to get the final border size.
  707. # Support expansion is added to the bed adhesion, since the bed adhesion goes around support.
  708. # Support expansion is added to farthest shield distance, since the shields go around support.
  709. border_size = max(move_from_wall_radius, support_expansion + farthest_shield_distance, support_expansion + bed_adhesion_size)
  710. return border_size
  711. def _clamp(self, value, min_value, max_value):
  712. return max(min(value, max_value), min_value)
  713. _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"]
  714. _raft_settings = ["adhesion_type", "raft_base_thickness", "raft_interface_thickness", "raft_surface_layers", "raft_surface_thickness", "raft_airgap"]
  715. _prime_settings = ["extruder_prime_pos_x", "extruder_prime_pos_y", "extruder_prime_pos_z"]
  716. _tower_settings = ["prime_tower_enable", "prime_tower_size", "prime_tower_position_x", "prime_tower_position_y"]
  717. _ooze_shield_settings = ["ooze_shield_enabled", "ooze_shield_dist"]
  718. _distance_settings = ["infill_wipe_dist", "travel_avoid_distance", "support_offset", "support_enable", "travel_avoid_other_parts"]
  719. _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.