SimulationView.py 31 KB

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