SolidView.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import os.path
  4. from UM.View.View import View
  5. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  6. from UM.Scene.Selection import Selection
  7. from UM.Resources import Resources
  8. from PyQt5.QtGui import QOpenGLContext, QImage
  9. from PyQt5.QtCore import QSize
  10. import numpy as np
  11. import time
  12. from UM.Application import Application
  13. from UM.Logger import Logger
  14. from UM.Message import Message
  15. from UM.Math.Color import Color
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Platform import Platform
  18. from UM.Event import Event
  19. from UM.View.RenderBatch import RenderBatch
  20. from UM.View.GL.OpenGL import OpenGL
  21. from UM.i18n import i18nCatalog
  22. from cura.Settings.ExtruderManager import ExtruderManager
  23. from cura import XRayPass
  24. import math
  25. catalog = i18nCatalog("cura")
  26. class SolidView(View):
  27. """Standard view for mesh models."""
  28. _show_xray_warning_preference = "view/show_xray_warning"
  29. def __init__(self):
  30. super().__init__()
  31. application = Application.getInstance()
  32. application.getPreferences().addPreference("view/show_overhang", True)
  33. application.globalContainerStackChanged.connect(self._onGlobalContainerChanged)
  34. self._enabled_shader = None
  35. self._disabled_shader = None
  36. self._non_printing_shader = None
  37. self._support_mesh_shader = None
  38. self._xray_shader = None
  39. self._xray_pass = None
  40. self._xray_composite_shader = None
  41. self._composite_pass = None
  42. self._extruders_model = None
  43. self._theme = None
  44. self._support_angle = 90
  45. self._global_stack = None
  46. self._old_composite_shader = None
  47. self._old_layer_bindings = None
  48. self._next_xray_checking_time = time.time()
  49. self._xray_checking_update_time = 30.0 # seconds
  50. self._xray_warning_cooldown = 60 * 10 # reshow Model error message every 10 minutes
  51. self._xray_warning_message = Message(
  52. catalog.i18nc("@info:status", "Your model is not manifold. The highlighted areas indicate either missing or extraneous surfaces."),
  53. lifetime = 60 * 5, # leave message for 5 minutes
  54. title = catalog.i18nc("@info:title", "Model errors"),
  55. option_text = catalog.i18nc("@info:option_text", "Do not show this message again"),
  56. option_state = False
  57. )
  58. self._xray_warning_message.optionToggled.connect(self._onDontAskMeAgain)
  59. application.getPreferences().addPreference(self._show_xray_warning_preference, True)
  60. application.engineCreatedSignal.connect(self._onGlobalContainerChanged)
  61. def _onDontAskMeAgain(self, checked: bool) -> None:
  62. Application.getInstance().getPreferences().setValue(self._show_xray_warning_preference, not checked)
  63. def _onGlobalContainerChanged(self) -> None:
  64. if self._global_stack:
  65. try:
  66. self._global_stack.propertyChanged.disconnect(self._onPropertyChanged)
  67. except TypeError:
  68. pass
  69. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  70. extruder_stack.propertyChanged.disconnect(self._onPropertyChanged)
  71. self._global_stack = Application.getInstance().getGlobalContainerStack()
  72. if self._global_stack:
  73. self._global_stack.propertyChanged.connect(self._onPropertyChanged)
  74. for extruder_stack in ExtruderManager.getInstance().getActiveExtruderStacks():
  75. extruder_stack.propertyChanged.connect(self._onPropertyChanged)
  76. self._onPropertyChanged("support_angle", "value") # Force an re-evaluation
  77. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  78. if key != "support_angle" or property_name != "value":
  79. return
  80. # As the rendering is called a *lot* we really, dont want to re-evaluate the property every time. So we store em!
  81. global_container_stack = Application.getInstance().getGlobalContainerStack()
  82. if global_container_stack:
  83. support_extruder_nr = int(global_container_stack.getExtruderPositionValueWithDefault("support_extruder_nr"))
  84. try:
  85. support_angle_stack = global_container_stack.extruderList[support_extruder_nr]
  86. except IndexError:
  87. pass
  88. else:
  89. angle = support_angle_stack.getProperty("support_angle", "value")
  90. if angle is not None:
  91. self._support_angle = angle
  92. def _checkSetup(self):
  93. if not self._extruders_model:
  94. self._extruders_model = Application.getInstance().getExtrudersModel()
  95. if not self._theme:
  96. self._theme = Application.getInstance().getTheme()
  97. if not self._enabled_shader:
  98. self._enabled_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "overhang.shader"))
  99. self._enabled_shader.setUniformValue("u_overhangColor", Color(*self._theme.getColor("model_overhang").getRgb()))
  100. self._enabled_shader.setUniformValue("u_renderError", 0.0)
  101. if not self._disabled_shader:
  102. self._disabled_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "striped.shader"))
  103. self._disabled_shader.setUniformValue("u_diffuseColor1", Color(*self._theme.getColor("model_unslicable").getRgb()))
  104. self._disabled_shader.setUniformValue("u_diffuseColor2", Color(*self._theme.getColor("model_unslicable_alt").getRgb()))
  105. self._disabled_shader.setUniformValue("u_width", 50.0)
  106. if not self._non_printing_shader:
  107. self._non_printing_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "transparent_object.shader"))
  108. self._non_printing_shader.setUniformValue("u_diffuseColor", Color(*self._theme.getColor("model_non_printing").getRgb()))
  109. self._non_printing_shader.setUniformValue("u_opacity", 0.6)
  110. if not self._support_mesh_shader:
  111. self._support_mesh_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "striped.shader"))
  112. self._support_mesh_shader.setUniformValue("u_vertical_stripes", True)
  113. self._support_mesh_shader.setUniformValue("u_width", 5.0)
  114. if not Application.getInstance().getPreferences().getValue(self._show_xray_warning_preference):
  115. self._xray_shader = None
  116. self._xray_composite_shader = None
  117. if self._composite_pass and 'xray' in self._composite_pass.getLayerBindings():
  118. self._composite_pass.setLayerBindings(self._old_layer_bindings)
  119. self._composite_pass.setCompositeShader(self._old_composite_shader)
  120. self._old_layer_bindings = None
  121. self._old_composite_shader = None
  122. self._enabled_shader.setUniformValue("u_renderError", 0.0) # We don't want any error markers!.
  123. self._xray_warning_message.hide()
  124. else:
  125. if not self._xray_shader:
  126. self._xray_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "xray.shader"))
  127. if not self._xray_composite_shader:
  128. self._xray_composite_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "xray_composite.shader"))
  129. theme = Application.getInstance().getTheme()
  130. self._xray_composite_shader.setUniformValue("u_background_color", Color(*theme.getColor("viewport_background").getRgb()))
  131. self._xray_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
  132. self._xray_composite_shader.setUniformValue("u_flat_error_color_mix", 0.) # Don't show flat error color in solid-view.
  133. renderer = self.getRenderer()
  134. if not self._composite_pass or not 'xray' in self._composite_pass.getLayerBindings():
  135. # Currently the RenderPass constructor requires a size > 0
  136. # This should be fixed in RenderPass's constructor.
  137. self._xray_pass = XRayPass.XRayPass(1, 1)
  138. self._enabled_shader.setUniformValue("u_renderError", 1.0) # We don't want any error markers!.
  139. renderer.addRenderPass(self._xray_pass)
  140. if not self._composite_pass:
  141. self._composite_pass = self.getRenderer().getRenderPass("composite")
  142. self._old_layer_bindings = self._composite_pass.getLayerBindings()
  143. self._composite_pass.setLayerBindings(["default", "selection", "xray"])
  144. self._old_composite_shader = self._composite_pass.getCompositeShader()
  145. self._composite_pass.setCompositeShader(self._xray_composite_shader)
  146. def beginRendering(self):
  147. scene = self.getController().getScene()
  148. renderer = self.getRenderer()
  149. self._checkSetup()
  150. global_container_stack = Application.getInstance().getGlobalContainerStack()
  151. if global_container_stack:
  152. if Application.getInstance().getPreferences().getValue("view/show_overhang"):
  153. # Make sure the overhang angle is valid before passing it to the shader
  154. if self._support_angle >= 0 and self._support_angle <= 90:
  155. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(90 - self._support_angle)))
  156. else:
  157. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(0))) #Overhang angle of 0 causes no area at all to be marked as overhang.
  158. else:
  159. self._enabled_shader.setUniformValue("u_overhangAngle", math.cos(math.radians(0)))
  160. disabled_batch = renderer.createRenderBatch(shader = self._disabled_shader)
  161. normal_object_batch = renderer.createRenderBatch(shader = self._enabled_shader)
  162. renderer.addRenderBatch(disabled_batch)
  163. renderer.addRenderBatch(normal_object_batch)
  164. for node in DepthFirstIterator(scene.getRoot()):
  165. if node.render(renderer):
  166. continue
  167. if node.getMeshData() and node.isVisible():
  168. uniforms = {}
  169. shade_factor = 1.0
  170. per_mesh_stack = node.callDecoration("getStack")
  171. extruder_index = node.callDecoration("getActiveExtruderPosition")
  172. if extruder_index is None:
  173. extruder_index = "0"
  174. extruder_index = int(extruder_index)
  175. try:
  176. material_color = self._extruders_model.getItem(extruder_index)["color"]
  177. except KeyError:
  178. material_color = self._extruders_model.defaultColors[0]
  179. if extruder_index != ExtruderManager.getInstance().activeExtruderIndex:
  180. # Shade objects that are printed with the non-active extruder 25% darker
  181. shade_factor = 0.6
  182. try:
  183. # Colors are passed as rgb hex strings (eg "#ffffff"), and the shader needs
  184. # an rgba list of floats (eg [1.0, 1.0, 1.0, 1.0])
  185. uniforms["diffuse_color"] = [
  186. shade_factor * int(material_color[1:3], 16) / 255,
  187. shade_factor * int(material_color[3:5], 16) / 255,
  188. shade_factor * int(material_color[5:7], 16) / 255,
  189. 1.0
  190. ]
  191. # Color the currently selected face-id. (Disable for now.)
  192. #face = Selection.getHoverFace()
  193. uniforms["hover_face"] = -1 #if not face or node != face[0] else face[1]
  194. except ValueError:
  195. pass
  196. if node.callDecoration("isNonPrintingMesh"):
  197. if per_mesh_stack and (node.callDecoration("isInfillMesh") or node.callDecoration("isCuttingMesh")):
  198. renderer.queueNode(node, shader = self._non_printing_shader, uniforms = uniforms, transparent = True)
  199. else:
  200. renderer.queueNode(node, shader = self._non_printing_shader, transparent = True)
  201. elif getattr(node, "_outside_buildarea", False):
  202. disabled_batch.addItem(node.getWorldTransformation(copy = False), node.getMeshData(), normal_transformation = node.getCachedNormalMatrix())
  203. elif per_mesh_stack and node.callDecoration("isSupportMesh"):
  204. # Render support meshes with a vertical stripe that is darker
  205. shade_factor = 0.6
  206. uniforms["diffuse_color_2"] = [
  207. uniforms["diffuse_color"][0] * shade_factor,
  208. uniforms["diffuse_color"][1] * shade_factor,
  209. uniforms["diffuse_color"][2] * shade_factor,
  210. 1.0
  211. ]
  212. renderer.queueNode(node, shader = self._support_mesh_shader, uniforms = uniforms)
  213. else:
  214. normal_object_batch.addItem(node.getWorldTransformation(copy=False), node.getMeshData(), uniforms=uniforms, normal_transformation = node.getCachedNormalMatrix())
  215. if node.callDecoration("isGroup") and Selection.isSelected(node):
  216. renderer.queueNode(scene.getRoot(), mesh = node.getBoundingBoxMesh(), mode = RenderBatch.RenderMode.LineLoop)
  217. def endRendering(self):
  218. # check whether the xray overlay is showing badness
  219. if time.time() > self._next_xray_checking_time\
  220. and Application.getInstance().getPreferences().getValue(self._show_xray_warning_preference):
  221. self._next_xray_checking_time = time.time() + self._xray_checking_update_time
  222. xray_img = self._xray_pass.getOutput()
  223. xray_img = xray_img.convertToFormat(QImage.Format_RGB888)
  224. # We can't just read the image since the pixels are aligned to internal memory positions.
  225. # xray_img.byteCount() != xray_img.width() * xray_img.height() * 3
  226. # The byte count is a little higher sometimes. We need to check the data per line, but fast using Numpy.
  227. # See https://stackoverflow.com/questions/5810970/get-raw-data-from-qimage for a description of the problem.
  228. # We can't use that solution though, since it doesn't perform well in Python.
  229. class QImageArrayView:
  230. """
  231. Class that ducktypes to be a Numpy ndarray.
  232. """
  233. def __init__(self, qimage):
  234. bits_pointer = qimage.bits()
  235. if bits_pointer is None: # If this happens before there is a window.
  236. self.__array_interface__ = {
  237. "shape": (0, 0),
  238. "typestr": "|u4",
  239. "data": (0, False),
  240. "strides": (1, 3),
  241. "version": 3
  242. }
  243. else:
  244. self.__array_interface__ = {
  245. "shape": (qimage.height(), qimage.width()),
  246. "typestr": "|u4", # Use 4 bytes per pixel rather than 3, since Numpy doesn't support 3.
  247. "data": (int(bits_pointer), False),
  248. "strides": (qimage.bytesPerLine(), 3), # This does the magic: For each line, skip the correct number of bytes. Bytes per pixel is always 3 due to QImage.Format.Format_RGB888.
  249. "version": 3
  250. }
  251. array = np.asarray(QImageArrayView(xray_img)).view(np.dtype({
  252. "r": (np.uint8, 0, "red"),
  253. "g": (np.uint8, 1, "green"),
  254. "b": (np.uint8, 2, "blue"),
  255. "a": (np.uint8, 3, "alpha") # Never filled since QImage was reformatted to RGB888.
  256. }), np.recarray)
  257. if np.any(np.mod(array.r, 2)):
  258. self._next_xray_checking_time = time.time() + self._xray_warning_cooldown
  259. self._xray_warning_message.show()
  260. Logger.log("i", "X-Ray overlay found non-manifold pixels.")
  261. def event(self, event):
  262. if event.type == Event.ViewDeactivateEvent:
  263. if self._composite_pass and 'xray' in self._composite_pass.getLayerBindings():
  264. self.getRenderer().removeRenderPass(self._xray_pass)
  265. self._composite_pass.setLayerBindings(self._old_layer_bindings)
  266. self._composite_pass.setCompositeShader(self._old_composite_shader)
  267. self._xray_warning_message.hide()