bbox.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # Created: 27.01.2019
  2. # Copyright (c) 2019, Manfred Moitzi
  3. # License: MIT License
  4. from typing import TYPE_CHECKING, Iterable, Tuple
  5. from .vector import Vector, Vec2
  6. if TYPE_CHECKING:
  7. from ezdxf.eztypes import Vertex
  8. class BoundingBox:
  9. def __init__(self, vertices: Iterable['Vertex']):
  10. self.extmin, self.extmax = extends(vertices)
  11. def inside(self, vertex: 'Vertex') -> bool:
  12. x, y, z = Vector(vertex).xyz
  13. xmin, ymin, zmin = self.extmin.xyz
  14. xmax, ymax, zmax = self.extmax.xyz
  15. return (xmin <= x <= xmax) and (ymin <= y <= ymax) and (zmin <= z <= zmax)
  16. def extend(self, vertices: Iterable['Vertex']) -> None:
  17. v = [self.extmin, self.extmax]
  18. v.extend(vertices)
  19. self.extmin, self.extmax = extends(v)
  20. def extends(vertices: Iterable['Vertex']) -> Tuple[Vector, Vector]:
  21. minx, miny, minz = None, None, None
  22. maxx, maxy, maxz = None, None, None
  23. for v in vertices:
  24. v = Vector(v)
  25. if minx is None:
  26. minx, miny, minz = v.xyz
  27. maxx, maxy, maxz = v.xyz
  28. else:
  29. x, y, z = v.xyz
  30. if x < minx:
  31. minx = x
  32. elif x > maxx:
  33. maxx = x
  34. if y < miny:
  35. miny = y
  36. elif y > maxy:
  37. maxy = y
  38. if z < minz:
  39. minz = z
  40. elif z > maxz:
  41. maxz = z
  42. return Vector(minx, miny, minz), Vector(maxx, maxy, maxz)
  43. class BoundingBox2d:
  44. def __init__(self, vertices: Iterable['Vertex']):
  45. self.extmin, self.extmax = extends2d(vertices)
  46. def inside(self, vertex: 'Vertex') -> bool:
  47. v = Vec2(vertex)
  48. min_ = self.extmin
  49. max_ = self.extmax
  50. return (min_.x <= v.x <= max_.x) and (min_.y <= v.y <= max_.y)
  51. def extend(self, vertices: Iterable['Vertex']) -> None:
  52. v = [self.extmin, self.extmax]
  53. v.extend(vertices)
  54. self.extmin, self.extmax = extends(v)
  55. def extends2d(vertices: Iterable['Vertex']) -> Tuple[Vec2, Vec2]:
  56. minx, miny = None, None
  57. maxx, maxy = None, None
  58. for v in vertices:
  59. v = Vec2(v)
  60. x, y = v.x, v.y
  61. if minx is None:
  62. minx = x
  63. maxx = x
  64. miny = y
  65. maxy = y
  66. else:
  67. if x < minx:
  68. minx = x
  69. elif x > maxx:
  70. maxx = x
  71. if y < miny:
  72. miny = y
  73. elif y > maxy:
  74. maxy = y
  75. return Vec2((minx, miny)), Vec2((maxx, maxy))