SimulationView.py 41 KB

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