ModelChecker.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. # Copyright (c) 2018 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os
  4. from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, pyqtProperty, QTimer
  5. from UM.Application import Application
  6. from UM.Extension import Extension
  7. from UM.Logger import Logger
  8. from UM.Message import Message
  9. from UM.Scene.Camera import Camera
  10. from UM.i18n import i18nCatalog
  11. from UM.PluginRegistry import PluginRegistry
  12. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  13. catalog = i18nCatalog("cura")
  14. class ModelChecker(QObject, Extension):
  15. onChanged = pyqtSignal()
  16. """Signal that gets emitted when anything changed that we need to check."""
  17. def __init__(self):
  18. super().__init__()
  19. self._button_view = None
  20. self._caution_message = Message("", #Message text gets set when the message gets shown, to display the models in question.
  21. lifetime = 0,
  22. title = catalog.i18nc("@info:title", "3D Model Assistant"))
  23. self._change_timer = QTimer()
  24. self._change_timer.setInterval(200)
  25. self._change_timer.setSingleShot(True)
  26. self._change_timer.timeout.connect(self.onChanged)
  27. Application.getInstance().initializationFinished.connect(self._pluginsInitialized)
  28. Application.getInstance().getController().getScene().sceneChanged.connect(self._onChanged)
  29. Application.getInstance().globalContainerStackChanged.connect(self._onChanged)
  30. def _onChanged(self, *args, **kwargs):
  31. # Ignore camera updates.
  32. if len(args) == 0:
  33. self._change_timer.start()
  34. return
  35. if not isinstance(args[0], Camera):
  36. self._change_timer.start()
  37. def _pluginsInitialized(self):
  38. """Called when plug-ins are initialized.
  39. This makes sure that we listen to changes of the material and that the
  40. button is created that indicates warnings with the current set-up.
  41. """
  42. Application.getInstance().getMachineManager().rootMaterialChanged.connect(self.onChanged)
  43. self._createView()
  44. def checkObjectsForShrinkage(self):
  45. shrinkage_threshold = 100.5 #From what shrinkage percentage a warning will be issued about the model size.
  46. warning_size_xy = 150 #The horizontal size of a model that would be too large when dealing with shrinking materials.
  47. warning_size_z = 100 #The vertical size of a model that would be too large when dealing with shrinking materials.
  48. # This function can be triggered in the middle of a machine change, so do not proceed if the machine change
  49. # has not done yet.
  50. global_container_stack = Application.getInstance().getGlobalContainerStack()
  51. if global_container_stack is None:
  52. return False
  53. material_shrinkage = self._getMaterialShrinkage()
  54. warning_nodes = []
  55. # Check node material shrinkage and bounding box size
  56. for node in self.sliceableNodes():
  57. node_extruder_position = node.callDecoration("getActiveExtruderPosition")
  58. if node_extruder_position is None:
  59. continue
  60. # This function can be triggered in the middle of a machine change, so do not proceed if the machine change
  61. # has not done yet.
  62. try:
  63. global_container_stack.extruderList[int(node_extruder_position)]
  64. except IndexError:
  65. Application.getInstance().callLater(lambda: self.onChanged.emit())
  66. return False
  67. if material_shrinkage > shrinkage_threshold:
  68. bbox = node.getBoundingBox()
  69. if bbox is not None and (bbox.width >= warning_size_xy or bbox.depth >= warning_size_xy or bbox.height >= warning_size_z):
  70. warning_nodes.append(node)
  71. self._caution_message.setText(catalog.i18nc(
  72. "@info:status",
  73. "<p>One or more 3D models may not print optimally due to the model size and material configuration:</p>\n"
  74. "<p>{model_names}</p>\n"
  75. "<p>Find out how to ensure the best possible print quality and reliability.</p>\n"
  76. "<p><a href=\"https://ultimaker.com/3D-model-assistant\">View print quality guide</a></p>"
  77. ).format(model_names = ", ".join([n.getName() for n in warning_nodes])))
  78. return len(warning_nodes) > 0
  79. def sliceableNodes(self):
  80. # Add all sliceable scene nodes to check
  81. scene = Application.getInstance().getController().getScene()
  82. for node in DepthFirstIterator(scene.getRoot()):
  83. if node.callDecoration("isSliceable"):
  84. yield node
  85. def _createView(self):
  86. """Creates the view used by show popup.
  87. The view is saved because of the fairly aggressive garbage collection.
  88. """
  89. Logger.log("d", "Creating model checker view.")
  90. # Create the plugin dialog component
  91. path = os.path.join(PluginRegistry.getInstance().getPluginPath("ModelChecker"), "ModelChecker.qml")
  92. self._button_view = Application.getInstance().createQmlComponent(path, {"manager": self})
  93. # The qml is only the button
  94. Application.getInstance().addAdditionalComponent("jobSpecsButton", self._button_view)
  95. Logger.log("d", "Model checker view created.")
  96. @pyqtProperty(bool, notify = onChanged)
  97. def hasWarnings(self):
  98. danger_shrinkage = self.checkObjectsForShrinkage()
  99. return any((danger_shrinkage, )) #If any of the checks fail, show the warning button.
  100. @pyqtSlot()
  101. def showWarnings(self):
  102. self._caution_message.show()
  103. def _getMaterialShrinkage(self) -> float:
  104. global_container_stack = Application.getInstance().getGlobalContainerStack()
  105. if global_container_stack is None:
  106. return 100
  107. return global_container_stack.getProperty("material_shrinkage_percentage", "value")