SimulationView.py 38 KB

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