SimulationView.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. # Copyright (c) 2020 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import sys
  4. from PyQt5.QtCore import Qt
  5. from PyQt5.QtGui import QOpenGLContext
  6. from PyQt5.QtWidgets import QApplication
  7. from UM.Application import Application
  8. from UM.Event import Event, KeyEvent
  9. from UM.Job import Job
  10. from UM.Logger import Logger
  11. from UM.Math.Color import Color
  12. from UM.Math.Matrix import Matrix
  13. from UM.Mesh.MeshBuilder import MeshBuilder
  14. from UM.Message import Message
  15. from UM.Platform import Platform
  16. from UM.PluginRegistry import PluginRegistry
  17. from UM.Qt.QtApplication import QtApplication
  18. from UM.Resources import Resources
  19. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  20. from UM.Scene.Selection import Selection
  21. from UM.Signal import Signal
  22. from UM.View.CompositePass import CompositePass
  23. from UM.View.GL.OpenGL import OpenGL
  24. from UM.View.GL.OpenGLContext import OpenGLContext
  25. from UM.View.GL.ShaderProgram import ShaderProgram
  26. from UM.i18n import i18nCatalog
  27. from cura.CuraView import CuraView
  28. from cura.Scene.ConvexHullNode import ConvexHullNode
  29. from cura.CuraApplication import CuraApplication
  30. from .NozzleNode import NozzleNode
  31. from .SimulationPass import SimulationPass
  32. from .SimulationViewProxy import SimulationViewProxy
  33. import numpy
  34. import os.path
  35. from typing import Optional, TYPE_CHECKING, List, cast
  36. if TYPE_CHECKING:
  37. from UM.Scene.SceneNode import SceneNode
  38. from UM.Scene.Scene import Scene
  39. from UM.Settings.ContainerStack import ContainerStack
  40. catalog = i18nCatalog("cura")
  41. class SimulationView(CuraView):
  42. """The preview layer view. It is used to display g-code paths."""
  43. # Must match SimulationViewMenuComponent.qml
  44. LAYER_VIEW_TYPE_MATERIAL_TYPE = 0
  45. LAYER_VIEW_TYPE_LINE_TYPE = 1
  46. LAYER_VIEW_TYPE_FEEDRATE = 2
  47. LAYER_VIEW_TYPE_THICKNESS = 3
  48. _no_layers_warning_preference = "view/no_layers_warning"
  49. def __init__(self, parent = None) -> None:
  50. super().__init__(parent)
  51. self._max_layers = 0
  52. self._current_layer_num = 0
  53. self._minimum_layer_num = 0
  54. self._current_layer_mesh = None
  55. self._current_layer_jumps = None
  56. self._top_layers_job = None # type: Optional["_CreateTopLayersJob"]
  57. self._activity = False
  58. self._old_max_layers = 0
  59. self._max_paths = 0
  60. self._current_path_num = 0
  61. self._minimum_path_num = 0
  62. self.currentLayerNumChanged.connect(self._onCurrentLayerNumChanged)
  63. self._busy = False
  64. self._simulation_running = False
  65. self._ghost_shader = None # type: Optional["ShaderProgram"]
  66. self._layer_pass = None # type: Optional[SimulationPass]
  67. self._composite_pass = None # type: Optional[CompositePass]
  68. self._old_layer_bindings = None # type: Optional[List[str]]
  69. self._simulationview_composite_shader = None # type: Optional["ShaderProgram"]
  70. self._old_composite_shader = None # type: Optional["ShaderProgram"]
  71. self._max_feedrate = sys.float_info.min
  72. self._min_feedrate = sys.float_info.max
  73. self._max_thickness = sys.float_info.min
  74. self._min_thickness = sys.float_info.max
  75. self._max_line_width = sys.float_info.min
  76. self._min_line_width = sys.float_info.max
  77. self._global_container_stack = None # type: Optional[ContainerStack]
  78. self._proxy = None
  79. self._resetSettings()
  80. self._legend_items = None
  81. self._show_travel_moves = False
  82. self._nozzle_node = None # type: Optional[NozzleNode]
  83. Application.getInstance().getPreferences().addPreference("view/top_layer_count", 5)
  84. Application.getInstance().getPreferences().addPreference("view/only_show_top_layers", False)
  85. Application.getInstance().getPreferences().addPreference("view/force_layer_view_compatibility_mode", False)
  86. Application.getInstance().getPreferences().addPreference("layerview/layer_view_type", 1) # Default to "Line Type".
  87. Application.getInstance().getPreferences().addPreference("layerview/extruder_opacities", "")
  88. Application.getInstance().getPreferences().addPreference("layerview/show_travel_moves", False)
  89. Application.getInstance().getPreferences().addPreference("layerview/show_helpers", True)
  90. Application.getInstance().getPreferences().addPreference("layerview/show_skin", True)
  91. Application.getInstance().getPreferences().addPreference("layerview/show_infill", True)
  92. Application.getInstance().getPreferences().addPreference("layerview/show_starts", True)
  93. self._updateWithPreferences()
  94. self._solid_layers = int(Application.getInstance().getPreferences().getValue("view/top_layer_count"))
  95. self._only_show_top_layers = bool(Application.getInstance().getPreferences().getValue("view/only_show_top_layers"))
  96. self._compatibility_mode = self._evaluateCompatibilityMode()
  97. self._wireprint_warning_message = Message(catalog.i18nc("@info:status", "Cura does not accurately display layers when Wire Printing is enabled."),
  98. title = catalog.i18nc("@info:title", "Simulation View"))
  99. self._slice_first_warning_message = Message(catalog.i18nc("@info:status", "Nothing is shown because you need to slice first."), title = catalog.i18nc("@info:title", "No layers to show"),
  100. option_text = catalog.i18nc("@info:option_text", "Do not show this message again"), option_state = False)
  101. self._slice_first_warning_message.optionToggled.connect(self._onDontAskMeAgain)
  102. CuraApplication.getInstance().getPreferences().addPreference(self._no_layers_warning_preference, True)
  103. QtApplication.getInstance().engineCreatedSignal.connect(self._onEngineCreated)
  104. def _onEngineCreated(self) -> None:
  105. plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
  106. if plugin_path:
  107. self.addDisplayComponent("main", os.path.join(plugin_path, "SimulationViewMainComponent.qml"))
  108. self.addDisplayComponent("menu", os.path.join(plugin_path, "SimulationViewMenuComponent.qml"))
  109. else:
  110. Logger.log("e", "Unable to find the path for %s", self.getPluginId())
  111. def _evaluateCompatibilityMode(self) -> bool:
  112. return OpenGLContext.isLegacyOpenGL() or bool(Application.getInstance().getPreferences().getValue("view/force_layer_view_compatibility_mode"))
  113. def _resetSettings(self) -> None:
  114. self._layer_view_type = 0 # type: int # 0 is material color, 1 is color by linetype, 2 is speed, 3 is layer thickness
  115. self._extruder_count = 0
  116. self._extruder_opacity = [[1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]
  117. self._show_travel_moves = False
  118. self._show_helpers = True
  119. self._show_skin = True
  120. self._show_infill = True
  121. self._show_starts = True
  122. self.resetLayerData()
  123. def getActivity(self) -> bool:
  124. return self._activity
  125. def setActivity(self, activity: bool) -> None:
  126. if self._activity == activity:
  127. return
  128. self._activity = activity
  129. self._updateSliceWarningVisibility()
  130. self.activityChanged.emit()
  131. def getSimulationPass(self) -> SimulationPass:
  132. if not self._layer_pass:
  133. # Currently the RenderPass constructor requires a size > 0
  134. # This should be fixed in RenderPass's constructor.
  135. self._layer_pass = SimulationPass(1, 1)
  136. self._compatibility_mode = self._evaluateCompatibilityMode()
  137. self._layer_pass.setSimulationView(self)
  138. return self._layer_pass
  139. def getCurrentLayer(self) -> int:
  140. return self._current_layer_num
  141. def getMinimumLayer(self) -> int:
  142. return self._minimum_layer_num
  143. def getMaxLayers(self) -> int:
  144. return self._max_layers
  145. def getCurrentPath(self) -> int:
  146. return self._current_path_num
  147. def getMinimumPath(self) -> int:
  148. return self._minimum_path_num
  149. def getMaxPaths(self) -> int:
  150. return self._max_paths
  151. def getNozzleNode(self) -> NozzleNode:
  152. if not self._nozzle_node:
  153. self._nozzle_node = NozzleNode()
  154. return self._nozzle_node
  155. def _onSceneChanged(self, node: "SceneNode") -> None:
  156. if node.getMeshData() is None:
  157. return
  158. self.setActivity(False)
  159. self.calculateMaxLayers()
  160. self.calculateMaxPathsOnLayer(self._current_layer_num)
  161. def isBusy(self) -> bool:
  162. return self._busy
  163. def setBusy(self, busy: bool) -> None:
  164. if busy != self._busy:
  165. self._busy = busy
  166. self.busyChanged.emit()
  167. def isSimulationRunning(self) -> bool:
  168. return self._simulation_running
  169. def setSimulationRunning(self, running: bool) -> None:
  170. self._simulation_running = running
  171. def resetLayerData(self) -> None:
  172. self._current_layer_mesh = None
  173. self._current_layer_jumps = None
  174. self._max_feedrate = sys.float_info.min
  175. self._min_feedrate = sys.float_info.max
  176. self._max_thickness = sys.float_info.min
  177. self._min_thickness = sys.float_info.max
  178. self._max_line_width = sys.float_info.min
  179. self._min_line_width = sys.float_info.max
  180. def beginRendering(self) -> None:
  181. scene = self.getController().getScene()
  182. renderer = self.getRenderer()
  183. if renderer is None:
  184. return
  185. if not self._ghost_shader:
  186. self._ghost_shader = OpenGL.getInstance().createShaderProgram(Resources.getPath(Resources.Shaders, "color.shader"))
  187. theme = CuraApplication.getInstance().getTheme()
  188. if theme is not None:
  189. self._ghost_shader.setUniformValue("u_color", Color(*theme.getColor("layerview_ghost").getRgb()))
  190. for node in DepthFirstIterator(scene.getRoot()):
  191. # We do not want to render ConvexHullNode as it conflicts with the bottom layers.
  192. # However, it is somewhat relevant when the node is selected, so do render it then.
  193. if type(node) is ConvexHullNode and not Selection.isSelected(cast(ConvexHullNode, node).getWatchedNode()):
  194. continue
  195. if not node.render(renderer):
  196. if (node.getMeshData()) and node.isVisible():
  197. renderer.queueNode(node, transparent = True, shader = self._ghost_shader)
  198. def setLayer(self, value: int) -> None:
  199. if self._current_layer_num != value:
  200. self._current_layer_num = value
  201. if self._current_layer_num < 0:
  202. self._current_layer_num = 0
  203. if self._current_layer_num > self._max_layers:
  204. self._current_layer_num = self._max_layers
  205. if self._current_layer_num < self._minimum_layer_num:
  206. self._minimum_layer_num = self._current_layer_num
  207. self._startUpdateTopLayers()
  208. self.currentLayerNumChanged.emit()
  209. def setMinimumLayer(self, value: int) -> None:
  210. if self._minimum_layer_num != value:
  211. self._minimum_layer_num = value
  212. if self._minimum_layer_num < 0:
  213. self._minimum_layer_num = 0
  214. if self._minimum_layer_num > self._max_layers:
  215. self._minimum_layer_num = self._max_layers
  216. if self._minimum_layer_num > self._current_layer_num:
  217. self._current_layer_num = self._minimum_layer_num
  218. self._startUpdateTopLayers()
  219. self.currentLayerNumChanged.emit()
  220. def setPath(self, value: int) -> None:
  221. if self._current_path_num != value:
  222. self._current_path_num = value
  223. if self._current_path_num < 0:
  224. self._current_path_num = 0
  225. if self._current_path_num > self._max_paths:
  226. self._current_path_num = self._max_paths
  227. if self._current_path_num < self._minimum_path_num:
  228. self._minimum_path_num = self._current_path_num
  229. self._startUpdateTopLayers()
  230. self.currentPathNumChanged.emit()
  231. def setMinimumPath(self, value: int) -> None:
  232. if self._minimum_path_num != value:
  233. self._minimum_path_num = value
  234. if self._minimum_path_num < 0:
  235. self._minimum_path_num = 0
  236. if self._minimum_path_num > self._max_layers:
  237. self._minimum_path_num = self._max_layers
  238. if self._minimum_path_num > self._current_path_num:
  239. self._current_path_num = self._minimum_path_num
  240. self._startUpdateTopLayers()
  241. self.currentPathNumChanged.emit()
  242. def setSimulationViewType(self, layer_view_type: int) -> None:
  243. """Set the layer view type
  244. :param layer_view_type: integer as in SimulationView.qml and this class
  245. """
  246. if layer_view_type != self._layer_view_type:
  247. self._layer_view_type = layer_view_type
  248. self.currentLayerNumChanged.emit()
  249. def getSimulationViewType(self) -> int:
  250. """Return the layer view type, integer as in SimulationView.qml and this class"""
  251. return self._layer_view_type
  252. def setExtruderOpacity(self, extruder_nr: int, opacity: float) -> None:
  253. """Set the extruder opacity
  254. :param extruder_nr: 0..15
  255. :param opacity: 0.0 .. 1.0
  256. """
  257. if 0 <= extruder_nr <= 15:
  258. self._extruder_opacity[extruder_nr // 4][extruder_nr % 4] = opacity
  259. self.currentLayerNumChanged.emit()
  260. def getExtruderOpacities(self) -> Matrix:
  261. # NOTE: Extruder opacities are stored in a matrix for (minor) performance reasons (w.r.t. OpenGL/shaders).
  262. # If more than 16 extruders are called for, this should be converted to a sampler1d.
  263. return Matrix(self._extruder_opacity)
  264. def setShowTravelMoves(self, show):
  265. self._show_travel_moves = show
  266. self.currentLayerNumChanged.emit()
  267. def getShowTravelMoves(self):
  268. return self._show_travel_moves
  269. def setShowHelpers(self, show: bool) -> None:
  270. self._show_helpers = show
  271. self.currentLayerNumChanged.emit()
  272. def getShowHelpers(self) -> bool:
  273. return self._show_helpers
  274. def setShowSkin(self, show: bool) -> None:
  275. self._show_skin = show
  276. self.currentLayerNumChanged.emit()
  277. def getShowSkin(self) -> bool:
  278. return self._show_skin
  279. def setShowInfill(self, show: bool) -> None:
  280. self._show_infill = show
  281. self.currentLayerNumChanged.emit()
  282. def getShowInfill(self) -> bool:
  283. return self._show_infill
  284. def setShowStarts(self, show: bool) -> None:
  285. self._show_starts = show
  286. self.currentLayerNumChanged.emit()
  287. def getShowStarts(self) -> bool:
  288. return self._show_starts
  289. def getCompatibilityMode(self) -> bool:
  290. return self._compatibility_mode
  291. def getExtruderCount(self) -> int:
  292. return self._extruder_count
  293. def getMinFeedrate(self) -> float:
  294. if abs(self._min_feedrate - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  295. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  296. return self._min_feedrate
  297. def getMaxFeedrate(self) -> float:
  298. return self._max_feedrate
  299. def getMinThickness(self) -> float:
  300. if abs(self._min_thickness - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  301. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  302. return self._min_thickness
  303. def getMaxThickness(self) -> float:
  304. return self._max_thickness
  305. def getMaxLineWidth(self) -> float:
  306. return self._max_line_width
  307. def getMinLineWidth(self) -> float:
  308. if abs(self._min_line_width - sys.float_info.max) < 10: # Some lenience due to floating point rounding.
  309. return 0.0 # If it's still max-float, there are no measurements. Use 0 then.
  310. return self._min_line_width
  311. def calculateMaxLayers(self) -> None:
  312. scene = self.getController().getScene()
  313. self._old_max_layers = self._max_layers
  314. new_max_layers = -1
  315. """Recalculate num max layers"""
  316. for node in DepthFirstIterator(scene.getRoot()): # type: ignore
  317. layer_data = node.callDecoration("getLayerData")
  318. if not layer_data:
  319. continue
  320. self.setActivity(True)
  321. min_layer_number = sys.maxsize
  322. max_layer_number = -sys.maxsize
  323. for layer_id in layer_data.getLayers():
  324. # If a layer doesn't contain any polygons, skip it (for infill meshes taller than print objects
  325. if len(layer_data.getLayer(layer_id).polygons) < 1:
  326. continue
  327. # Store the max and min feedrates and thicknesses for display purposes
  328. for p in layer_data.getLayer(layer_id).polygons:
  329. self._max_feedrate = max(float(p.lineFeedrates.max()), self._max_feedrate)
  330. self._min_feedrate = min(float(p.lineFeedrates.min()), self._min_feedrate)
  331. self._max_line_width = max(float(p.lineWidths.max()), self._max_line_width)
  332. self._min_line_width = min(float(p.lineWidths.min()), self._min_line_width)
  333. self._max_thickness = max(float(p.lineThicknesses.max()), self._max_thickness)
  334. try:
  335. self._min_thickness = min(float(p.lineThicknesses[numpy.nonzero(p.lineThicknesses)].min()), self._min_thickness)
  336. except ValueError:
  337. # Sometimes, when importing a GCode the line thicknesses are zero and so the minimum (avoiding
  338. # the zero) can't be calculated
  339. Logger.log("i", "Min thickness can't be calculated because all the values are zero")
  340. if max_layer_number < layer_id:
  341. max_layer_number = layer_id
  342. if min_layer_number > layer_id:
  343. min_layer_number = layer_id
  344. layer_count = max_layer_number - min_layer_number
  345. if new_max_layers < layer_count:
  346. new_max_layers = layer_count
  347. if new_max_layers >= 0 and new_max_layers != self._old_max_layers:
  348. self._max_layers = new_max_layers
  349. # The qt slider has a bit of weird behavior that if the maxvalue needs to be changed first
  350. # if it's the largest value. If we don't do this, we can have a slider block outside of the
  351. # slider.
  352. if new_max_layers > self._current_layer_num:
  353. self.maxLayersChanged.emit()
  354. self.setLayer(int(self._max_layers))
  355. else:
  356. self.setLayer(int(self._max_layers))
  357. self.maxLayersChanged.emit()
  358. self._startUpdateTopLayers()
  359. def calculateMaxPathsOnLayer(self, layer_num: int) -> None:
  360. # Update the currentPath
  361. scene = self.getController().getScene()
  362. for node in DepthFirstIterator(scene.getRoot()): # type: ignore
  363. layer_data = node.callDecoration("getLayerData")
  364. if not layer_data:
  365. continue
  366. layer = layer_data.getLayer(layer_num)
  367. if layer is None:
  368. return
  369. new_max_paths = layer.lineMeshElementCount()
  370. if new_max_paths >= 0 and new_max_paths != self._max_paths:
  371. self._max_paths = new_max_paths
  372. self.maxPathsChanged.emit()
  373. self.setPath(int(new_max_paths))
  374. maxLayersChanged = Signal()
  375. maxPathsChanged = Signal()
  376. currentLayerNumChanged = Signal()
  377. currentPathNumChanged = Signal()
  378. globalStackChanged = Signal()
  379. preferencesChanged = Signal()
  380. busyChanged = Signal()
  381. activityChanged = Signal()
  382. def getProxy(self, engine, script_engine):
  383. """Hackish way to ensure the proxy is already created
  384. which ensures that the layerview.qml is already created as this caused some issues.
  385. """
  386. if self._proxy is None:
  387. self._proxy = SimulationViewProxy(self)
  388. return self._proxy
  389. def endRendering(self) -> None:
  390. pass
  391. def event(self, event) -> bool:
  392. modifiers = QApplication.keyboardModifiers()
  393. ctrl_is_active = modifiers & Qt.ControlModifier
  394. shift_is_active = modifiers & Qt.ShiftModifier
  395. if event.type == Event.KeyPressEvent and ctrl_is_active:
  396. amount = 10 if shift_is_active else 1
  397. if event.key == KeyEvent.UpKey:
  398. self.setLayer(self._current_layer_num + amount)
  399. return True
  400. if event.key == KeyEvent.DownKey:
  401. self.setLayer(self._current_layer_num - amount)
  402. return True
  403. if event.type == Event.ViewActivateEvent:
  404. # Start listening to changes.
  405. Application.getInstance().getPreferences().preferenceChanged.connect(self._onPreferencesChanged)
  406. self._controller.getScene().getRoot().childrenChanged.connect(self._onSceneChanged)
  407. self.calculateMaxLayers()
  408. self.calculateMaxPathsOnLayer(self._current_layer_num)
  409. # FIX: on Max OS X, somehow QOpenGLContext.currentContext() can become None during View switching.
  410. # This can happen when you do the following steps:
  411. # 1. Start Cura
  412. # 2. Load a model
  413. # 3. Switch to Custom mode
  414. # 4. Select the model and click on the per-object tool icon
  415. # 5. Switch view to Layer view or X-Ray
  416. # 6. Cura will very likely crash
  417. # It seems to be a timing issue that the currentContext can somehow be empty, but I have no clue why.
  418. # This fix tries to reschedule the view changing event call on the Qt thread again if the current OpenGL
  419. # context is None.
  420. if Platform.isOSX():
  421. if QOpenGLContext.currentContext() is None:
  422. Logger.log("d", "current context of OpenGL is empty on Mac OS X, will try to create shaders later")
  423. CuraApplication.getInstance().callLater(lambda e=event: self.event(e))
  424. return False
  425. # Make sure the SimulationPass is created
  426. layer_pass = self.getSimulationPass()
  427. renderer = self.getRenderer()
  428. if renderer is None:
  429. return False
  430. renderer.addRenderPass(layer_pass)
  431. # Make sure the NozzleNode is add to the root
  432. nozzle = self.getNozzleNode()
  433. nozzle.setParent(self.getController().getScene().getRoot())
  434. nozzle.setVisible(False)
  435. Application.getInstance().globalContainerStackChanged.connect(self._onGlobalStackChanged)
  436. self._onGlobalStackChanged()
  437. if not self._simulationview_composite_shader:
  438. plugin_path = cast(str, PluginRegistry.getInstance().getPluginPath("SimulationView"))
  439. self._simulationview_composite_shader = OpenGL.getInstance().createShaderProgram(os.path.join(plugin_path, "simulationview_composite.shader"))
  440. theme = CuraApplication.getInstance().getTheme()
  441. if theme is not None:
  442. self._simulationview_composite_shader.setUniformValue("u_background_color", Color(*theme.getColor("viewport_background").getRgb()))
  443. self._simulationview_composite_shader.setUniformValue("u_outline_color", Color(*theme.getColor("model_selection_outline").getRgb()))
  444. if not self._composite_pass:
  445. self._composite_pass = cast(CompositePass, renderer.getRenderPass("composite"))
  446. self._old_layer_bindings = self._composite_pass.getLayerBindings()[:] # make a copy so we can restore to it later
  447. self._composite_pass.getLayerBindings().append("simulationview")
  448. self._old_composite_shader = self._composite_pass.getCompositeShader()
  449. self._composite_pass.setCompositeShader(self._simulationview_composite_shader)
  450. self._updateSliceWarningVisibility()
  451. elif event.type == Event.ViewDeactivateEvent:
  452. self._controller.getScene().getRoot().childrenChanged.disconnect(self._onSceneChanged)
  453. Application.getInstance().getPreferences().preferenceChanged.disconnect(self._onPreferencesChanged)
  454. self._wireprint_warning_message.hide()
  455. self._slice_first_warning_message.hide()
  456. Application.getInstance().globalContainerStackChanged.disconnect(self._onGlobalStackChanged)
  457. if self._global_container_stack:
  458. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  459. if self._nozzle_node:
  460. self._nozzle_node.setParent(None)
  461. renderer = self.getRenderer()
  462. if renderer is None:
  463. return False
  464. if self._layer_pass is not None:
  465. renderer.removeRenderPass(self._layer_pass)
  466. if self._composite_pass:
  467. self._composite_pass.setLayerBindings(cast(List[str], self._old_layer_bindings))
  468. self._composite_pass.setCompositeShader(cast(ShaderProgram, self._old_composite_shader))
  469. return False
  470. def getCurrentLayerMesh(self):
  471. return self._current_layer_mesh
  472. def getCurrentLayerJumps(self):
  473. return self._current_layer_jumps
  474. def _onGlobalStackChanged(self) -> None:
  475. if self._global_container_stack:
  476. self._global_container_stack.propertyChanged.disconnect(self._onPropertyChanged)
  477. self._global_container_stack = Application.getInstance().getGlobalContainerStack()
  478. if self._global_container_stack:
  479. self._global_container_stack.propertyChanged.connect(self._onPropertyChanged)
  480. self._extruder_count = self._global_container_stack.getProperty("machine_extruder_count", "value")
  481. self._onPropertyChanged("wireframe_enabled", "value")
  482. self.globalStackChanged.emit()
  483. else:
  484. self._wireprint_warning_message.hide()
  485. def _onPropertyChanged(self, key: str, property_name: str) -> None:
  486. if key == "wireframe_enabled" and property_name == "value":
  487. if self._global_container_stack and self._global_container_stack.getProperty("wireframe_enabled", "value"):
  488. self._wireprint_warning_message.show()
  489. else:
  490. self._wireprint_warning_message.hide()
  491. def _onCurrentLayerNumChanged(self) -> None:
  492. self.calculateMaxPathsOnLayer(self._current_layer_num)
  493. scene = Application.getInstance().getController().getScene()
  494. scene.sceneChanged.emit(scene.getRoot())
  495. def _startUpdateTopLayers(self) -> None:
  496. if not self._compatibility_mode:
  497. return
  498. if self._top_layers_job:
  499. self._top_layers_job.finished.disconnect(self._updateCurrentLayerMesh)
  500. self._top_layers_job.cancel()
  501. self.setBusy(True)
  502. self._top_layers_job = _CreateTopLayersJob(self._controller.getScene(), self._current_layer_num, self._solid_layers)
  503. self._top_layers_job.finished.connect(self._updateCurrentLayerMesh) # type: ignore # mypy doesn't understand the whole private class thing that's going on here.
  504. self._top_layers_job.start() # type: ignore
  505. def _updateCurrentLayerMesh(self, job: "_CreateTopLayersJob") -> None:
  506. self.setBusy(False)
  507. if not job.getResult():
  508. return
  509. self.resetLayerData() # Reset the layer data only when job is done. Doing it now prevents "blinking" data.
  510. self._current_layer_mesh = job.getResult().get("layers")
  511. if self._show_travel_moves:
  512. self._current_layer_jumps = job.getResult().get("jumps")
  513. self._controller.getScene().sceneChanged.emit(self._controller.getScene().getRoot())
  514. self._top_layers_job = None
  515. def _updateWithPreferences(self) -> None:
  516. self._solid_layers = int(Application.getInstance().getPreferences().getValue("view/top_layer_count"))
  517. self._only_show_top_layers = bool(Application.getInstance().getPreferences().getValue("view/only_show_top_layers"))
  518. self._compatibility_mode = self._evaluateCompatibilityMode()
  519. self.setSimulationViewType(int(float(Application.getInstance().getPreferences().getValue("layerview/layer_view_type"))))
  520. for extruder_nr, extruder_opacity in enumerate(Application.getInstance().getPreferences().getValue("layerview/extruder_opacities").split("|")):
  521. try:
  522. opacity = float(extruder_opacity)
  523. except ValueError:
  524. opacity = 1.0
  525. self.setExtruderOpacity(extruder_nr, opacity)
  526. self.setShowTravelMoves(bool(Application.getInstance().getPreferences().getValue("layerview/show_travel_moves")))
  527. self.setShowHelpers(bool(Application.getInstance().getPreferences().getValue("layerview/show_helpers")))
  528. self.setShowSkin(bool(Application.getInstance().getPreferences().getValue("layerview/show_skin")))
  529. self.setShowInfill(bool(Application.getInstance().getPreferences().getValue("layerview/show_infill")))
  530. self.setShowStarts(bool(Application.getInstance().getPreferences().getValue("layerview/show_starts")))
  531. self._startUpdateTopLayers()
  532. self.preferencesChanged.emit()
  533. def _onPreferencesChanged(self, preference: str) -> None:
  534. if preference not in {
  535. "view/top_layer_count",
  536. "view/only_show_top_layers",
  537. "view/force_layer_view_compatibility_mode",
  538. "layerview/layer_view_type",
  539. "layerview/extruder_opacities",
  540. "layerview/show_travel_moves",
  541. "layerview/show_helpers",
  542. "layerview/show_skin",
  543. "layerview/show_infill",
  544. "layerview/show_starts",
  545. }:
  546. return
  547. self._updateWithPreferences()
  548. def _updateSliceWarningVisibility(self):
  549. if not self.getActivity()\
  550. and not CuraApplication.getInstance().getPreferences().getValue("general/auto_slice")\
  551. and CuraApplication.getInstance().getPreferences().getValue(self._no_layers_warning_preference):
  552. self._slice_first_warning_message.show()
  553. else:
  554. self._slice_first_warning_message.hide()
  555. def _onDontAskMeAgain(self, checked: bool) -> None:
  556. CuraApplication.getInstance().getPreferences().setValue(self._no_layers_warning_preference, not checked)
  557. class _CreateTopLayersJob(Job):
  558. def __init__(self, scene: "Scene", layer_number: int, solid_layers: int) -> None:
  559. super().__init__()
  560. self._scene = scene
  561. self._layer_number = layer_number
  562. self._solid_layers = solid_layers
  563. self._cancel = False
  564. def run(self) -> None:
  565. layer_data = None
  566. for node in DepthFirstIterator(self._scene.getRoot()): # type: ignore
  567. layer_data = node.callDecoration("getLayerData")
  568. if layer_data:
  569. break
  570. if self._cancel or not layer_data:
  571. return
  572. layer_mesh = MeshBuilder()
  573. for i in range(self._solid_layers):
  574. layer_number = self._layer_number - i
  575. if layer_number < 0:
  576. continue
  577. try:
  578. layer = layer_data.getLayer(layer_number).createMesh()
  579. except Exception:
  580. Logger.logException("w", "An exception occurred while creating layer mesh.")
  581. return
  582. if not layer or layer.getVertices() is None:
  583. continue
  584. layer_mesh.addIndices(layer_mesh.getVertexCount() + layer.getIndices())
  585. layer_mesh.addVertices(layer.getVertices())
  586. # Scale layer color by a brightness factor based on the current layer number
  587. # This will result in a range of 0.5 - 1.0 to multiply colors by.
  588. brightness = numpy.ones((1, 4), dtype=numpy.float32) * (2.0 - (i / self._solid_layers)) / 2.0
  589. brightness[0, 3] = 1.0
  590. layer_mesh.addColors(layer.getColors() * brightness)
  591. if self._cancel:
  592. return
  593. Job.yieldThread()
  594. if self._cancel:
  595. return
  596. Job.yieldThread()
  597. jump_mesh = layer_data.getLayer(self._layer_number).createJumps()
  598. if not jump_mesh or jump_mesh.getVertices() is None:
  599. jump_mesh = None
  600. self.setResult({"layers": layer_mesh.build(), "jumps": jump_mesh})
  601. def cancel(self) -> None:
  602. self._cancel = True
  603. super().cancel()