LayerPolygon.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. # Copyright (c) 2019 Ultimaker B.V.
  2. # Cura is released under the terms of the LGPLv3 or higher.
  3. import math
  4. import numpy
  5. from typing import Optional, cast
  6. from UM.Qt.Bindings.Theme import Theme
  7. from UM.Qt.QtApplication import QtApplication
  8. from UM.Logger import Logger
  9. class LayerPolygon:
  10. NoneType = 0
  11. Inset0Type = 1
  12. InsetXType = 2
  13. SkinType = 3
  14. SupportType = 4
  15. SkirtType = 5
  16. InfillType = 6
  17. SupportInfillType = 7
  18. MoveCombingType = 8
  19. MoveRetractionType = 9
  20. SupportInterfaceType = 10
  21. PrimeTowerType = 11
  22. __number_of_types = 12
  23. __jump_map = numpy.logical_or(numpy.logical_or(numpy.arange(__number_of_types) == NoneType,
  24. numpy.arange(__number_of_types) == MoveCombingType),
  25. numpy.arange(__number_of_types) == MoveRetractionType)
  26. def __init__(self, extruder: int, line_types: numpy.ndarray, data: numpy.ndarray,
  27. line_widths: numpy.ndarray, line_thicknesses: numpy.ndarray, line_feedrates: numpy.ndarray) -> None:
  28. """LayerPolygon, used in ProcessSlicedLayersJob
  29. :param extruder: The position of the extruder
  30. :param line_types: array with line_types
  31. :param data: new_points
  32. :param line_widths: array with line widths
  33. :param line_thicknesses: array with type as index and thickness as value
  34. :param line_feedrates: array with line feedrates
  35. """
  36. self._extruder = extruder
  37. self._types = line_types
  38. unknown_types = numpy.where(self._types >= self.__number_of_types, self._types, None)
  39. if unknown_types.any():
  40. # Got faulty line data from the engine.
  41. for idx in unknown_types:
  42. Logger.warning(f"Found an unknown line type at: {idx}")
  43. self._types[idx] = self.NoneType
  44. self._data = data
  45. self._line_widths = line_widths
  46. self._line_thicknesses = line_thicknesses
  47. self._line_feedrates = line_feedrates
  48. self._vertex_begin = 0
  49. self._vertex_end = 0
  50. self._index_begin = 0
  51. self._index_end = 0
  52. self._jump_mask = self.__jump_map[self._types]
  53. self._jump_count = numpy.sum(self._jump_mask)
  54. self._mesh_line_count = len(self._types) - self._jump_count
  55. self._vertex_count = self._mesh_line_count + numpy.sum(self._types[1:] == self._types[:-1])
  56. # Buffering the colors shouldn't be necessary as it is not
  57. # re-used and can save a lot of memory usage.
  58. self._color_map = LayerPolygon.getColorMap()
  59. self._colors: numpy.ndarray = self._color_map[self._types]
  60. # When type is used as index returns true if type == LayerPolygon.InfillType
  61. # or type == LayerPolygon.SkinType
  62. # or type == LayerPolygon.SupportInfillType
  63. # Should be generated in better way, not hardcoded.
  64. self._is_infill_or_skin_type_map = numpy.array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0], dtype=bool)
  65. self._build_cache_line_mesh_mask: Optional[numpy.ndarray] = None
  66. self._build_cache_needed_points: Optional[numpy.ndarray] = None
  67. def buildCache(self) -> None:
  68. # For the line mesh we do not draw Infill or Jumps. Therefore those lines are filtered out.
  69. self._build_cache_line_mesh_mask = numpy.ones(self._jump_mask.shape, dtype = bool)
  70. self._index_begin = 0
  71. self._index_end = cast(int, numpy.sum(self._build_cache_line_mesh_mask))
  72. self._build_cache_needed_points = numpy.ones((len(self._types), 2), dtype = bool)
  73. # Only if the type of line segment changes do we need to add an extra vertex to change colors
  74. self._build_cache_needed_points[1:, 0][:, numpy.newaxis] = self._types[1:] != self._types[:-1]
  75. # Mark points as unneeded if they are of types we don't want in the line mesh according to the calculated mask
  76. numpy.logical_and(self._build_cache_needed_points, self._build_cache_line_mesh_mask, self._build_cache_needed_points)
  77. self._vertex_begin = 0
  78. self._vertex_end = cast(int, numpy.sum(self._build_cache_needed_points))
  79. def build(self, vertex_offset: int, index_offset: int, vertices: numpy.ndarray,
  80. colors: numpy.ndarray, line_dimensions: numpy.ndarray, feedrates: numpy.ndarray,
  81. extruders: numpy.ndarray, line_types: numpy.ndarray, indices: numpy.ndarray) -> None:
  82. """Set all the arrays provided by the function caller, representing the LayerPolygon
  83. The arrays are either by vertex or by indices.
  84. :param vertex_offset: determines where to start and end filling the arrays
  85. :param index_offset: determines where to start and end filling the arrays
  86. :param vertices: vertex numpy array to be filled
  87. :param colors: vertex numpy array to be filled
  88. :param line_dimensions: vertex numpy array to be filled
  89. :param feedrates: vertex numpy array to be filled
  90. :param extruders: vertex numpy array to be filled
  91. :param line_types: vertex numpy array to be filled
  92. :param indices: index numpy array to be filled
  93. """
  94. if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
  95. self.buildCache()
  96. if self._build_cache_line_mesh_mask is None or self._build_cache_needed_points is None:
  97. Logger.log("w", "Failed to build cache for layer polygon")
  98. return
  99. line_mesh_mask = self._build_cache_line_mesh_mask
  100. needed_points_list = self._build_cache_needed_points
  101. # Index to the points we need to represent the line mesh.
  102. # This is constructed by generating simple start and end points for each line.
  103. # For line segment n, these are points n and n+1. Row n reads [n n+1]
  104. # Then the indices for the points we don't need are thrown away based on the pre-calculated list.
  105. index_list = (numpy.arange(len(self._types)).reshape((-1, 1)) + numpy.array([[0, 1]])).reshape((-1, 1))[needed_points_list.reshape((-1, 1))]
  106. # The relative values of begin and end indices have already been set in buildCache, so we only need to offset them to the parents offset.
  107. self._vertex_begin += vertex_offset
  108. self._vertex_end += vertex_offset
  109. # Points are picked based on the index list to get the vertices needed.
  110. vertices[self._vertex_begin:self._vertex_end, :] = self._data[index_list, :]
  111. # Create an array with colors for each vertex and remove the color data for the points that has been thrown away.
  112. colors[self._vertex_begin:self._vertex_end, :] = numpy.tile(self._colors, (1, 2)).reshape((-1, 4))[needed_points_list.ravel()]
  113. # Create an array with line widths and thicknesses for each vertex.
  114. line_dimensions[self._vertex_begin:self._vertex_end, 0] = numpy.tile(self._line_widths, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  115. line_dimensions[self._vertex_begin:self._vertex_end, 1] = numpy.tile(self._line_thicknesses, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  116. # Create an array with feedrates for each line
  117. feedrates[self._vertex_begin:self._vertex_end] = numpy.tile(self._line_feedrates, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  118. extruders[self._vertex_begin:self._vertex_end] = self._extruder
  119. # Convert type per vertex to type per line
  120. line_types[self._vertex_begin:self._vertex_end] = numpy.tile(self._types, (1, 2)).reshape((-1, 1))[needed_points_list.ravel()][:, 0]
  121. # The relative values of begin and end indices have already been set in buildCache,
  122. # so we only need to offset them to the parents offset.
  123. self._index_begin += index_offset
  124. self._index_end += index_offset
  125. indices[self._index_begin:self._index_end, :] = numpy.arange(self._index_end-self._index_begin, dtype=numpy.int32).reshape((-1, 1))
  126. # When the line type changes the index needs to be increased by 2.
  127. indices[self._index_begin:self._index_end, :] += numpy.cumsum(needed_points_list[line_mesh_mask.ravel(), 0], dtype = numpy.int32).reshape((-1, 1))
  128. # Each line segment goes from it's starting point p to p+1, offset by the vertex index.
  129. # The -1 is to compensate for the necessarily True value of needed_points_list[0,0] which causes an unwanted +1 in cumsum above.
  130. indices[self._index_begin:self._index_end, :] += numpy.array([self._vertex_begin - 1, self._vertex_begin])
  131. self._build_cache_line_mesh_mask = None
  132. self._build_cache_needed_points = None
  133. def getColors(self):
  134. return self._colors
  135. def mapLineTypeToColor(self, line_types: numpy.ndarray) -> numpy.ndarray:
  136. return self._color_map[line_types]
  137. def isInfillOrSkinType(self, line_types: numpy.ndarray) -> numpy.ndarray:
  138. return self._is_infill_or_skin_type_map[line_types]
  139. def lineMeshVertexCount(self) -> int:
  140. return self._vertex_end - self._vertex_begin
  141. def lineMeshElementCount(self) -> int:
  142. return self._index_end - self._index_begin
  143. @property
  144. def extruder(self):
  145. return self._extruder
  146. @property
  147. def types(self):
  148. return self._types
  149. @property
  150. def lineLengths(self):
  151. data_array = numpy.array(self._data)
  152. return numpy.linalg.norm(data_array[1:] - data_array[:-1], axis=1)
  153. @property
  154. def data(self):
  155. return self._data
  156. @property
  157. def elementCount(self):
  158. return (self._index_end - self._index_begin) * 2 # The range of vertices multiplied by 2 since each vertex is used twice
  159. @property
  160. def lineWidths(self):
  161. return self._line_widths
  162. @property
  163. def lineThicknesses(self):
  164. return self._line_thicknesses
  165. @property
  166. def lineFeedrates(self):
  167. return self._line_feedrates
  168. @property
  169. def jumpMask(self):
  170. return self._jump_mask
  171. @property
  172. def meshLineCount(self):
  173. return self._mesh_line_count
  174. @property
  175. def jumpCount(self):
  176. return self._jump_count
  177. def getNormals(self) -> numpy.ndarray:
  178. """Calculate normals for the entire polygon using numpy.
  179. :return: normals for the entire polygon
  180. """
  181. normals = numpy.copy(self._data)
  182. normals[:, 1] = 0.0 # We are only interested in 2D normals
  183. # Calculate the edges between points.
  184. # The call to numpy.roll shifts the entire array by one
  185. # so that we end up subtracting each next point from the current, wrapping around.
  186. # This gives us the edges from the next point to the current point.
  187. normals = numpy.diff(normals, 1, 0)
  188. # Calculate the length of each edge using standard Pythagoras
  189. lengths = numpy.sqrt(normals[:, 0] ** 2 + normals[:, 2] ** 2)
  190. # The normal of a 2D vector is equal to its x and y coordinates swapped
  191. # and then x inverted. This code does that.
  192. normals[:, [0, 2]] = normals[:, [2, 0]]
  193. normals[:, 0] *= -1
  194. # Normalize the normals.
  195. normals[:, 0] /= lengths
  196. normals[:, 2] /= lengths
  197. return normals
  198. __color_map = None # type: numpy.ndarray
  199. @classmethod
  200. def getColorMap(cls) -> numpy.ndarray:
  201. """Gets the instance of the VersionUpgradeManager, or creates one."""
  202. if cls.__color_map is None:
  203. theme = cast(Theme, QtApplication.getInstance().getTheme())
  204. cls.__color_map = numpy.array([
  205. theme.getColor("layerview_none").getRgbF(), # NoneType
  206. theme.getColor("layerview_inset_0").getRgbF(), # Inset0Type
  207. theme.getColor("layerview_inset_x").getRgbF(), # InsetXType
  208. theme.getColor("layerview_skin").getRgbF(), # SkinType
  209. theme.getColor("layerview_support").getRgbF(), # SupportType
  210. theme.getColor("layerview_skirt").getRgbF(), # SkirtType
  211. theme.getColor("layerview_infill").getRgbF(), # InfillType
  212. theme.getColor("layerview_support_infill").getRgbF(), # SupportInfillType
  213. theme.getColor("layerview_move_combing").getRgbF(), # MoveCombingType
  214. theme.getColor("layerview_move_retraction").getRgbF(), # MoveRetractionType
  215. theme.getColor("layerview_support_interface").getRgbF(), # SupportInterfaceType
  216. theme.getColor("layerview_prime_tower").getRgbF() # PrimeTowerType
  217. ])
  218. return cls.__color_map