ProcessSlicedLayersJob.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. # Copyright (c) 2016 Ultimaker B.V.
  2. # Cura is released under the terms of the AGPLv3 or higher.
  3. import gc
  4. from UM.Job import Job
  5. from UM.Scene.Iterator.DepthFirstIterator import DepthFirstIterator
  6. from UM.Scene.SceneNode import SceneNode
  7. from UM.Application import Application
  8. from UM.Mesh.MeshData import MeshData
  9. from UM.Preferences import Preferences
  10. from UM.View.GL.OpenGLContext import OpenGLContext
  11. from UM.Message import Message
  12. from UM.i18n import i18nCatalog
  13. from UM.Logger import Logger
  14. from UM.Math.Vector import Vector
  15. from cura.Settings.ExtruderManager import ExtruderManager
  16. from cura import LayerDataBuilder
  17. from cura import LayerDataDecorator
  18. from cura import LayerPolygon
  19. import numpy
  20. from time import time
  21. catalog = i18nCatalog("cura")
  22. ## Return a 4-tuple with floats 0-1 representing the html color code
  23. #
  24. # \param color_code html color code, i.e. "#FF0000" -> red
  25. def colorCodeToRGBA(color_code):
  26. if color_code is None:
  27. Logger.log("w", "Unable to convert color code, returning default")
  28. return [0, 0, 0, 1]
  29. return [
  30. int(color_code[1:3], 16) / 255,
  31. int(color_code[3:5], 16) / 255,
  32. int(color_code[5:7], 16) / 255,
  33. 1.0]
  34. class ProcessSlicedLayersJob(Job):
  35. def __init__(self, layers):
  36. super().__init__()
  37. self._layers = layers
  38. self._scene = Application.getInstance().getController().getScene()
  39. self._progress = None
  40. self._abort_requested = False
  41. ## Aborts the processing of layers.
  42. #
  43. # This abort is made on a best-effort basis, meaning that the actual
  44. # job thread will check once in a while to see whether an abort is
  45. # requested and then stop processing by itself. There is no guarantee
  46. # that the abort will stop the job any time soon or even at all.
  47. def abort(self):
  48. self._abort_requested = True
  49. def run(self):
  50. start_time = time()
  51. if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
  52. self._progress = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, -1)
  53. self._progress.show()
  54. Job.yieldThread()
  55. if self._abort_requested:
  56. if self._progress:
  57. self._progress.hide()
  58. return
  59. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  60. new_node = SceneNode()
  61. ## Remove old layer data (if any)
  62. for node in DepthFirstIterator(self._scene.getRoot()):
  63. if node.callDecoration("getLayerData"):
  64. node.getParent().removeChild(node)
  65. break
  66. if self._abort_requested:
  67. if self._progress:
  68. self._progress.hide()
  69. return
  70. # Force garbage collection.
  71. # For some reason, Python has a tendency to keep the layer data
  72. # in memory longer than needed. Forcing the GC to run here makes
  73. # sure any old layer data is really cleaned up before adding new.
  74. gc.collect()
  75. mesh = MeshData()
  76. layer_data = LayerDataBuilder.LayerDataBuilder()
  77. layer_count = len(self._layers)
  78. # Find the minimum layer number
  79. # When using a raft, the raft layers are sent as layers < 0. Instead of allowing layers < 0, we
  80. # instead simply offset all other layers so the lowest layer is always 0.
  81. min_layer_number = 0
  82. for layer in self._layers:
  83. if layer.id < min_layer_number:
  84. min_layer_number = layer.id
  85. current_layer = 0
  86. for layer in self._layers:
  87. abs_layer_number = layer.id + abs(min_layer_number)
  88. layer_data.addLayer(abs_layer_number)
  89. this_layer = layer_data.getLayer(abs_layer_number)
  90. layer_data.setLayerHeight(abs_layer_number, layer.height)
  91. for p in range(layer.repeatedMessageCount("path_segment")):
  92. polygon = layer.getRepeatedMessage("path_segment", p)
  93. extruder = polygon.extruder
  94. line_types = numpy.fromstring(polygon.line_type, dtype="u1") # Convert bytearray to numpy array
  95. line_types = line_types.reshape((-1,1))
  96. points = numpy.fromstring(polygon.points, dtype="f4") # Convert bytearray to numpy array
  97. if polygon.point_type == 0: # Point2D
  98. points = points.reshape((-1,2)) # We get a linear list of pairs that make up the points, so make numpy interpret them correctly.
  99. else: # Point3D
  100. points = points.reshape((-1,3))
  101. line_widths = numpy.fromstring(polygon.line_width, dtype="f4") # Convert bytearray to numpy array
  102. line_widths = line_widths.reshape((-1,1)) # We get a linear list of pairs that make up the points, so make numpy interpret them correctly.
  103. # In the future, line_thicknesses should be given by CuraEngine as well.
  104. # Currently the infill layer thickness also translates to line width
  105. line_thicknesses = numpy.zeros(line_widths.shape, dtype="f4")
  106. line_thicknesses[:] = layer.thickness / 1000 # from micrometer to millimeter
  107. # Create a new 3D-array, copy the 2D points over and insert the right height.
  108. # This uses manual array creation + copy rather than numpy.insert since this is
  109. # faster.
  110. new_points = numpy.empty((len(points), 3), numpy.float32)
  111. if polygon.point_type == 0: # Point2D
  112. new_points[:, 0] = points[:, 0]
  113. new_points[:, 1] = layer.height / 1000 # layer height value is in backend representation
  114. new_points[:, 2] = -points[:, 1]
  115. else: # Point3D
  116. new_points[:, 0] = points[:, 0]
  117. new_points[:, 1] = points[:, 2]
  118. new_points[:, 2] = -points[:, 1]
  119. this_poly = LayerPolygon.LayerPolygon(extruder, line_types, new_points, line_widths, line_thicknesses)
  120. this_poly.buildCache()
  121. this_layer.polygons.append(this_poly)
  122. Job.yieldThread()
  123. Job.yieldThread()
  124. current_layer += 1
  125. progress = (current_layer / layer_count) * 99
  126. # TODO: Rebuild the layer data mesh once the layer has been processed.
  127. # This needs some work in LayerData so we can add the new layers instead of recreating the entire mesh.
  128. if self._abort_requested:
  129. if self._progress:
  130. self._progress.hide()
  131. return
  132. if self._progress:
  133. self._progress.setProgress(progress)
  134. # We are done processing all the layers we got from the engine, now create a mesh out of the data
  135. # Find out colors per extruder
  136. global_container_stack = Application.getInstance().getGlobalContainerStack()
  137. manager = ExtruderManager.getInstance()
  138. extruders = list(manager.getMachineExtruders(global_container_stack.getId()))
  139. if extruders:
  140. material_color_map = numpy.zeros((len(extruders), 4), dtype=numpy.float32)
  141. for extruder in extruders:
  142. material = extruder.findContainer({"type": "material"})
  143. position = int(extruder.getMetaDataEntry("position", default="0")) # Get the position
  144. color_code = material.getMetaDataEntry("color_code", default="#e0e000")
  145. color = colorCodeToRGBA(color_code)
  146. material_color_map[position, :] = color
  147. else:
  148. # Single extruder via global stack.
  149. material_color_map = numpy.zeros((1, 4), dtype=numpy.float32)
  150. material = global_container_stack.findContainer({"type": "material"})
  151. color_code = "#e0e000"
  152. if material:
  153. if material.getMetaDataEntry("color_code") is not None:
  154. color_code = material.getMetaDataEntry("color_code")
  155. color = colorCodeToRGBA(color_code)
  156. material_color_map[0, :] = color
  157. # We have to scale the colors for compatibility mode
  158. if OpenGLContext.isLegacyOpenGL() or bool(Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode")):
  159. line_type_brightness = 0.5 # for compatibility mode
  160. else:
  161. line_type_brightness = 1.0
  162. layer_mesh = layer_data.build(material_color_map, line_type_brightness)
  163. if self._abort_requested:
  164. if self._progress:
  165. self._progress.hide()
  166. return
  167. # Add LayerDataDecorator to scene node to indicate that the node has layer data
  168. decorator = LayerDataDecorator.LayerDataDecorator()
  169. decorator.setLayerData(layer_mesh)
  170. new_node.addDecorator(decorator)
  171. new_node.setMeshData(mesh)
  172. # Set build volume as parent, the build volume can move as a result of raft settings.
  173. # It makes sense to set the build volume as parent: the print is actually printed on it.
  174. new_node_parent = Application.getInstance().getBuildVolume()
  175. new_node.setParent(new_node_parent) # Note: After this we can no longer abort!
  176. settings = Application.getInstance().getGlobalContainerStack()
  177. if not settings.getProperty("machine_center_is_zero", "value"):
  178. new_node.setPosition(Vector(-settings.getProperty("machine_width", "value") / 2, 0.0, settings.getProperty("machine_depth", "value") / 2))
  179. if self._progress:
  180. self._progress.setProgress(100)
  181. view = Application.getInstance().getController().getActiveView()
  182. if view.getPluginId() == "LayerView":
  183. view.resetLayerData()
  184. if self._progress:
  185. self._progress.hide()
  186. # Clear the unparsed layers. This saves us a bunch of memory if the Job does not get destroyed.
  187. self._layers = None
  188. Logger.log("d", "Processing layers took %s seconds", time() - start_time)
  189. def _onActiveViewChanged(self):
  190. if self.isRunning():
  191. if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
  192. if not self._progress:
  193. self._progress = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, 0)
  194. if self._progress.getProgress() != 100:
  195. self._progress.show()
  196. else:
  197. if self._progress:
  198. self._progress.hide()