polyfacebuilder.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Created: 04.04.2011
  2. # Copyright (c) 2011-2018, Manfred Moitzi
  3. # License: MIT License
  4. from typing import TYPE_CHECKING, Iterable, List
  5. from ezdxf.lldxf.const import VERTEXNAMES
  6. if TYPE_CHECKING:
  7. from ezdxf.eztypes import DXFVertex
  8. from .facemixins import FaceProxy
  9. class PolyfaceBuilder:
  10. def __init__(self, faces: Iterable['FaceProxy'], precision: int = 6):
  11. self.precision = precision
  12. self.faces = []
  13. self.vertices = []
  14. self.index_mapping = {}
  15. self.build(faces)
  16. @property
  17. def nvertices(self) -> int:
  18. return len(self.vertices)
  19. @property
  20. def nfaces(self) -> int:
  21. return len(self.faces)
  22. def get_vertices(self) -> List['DXFVertex']:
  23. vertices = self.vertices[:]
  24. vertices.extend(self.faces)
  25. return vertices
  26. def build(self, faces: Iterable['FaceProxy']) -> None:
  27. for face in faces:
  28. face_record = face.face_record
  29. for vertex, name in zip(face, VERTEXNAMES):
  30. index = self.add(vertex)
  31. # preserve sign of old index value
  32. sign = -1 if face_record.get_dxf_attrib(name, 0) < 0 else +1
  33. face_record.set_dxf_attrib(name, (index + 1) * sign)
  34. self.faces.append(face_record)
  35. def add(self, vertex: 'DXFVertex') -> int:
  36. def key(point):
  37. return tuple((round(coord, self.precision) for coord in point))
  38. location = key(vertex.dxf.location)
  39. try:
  40. return self.index_mapping[location]
  41. except KeyError: # internal exception
  42. index = len(self.vertices)
  43. self.index_mapping[location] = index
  44. self.vertices.append(vertex)
  45. return index