CuraSceneNode.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. from copy import deepcopy
  4. from typing import cast, Dict, List, Optional
  5. from UM.Application import Application
  6. from UM.Math.AxisAlignedBox import AxisAlignedBox
  7. from UM.Math.Polygon import Polygon # For typing.
  8. from UM.Scene.SceneNode import SceneNode
  9. from UM.Scene.SceneNodeDecorator import SceneNodeDecorator # To cast the deepcopy of every decorator back to SceneNodeDecorator.
  10. import cura.CuraApplication # To get the build plate.
  11. from cura.Settings.ExtruderStack import ExtruderStack # For typing.
  12. from cura.Settings.SettingOverrideDecorator import SettingOverrideDecorator # For per-object settings.
  13. class CuraSceneNode(SceneNode):
  14. """Scene nodes that are models are only seen when selecting the corresponding build plate
  15. Note that many other nodes can just be UM SceneNode objects.
  16. """
  17. def __init__(self, parent: Optional["SceneNode"] = None, visible: bool = True, name: str = "", no_setting_override: bool = False) -> None:
  18. super().__init__(parent = parent, visible = visible, name = name)
  19. if not no_setting_override:
  20. self.addDecorator(SettingOverrideDecorator()) # Now we always have a getActiveExtruderPosition, unless explicitly disabled
  21. self._outside_buildarea = False
  22. def setOutsideBuildArea(self, new_value: bool) -> None:
  23. self._outside_buildarea = new_value
  24. def isOutsideBuildArea(self) -> bool:
  25. return self._outside_buildarea or self.callDecoration("getBuildPlateNumber") < 0
  26. def isVisible(self) -> bool:
  27. return super().isVisible() and self.callDecoration("getBuildPlateNumber") == cura.CuraApplication.CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  28. def isSelectable(self) -> bool:
  29. return super().isSelectable() and self.callDecoration("getBuildPlateNumber") == cura.CuraApplication.CuraApplication.getInstance().getMultiBuildPlateModel().activeBuildPlate
  30. def isSupportMesh(self) -> bool:
  31. per_mesh_stack = self.callDecoration("getStack")
  32. if not per_mesh_stack:
  33. return False
  34. return per_mesh_stack.getProperty("support_mesh", "value")
  35. def getPrintingExtruder(self) -> Optional[ExtruderStack]:
  36. """Get the extruder used to print this node. If there is no active node, then the extruder in position zero is returned
  37. TODO The best way to do it is by adding the setActiveExtruder decorator to every node when is loaded
  38. """
  39. global_container_stack = Application.getInstance().getGlobalContainerStack()
  40. if global_container_stack is None:
  41. return None
  42. per_mesh_stack = self.callDecoration("getStack")
  43. extruders = global_container_stack.extruderList
  44. # Use the support extruder instead of the active extruder if this is a support_mesh
  45. if per_mesh_stack:
  46. if per_mesh_stack.getProperty("support_mesh", "value"):
  47. return extruders[int(global_container_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))]
  48. # It's only set if you explicitly choose an extruder
  49. extruder_id = self.callDecoration("getActiveExtruder")
  50. for extruder in extruders:
  51. # Find out the extruder if we know the id.
  52. if extruder_id is not None:
  53. if extruder_id == extruder.getId():
  54. return extruder
  55. else: # If the id is unknown, then return the extruder in the position 0
  56. try:
  57. if extruder.getMetaDataEntry("position", default = "0") == "0": # Check if the position is zero
  58. return extruder
  59. except ValueError:
  60. continue
  61. # This point should never be reached
  62. return None
  63. def getDiffuseColor(self) -> List[float]:
  64. """Return the color of the material used to print this model"""
  65. printing_extruder = self.getPrintingExtruder()
  66. material_color = "#808080" # Fallback color
  67. if printing_extruder is not None and printing_extruder.material:
  68. material_color = printing_extruder.material.getMetaDataEntry("color_code", default = material_color)
  69. # Colors are passed as rgb hex strings (eg "#ffffff"), and the shader needs
  70. # an rgba list of floats (eg [1.0, 1.0, 1.0, 1.0])
  71. return [
  72. int(material_color[1:3], 16) / 255,
  73. int(material_color[3:5], 16) / 255,
  74. int(material_color[5:7], 16) / 255,
  75. 1.0
  76. ]
  77. def collidesWithAreas(self, areas: List[Polygon]) -> bool:
  78. """Return if any area collides with the convex hull of this scene node"""
  79. convex_hull = self.callDecoration("getPrintingArea")
  80. if convex_hull:
  81. if not convex_hull.isValid():
  82. return False
  83. # Check for collisions between provided areas and the object
  84. for area in areas:
  85. overlap = convex_hull.intersectsPolygon(area)
  86. if overlap is None:
  87. continue
  88. return True
  89. return False
  90. def _calculateAABB(self) -> None:
  91. """Override of SceneNode._calculateAABB to exclude non-printing-meshes from bounding box"""
  92. self._aabb = None
  93. if self._mesh_data:
  94. self._aabb = self._mesh_data.getExtents(self.getWorldTransformation(copy = False))
  95. else: # If there is no mesh_data, use a bounding box that encompasses the local (0,0,0)
  96. position = self.getWorldPosition()
  97. self._aabb = AxisAlignedBox(minimum = position, maximum = position)
  98. for child in self.getAllChildren():
  99. if child.callDecoration("isNonPrintingMesh"):
  100. # Non-printing-meshes inside a group should not affect push apart or drop to build plate
  101. continue
  102. if not child.getMeshData():
  103. # Nodes without mesh data should not affect bounding boxes of their parents.
  104. continue
  105. if self._aabb is None:
  106. self._aabb = child.getBoundingBox()
  107. else:
  108. self._aabb = self._aabb + child.getBoundingBox()
  109. def __deepcopy__(self, memo: Dict[int, object]) -> "CuraSceneNode":
  110. """Taken from SceneNode, but replaced SceneNode with CuraSceneNode"""
  111. copy = CuraSceneNode(no_setting_override = True) # Setting override will be added later
  112. copy.setTransformation(self.getLocalTransformation(copy= False))
  113. copy.setMeshData(self._mesh_data)
  114. copy.setVisible(cast(bool, deepcopy(self._visible, memo)))
  115. copy._selectable = cast(bool, deepcopy(self._selectable, memo))
  116. copy._name = cast(str, deepcopy(self._name, memo))
  117. for decorator in self._decorators:
  118. copy.addDecorator(cast(SceneNodeDecorator, deepcopy(decorator, memo)))
  119. for child in self._children:
  120. copy.addChild(cast(SceneNode, deepcopy(child, memo)))
  121. self.calculateBoundingBoxMesh()
  122. return copy
  123. def transformChanged(self) -> None:
  124. self._transformChanged()