ProcessSlicedLayersJob.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #Copyright (c) 2017 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. from cura.Settings.ExtrudersModel import ExtrudersModel
  22. catalog = i18nCatalog("cura")
  23. ## Return a 4-tuple with floats 0-1 representing the html color code
  24. #
  25. # \param color_code html color code, i.e. "#FF0000" -> red
  26. def colorCodeToRGBA(color_code):
  27. if color_code is None:
  28. Logger.log("w", "Unable to convert color code, returning default")
  29. return [0, 0, 0, 1]
  30. return [
  31. int(color_code[1:3], 16) / 255,
  32. int(color_code[3:5], 16) / 255,
  33. int(color_code[5:7], 16) / 255,
  34. 1.0]
  35. class ProcessSlicedLayersJob(Job):
  36. def __init__(self, layers):
  37. super().__init__()
  38. self._layers = layers
  39. self._scene = Application.getInstance().getController().getScene()
  40. self._progress = None
  41. self._abort_requested = False
  42. ## Aborts the processing of layers.
  43. #
  44. # This abort is made on a best-effort basis, meaning that the actual
  45. # job thread will check once in a while to see whether an abort is
  46. # requested and then stop processing by itself. There is no guarantee
  47. # that the abort will stop the job any time soon or even at all.
  48. def abort(self):
  49. self._abort_requested = True
  50. def run(self):
  51. start_time = time()
  52. if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
  53. self._progress = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, -1)
  54. self._progress.show()
  55. Job.yieldThread()
  56. if self._abort_requested:
  57. if self._progress:
  58. self._progress.hide()
  59. return
  60. Application.getInstance().getController().activeViewChanged.connect(self._onActiveViewChanged)
  61. new_node = SceneNode()
  62. ## Remove old layer data (if any)
  63. for node in DepthFirstIterator(self._scene.getRoot()):
  64. if node.callDecoration("getLayerData"):
  65. node.getParent().removeChild(node)
  66. break
  67. if self._abort_requested:
  68. if self._progress:
  69. self._progress.hide()
  70. return
  71. # Force garbage collection.
  72. # For some reason, Python has a tendency to keep the layer data
  73. # in memory longer than needed. Forcing the GC to run here makes
  74. # sure any old layer data is really cleaned up before adding new.
  75. gc.collect()
  76. mesh = MeshData()
  77. layer_data = LayerDataBuilder.LayerDataBuilder()
  78. layer_count = len(self._layers)
  79. # Find the minimum layer number
  80. # When using a raft, the raft layers are sent as layers < 0. Instead of allowing layers < 0, we
  81. # instead simply offset all other layers so the lowest layer is always 0.
  82. min_layer_number = 0
  83. for layer in self._layers:
  84. if layer.id < min_layer_number:
  85. min_layer_number = layer.id
  86. current_layer = 0
  87. for layer in self._layers:
  88. abs_layer_number = layer.id + abs(min_layer_number)
  89. layer_data.addLayer(abs_layer_number)
  90. this_layer = layer_data.getLayer(abs_layer_number)
  91. layer_data.setLayerHeight(abs_layer_number, layer.height)
  92. for p in range(layer.repeatedMessageCount("path_segment")):
  93. polygon = layer.getRepeatedMessage("path_segment", p)
  94. extruder = polygon.extruder
  95. line_types = numpy.fromstring(polygon.line_type, dtype="u1") # Convert bytearray to numpy array
  96. line_types = line_types.reshape((-1,1))
  97. points = numpy.fromstring(polygon.points, dtype="f4") # Convert bytearray to numpy array
  98. if polygon.point_type == 0: # Point2D
  99. points = points.reshape((-1,2)) # We get a linear list of pairs that make up the points, so make numpy interpret them correctly.
  100. else: # Point3D
  101. points = points.reshape((-1,3))
  102. line_widths = numpy.fromstring(polygon.line_width, dtype="f4") # Convert bytearray to numpy array
  103. 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.
  104. # In the future, line_thicknesses should be given by CuraEngine as well.
  105. # Currently the infill layer thickness also translates to line width
  106. line_thicknesses = numpy.zeros(line_widths.shape, dtype="f4")
  107. line_thicknesses[:] = layer.thickness / 1000 # from micrometer to millimeter
  108. # Create a new 3D-array, copy the 2D points over and insert the right height.
  109. # This uses manual array creation + copy rather than numpy.insert since this is
  110. # faster.
  111. new_points = numpy.empty((len(points), 3), numpy.float32)
  112. if polygon.point_type == 0: # Point2D
  113. new_points[:, 0] = points[:, 0]
  114. new_points[:, 1] = layer.height / 1000 # layer height value is in backend representation
  115. new_points[:, 2] = -points[:, 1]
  116. else: # Point3D
  117. new_points[:, 0] = points[:, 0]
  118. new_points[:, 1] = points[:, 2]
  119. new_points[:, 2] = -points[:, 1]
  120. this_poly = LayerPolygon.LayerPolygon(extruder, line_types, new_points, line_widths, line_thicknesses)
  121. this_poly.buildCache()
  122. this_layer.polygons.append(this_poly)
  123. Job.yieldThread()
  124. Job.yieldThread()
  125. current_layer += 1
  126. progress = (current_layer / layer_count) * 99
  127. # TODO: Rebuild the layer data mesh once the layer has been processed.
  128. # This needs some work in LayerData so we can add the new layers instead of recreating the entire mesh.
  129. if self._abort_requested:
  130. if self._progress:
  131. self._progress.hide()
  132. return
  133. if self._progress:
  134. self._progress.setProgress(progress)
  135. # We are done processing all the layers we got from the engine, now create a mesh out of the data
  136. # Find out colors per extruder
  137. global_container_stack = Application.getInstance().getGlobalContainerStack()
  138. manager = ExtruderManager.getInstance()
  139. extruders = list(manager.getMachineExtruders(global_container_stack.getId()))
  140. if extruders:
  141. material_color_map = numpy.zeros((len(extruders), 4), dtype=numpy.float32)
  142. for extruder in extruders:
  143. position = int(extruder.getMetaDataEntry("position", default="0")) # Get the position
  144. try:
  145. default_color = ExtrudersModel.defaultColors[position]
  146. except IndexError:
  147. default_color = "#e0e000"
  148. color_code = extruder.material.getMetaDataEntry("color_code", default=default_color)
  149. color = colorCodeToRGBA(color_code)
  150. material_color_map[position, :] = color
  151. else:
  152. # Single extruder via global stack.
  153. material_color_map = numpy.zeros((1, 4), dtype=numpy.float32)
  154. color_code = global_container_stack.material.getMetaDataEntry("color_code", default="#e0e000")
  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, catalog.i18nc("@info:title", "Information"))
  194. if self._progress.getProgress() != 100:
  195. self._progress.show()
  196. else:
  197. if self._progress:
  198. self._progress.hide()