SimulationView.py 28 KB

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