SimulationView.py 31 KB

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