ProcessSlicedLayersJob.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #Copyright (c) 2017 Ultimaker B.V.
  2. #Cura is released under the terms of the LGPLv3 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_message = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, -1)
  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.show()
  54. Job.yieldThread()
  55. if self._abort_requested:
  56. if self._progress_message:
  57. self._progress_message.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_message:
  68. self._progress_message.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_message:
  130. self._progress_message.hide()
  131. return
  132. if self._progress_message:
  133. self._progress_message.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. position = int(extruder.getMetaDataEntry("position", default="0")) # Get the position
  143. try:
  144. default_color = ExtrudersModel.defaultColors[position]
  145. except IndexError:
  146. default_color = "#e0e000"
  147. color_code = extruder.material.getMetaDataEntry("color_code", default=default_color)
  148. color = colorCodeToRGBA(color_code)
  149. material_color_map[position, :] = color
  150. else:
  151. # Single extruder via global stack.
  152. material_color_map = numpy.zeros((1, 4), dtype=numpy.float32)
  153. color_code = global_container_stack.material.getMetaDataEntry("color_code", default="#e0e000")
  154. color = colorCodeToRGBA(color_code)
  155. material_color_map[0, :] = color
  156. # We have to scale the colors for compatibility mode
  157. if OpenGLContext.isLegacyOpenGL() or bool(Preferences.getInstance().getValue("view/force_layer_view_compatibility_mode")):
  158. line_type_brightness = 0.5 # for compatibility mode
  159. else:
  160. line_type_brightness = 1.0
  161. layer_mesh = layer_data.build(material_color_map, line_type_brightness)
  162. if self._abort_requested:
  163. if self._progress_message:
  164. self._progress_message.hide()
  165. return
  166. # Add LayerDataDecorator to scene node to indicate that the node has layer data
  167. decorator = LayerDataDecorator.LayerDataDecorator()
  168. decorator.setLayerData(layer_mesh)
  169. new_node.addDecorator(decorator)
  170. new_node.setMeshData(mesh)
  171. # Set build volume as parent, the build volume can move as a result of raft settings.
  172. # It makes sense to set the build volume as parent: the print is actually printed on it.
  173. new_node_parent = Application.getInstance().getBuildVolume()
  174. new_node.setParent(new_node_parent) # Note: After this we can no longer abort!
  175. settings = Application.getInstance().getGlobalContainerStack()
  176. if not settings.getProperty("machine_center_is_zero", "value"):
  177. new_node.setPosition(Vector(-settings.getProperty("machine_width", "value") / 2, 0.0, settings.getProperty("machine_depth", "value") / 2))
  178. if self._progress_message:
  179. self._progress_message.setProgress(100)
  180. view = Application.getInstance().getController().getActiveView()
  181. if view.getPluginId() == "LayerView":
  182. view.resetLayerData()
  183. if self._progress_message:
  184. self._progress_message.hide()
  185. # Clear the unparsed layers. This saves us a bunch of memory if the Job does not get destroyed.
  186. self._layers = None
  187. Logger.log("d", "Processing layers took %s seconds", time() - start_time)
  188. def _onActiveViewChanged(self):
  189. if self.isRunning():
  190. if Application.getInstance().getController().getActiveView().getPluginId() == "LayerView":
  191. if not self._progress_message:
  192. self._progress_message = Message(catalog.i18nc("@info:status", "Processing Layers"), 0, False, 0, catalog.i18nc("@info:title", "Information"))
  193. if self._progress_message.getProgress() != 100:
  194. self._progress_message.show()
  195. else:
  196. if self._progress_message:
  197. self._progress_message.hide()