SimulationView.py 29 KB

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