Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/__init__.py +39 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier3p.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier3p.pyx +222 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier4p.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier4p.pyx +371 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bspline.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bspline.pyx +402 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/constants.h +8 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/construct.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/construct.pyx +359 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/linetypes.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/linetypes.pyx +91 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/mapbox_earcut.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/mapbox_earcut.pyx +835 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.pxd +15 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.pyx +676 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/np_support.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/np_support.pyx +177 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.c +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.pxd +49 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.pyx +838 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/api.py +31 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/cache.py +59 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/const.py +183 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/dbg.py +193 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/dxf.py +82 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/hdr.py +110 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/mesh.py +415 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/sab.py +527 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/sat.py +431 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__init__.py +2 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/__init__.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_face.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_manager.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_measurements.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_synonyms.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/fonts.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/glyphs.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/lff.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/shapefile.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/ttfonts.cpython-311.pyc +0 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_face.py +78 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_manager.py +530 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_measurements.py +54 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_synonyms.py +10 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/fonts.py +745 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/glyphs.py +39 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/lff.py +324 -0
- data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/shapefile.py +1064 -0
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2020-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
import sys
|
| 4 |
+
from ezdxf._options import options
|
| 5 |
+
|
| 6 |
+
# Set environment variable EZDXF_DISABLE_C_EXT to '1' or 'True' to disable
|
| 7 |
+
# the usage of C extensions implemented by Cython.
|
| 8 |
+
#
|
| 9 |
+
# Important: If you change the EZDXF_DISABLE_C_EXT state, you have to restart
|
| 10 |
+
# the Python interpreter, because C extension integration is done at the
|
| 11 |
+
# ezdxf import!
|
| 12 |
+
#
|
| 13 |
+
# Config files:
|
| 14 |
+
# Section: core
|
| 15 |
+
# Key: disable_c_ext = 1
|
| 16 |
+
#
|
| 17 |
+
# Direct imports from the C extension modules can not be disabled,
|
| 18 |
+
# just the usage by the ezdxf core package.
|
| 19 |
+
# For an example see ezdxf.math.__init__, if you import Vec3 from ezdxf.math
|
| 20 |
+
# the implementation depends on DISABLE_C_EXT and the existence of the C
|
| 21 |
+
# extension, but if you import Vec3 from ezdxf.math.vectors, you always get
|
| 22 |
+
# the Python implementation.
|
| 23 |
+
|
| 24 |
+
USE_C_EXT = not options.disable_c_ext
|
| 25 |
+
|
| 26 |
+
# C-extensions are always disabled for pypy because JIT compiled Python code is
|
| 27 |
+
# much faster!
|
| 28 |
+
PYPY = hasattr(sys, 'pypy_version_info')
|
| 29 |
+
if PYPY:
|
| 30 |
+
USE_C_EXT = False
|
| 31 |
+
|
| 32 |
+
if USE_C_EXT:
|
| 33 |
+
try:
|
| 34 |
+
from ezdxf.acc import vector
|
| 35 |
+
except ImportError:
|
| 36 |
+
USE_C_EXT = False
|
| 37 |
+
|
| 38 |
+
# set actual state of C-extension usage
|
| 39 |
+
options._use_c_ext = USE_C_EXT
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier3p.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier3p.pyx
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2021-2024 Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import TYPE_CHECKING, Sequence
|
| 5 |
+
from .vector cimport Vec3, isclose, v3_dist, v3_lerp, v3_add, Vec2
|
| 6 |
+
from .matrix44 cimport Matrix44
|
| 7 |
+
import warnings
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from ezdxf.math import UVec
|
| 10 |
+
|
| 11 |
+
__all__ = ['Bezier3P']
|
| 12 |
+
|
| 13 |
+
cdef extern from "constants.h":
|
| 14 |
+
const double ABS_TOL
|
| 15 |
+
const double REL_TOL
|
| 16 |
+
|
| 17 |
+
cdef double RECURSION_LIMIT = 1000
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
cdef class Bezier3P:
|
| 21 |
+
cdef:
|
| 22 |
+
FastQuadCurve curve # pyright: ignore
|
| 23 |
+
readonly Vec3 start_point
|
| 24 |
+
Vec3 cp1
|
| 25 |
+
readonly Vec3 end_point
|
| 26 |
+
|
| 27 |
+
def __cinit__(self, defpoints: Sequence[UVec]):
|
| 28 |
+
if not isinstance(defpoints[0], (Vec2, Vec3)):
|
| 29 |
+
warnings.warn(
|
| 30 |
+
DeprecationWarning,
|
| 31 |
+
"Bezier3P requires defpoints of type Vec2 or Vec3 in the future",
|
| 32 |
+
)
|
| 33 |
+
if len(defpoints) == 3:
|
| 34 |
+
self.start_point = Vec3(defpoints[0])
|
| 35 |
+
self.cp1 = Vec3(defpoints[1])
|
| 36 |
+
self.end_point = Vec3(defpoints[2])
|
| 37 |
+
|
| 38 |
+
self.curve = FastQuadCurve(
|
| 39 |
+
self.start_point,
|
| 40 |
+
self.cp1,
|
| 41 |
+
self.end_point
|
| 42 |
+
)
|
| 43 |
+
else:
|
| 44 |
+
raise ValueError("Three control points required.")
|
| 45 |
+
|
| 46 |
+
@property
|
| 47 |
+
def control_points(self) -> tuple[Vec3, Vec3, Vec3]:
|
| 48 |
+
return self.start_point, self.cp1, self.end_point
|
| 49 |
+
|
| 50 |
+
def __reduce__(self):
|
| 51 |
+
return Bezier3P, (self.control_points,)
|
| 52 |
+
|
| 53 |
+
def point(self, double t) -> Vec3:
|
| 54 |
+
if 0.0 <= t <= 1.0:
|
| 55 |
+
return self.curve.point(t)
|
| 56 |
+
else:
|
| 57 |
+
raise ValueError("t not in range [0 to 1]")
|
| 58 |
+
|
| 59 |
+
def tangent(self, double t) -> Vec3:
|
| 60 |
+
if 0.0 <= t <= 1.0:
|
| 61 |
+
return self.curve.tangent(t)
|
| 62 |
+
else:
|
| 63 |
+
raise ValueError("t not in range [0 to 1]")
|
| 64 |
+
|
| 65 |
+
def approximate(self, int segments) -> list[Vec3]:
|
| 66 |
+
cdef double delta_t
|
| 67 |
+
cdef int segment
|
| 68 |
+
cdef list points = [self.start_point]
|
| 69 |
+
|
| 70 |
+
if segments < 1:
|
| 71 |
+
raise ValueError(segments)
|
| 72 |
+
delta_t = 1.0 / segments
|
| 73 |
+
for segment in range(1, segments):
|
| 74 |
+
points.append(self.point(delta_t * segment))
|
| 75 |
+
points.append(self.end_point)
|
| 76 |
+
return points
|
| 77 |
+
|
| 78 |
+
def flattening(self, double distance, int segments = 4) -> list[Vec3]:
|
| 79 |
+
cdef double dt = 1.0 / segments
|
| 80 |
+
cdef double t0 = 0.0, t1
|
| 81 |
+
cdef _Flattening f = _Flattening(self, distance)
|
| 82 |
+
cdef Vec3 start_point = self.start_point
|
| 83 |
+
cdef Vec3 end_point
|
| 84 |
+
while t0 < 1.0:
|
| 85 |
+
t1 = t0 + dt
|
| 86 |
+
if isclose(t1, 1.0, REL_TOL, ABS_TOL):
|
| 87 |
+
end_point = self.end_point
|
| 88 |
+
t1 = 1.0
|
| 89 |
+
else:
|
| 90 |
+
end_point = self.curve.point(t1)
|
| 91 |
+
f.reset_recursion_check()
|
| 92 |
+
f.flatten(start_point, end_point, t0, t1)
|
| 93 |
+
if f.has_recursion_error():
|
| 94 |
+
raise RecursionError(
|
| 95 |
+
"Bezier3P flattening error, check for very large coordinates"
|
| 96 |
+
)
|
| 97 |
+
t0 = t1
|
| 98 |
+
start_point = end_point
|
| 99 |
+
return f.points
|
| 100 |
+
|
| 101 |
+
def approximated_length(self, segments: int = 128) -> float:
|
| 102 |
+
cdef double length = 0.0
|
| 103 |
+
cdef bint start_flag = 0
|
| 104 |
+
cdef Vec3 prev_point, point
|
| 105 |
+
|
| 106 |
+
for point in self.approximate(segments):
|
| 107 |
+
if start_flag:
|
| 108 |
+
length += v3_dist(prev_point, point)
|
| 109 |
+
else:
|
| 110 |
+
start_flag = 1
|
| 111 |
+
prev_point = point
|
| 112 |
+
return length
|
| 113 |
+
|
| 114 |
+
def reverse(self) -> Bezier3P:
|
| 115 |
+
return Bezier3P((self.end_point, self.cp1, self.start_point))
|
| 116 |
+
|
| 117 |
+
def transform(self, Matrix44 m) -> Bezier3P:
|
| 118 |
+
return Bezier3P(tuple(m.transform_vertices(self.control_points)))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
cdef class _Flattening:
|
| 122 |
+
cdef FastQuadCurve curve # pyright: ignore
|
| 123 |
+
cdef double distance
|
| 124 |
+
cdef list points
|
| 125 |
+
cdef int _recursion_level
|
| 126 |
+
cdef int _recursion_error
|
| 127 |
+
|
| 128 |
+
def __cinit__(self, Bezier3P curve, double distance):
|
| 129 |
+
self.curve = curve.curve
|
| 130 |
+
self.distance = distance
|
| 131 |
+
self.points = [curve.start_point]
|
| 132 |
+
self._recursion_level = 0
|
| 133 |
+
self._recursion_error = 0
|
| 134 |
+
|
| 135 |
+
cdef has_recursion_error(self):
|
| 136 |
+
return self._recursion_error
|
| 137 |
+
|
| 138 |
+
cdef reset_recursion_check(self):
|
| 139 |
+
self._recursion_level = 0
|
| 140 |
+
self._recursion_error = 0
|
| 141 |
+
|
| 142 |
+
cdef flatten(
|
| 143 |
+
self,
|
| 144 |
+
Vec3 start_point,
|
| 145 |
+
Vec3 end_point,
|
| 146 |
+
double start_t,
|
| 147 |
+
double end_t
|
| 148 |
+
):
|
| 149 |
+
if self._recursion_level > RECURSION_LIMIT:
|
| 150 |
+
self._recursion_error = 1
|
| 151 |
+
return
|
| 152 |
+
self._recursion_level += 1
|
| 153 |
+
cdef double mid_t = (start_t + end_t) * 0.5
|
| 154 |
+
cdef Vec3 mid_point = self.curve.point(mid_t)
|
| 155 |
+
cdef double d = v3_dist(mid_point, v3_lerp(start_point, end_point, 0.5))
|
| 156 |
+
if d < self.distance:
|
| 157 |
+
self.points.append(end_point)
|
| 158 |
+
else:
|
| 159 |
+
self.flatten(start_point, mid_point, start_t, mid_t)
|
| 160 |
+
self.flatten(mid_point, end_point, mid_t, end_t)
|
| 161 |
+
self._recursion_level -= 1
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
cdef class FastQuadCurve:
|
| 165 |
+
cdef:
|
| 166 |
+
double[3] offset
|
| 167 |
+
double[3] p1
|
| 168 |
+
double[3] p2
|
| 169 |
+
|
| 170 |
+
def __cinit__(self, Vec3 p0, Vec3 p1, Vec3 p2):
|
| 171 |
+
self.offset[0] = p0.x
|
| 172 |
+
self.offset[1] = p0.y
|
| 173 |
+
self.offset[2] = p0.z
|
| 174 |
+
|
| 175 |
+
# 1st control point (p0) is always (0, 0, 0)
|
| 176 |
+
self.p1[0] = p1.x - p0.x
|
| 177 |
+
self.p1[1] = p1.y - p0.y
|
| 178 |
+
self.p1[2] = p1.z - p0.z
|
| 179 |
+
|
| 180 |
+
self.p2[0] = p2.x - p0.x
|
| 181 |
+
self.p2[1] = p2.y - p0.y
|
| 182 |
+
self.p2[2] = p2.z - p0.z
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
cdef Vec3 point(self, double t):
|
| 186 |
+
# 1st control point (p0) is always (0, 0, 0)
|
| 187 |
+
# => p0 * a is always (0, 0, 0)
|
| 188 |
+
cdef:
|
| 189 |
+
Vec3 result = Vec3()
|
| 190 |
+
# double a = (1 - t) ** 2
|
| 191 |
+
double b = 2.0 * t * (1.0 - t)
|
| 192 |
+
double c = t * t
|
| 193 |
+
|
| 194 |
+
iadd_mul(result, self.p1, b)
|
| 195 |
+
iadd_mul(result, self.p2, c)
|
| 196 |
+
|
| 197 |
+
# add offset at last - it is maybe very large
|
| 198 |
+
result.x += self.offset[0]
|
| 199 |
+
result.y += self.offset[1]
|
| 200 |
+
result.z += self.offset[2]
|
| 201 |
+
|
| 202 |
+
return result
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
cdef Vec3 tangent(self, double t):
|
| 206 |
+
# tangent vector is independent from offset location!
|
| 207 |
+
cdef:
|
| 208 |
+
Vec3 result = Vec3()
|
| 209 |
+
# double a = -2 * (1 - t)
|
| 210 |
+
double b = 2.0 - 4.0 * t
|
| 211 |
+
double c = 2.0 * t
|
| 212 |
+
|
| 213 |
+
iadd_mul(result, self.p1, b)
|
| 214 |
+
iadd_mul(result, self.p2, c)
|
| 215 |
+
|
| 216 |
+
return result
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
cdef void iadd_mul(Vec3 a, double[3] b, double c):
|
| 220 |
+
a.x += b[0] * c
|
| 221 |
+
a.y += b[1] * c
|
| 222 |
+
a.z += b[2] * c
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bezier4p.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiag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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2020-2024 Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import TYPE_CHECKING, Sequence, Iterable, Iterator
|
| 5 |
+
import cython
|
| 6 |
+
import warnings
|
| 7 |
+
from .vector cimport (
|
| 8 |
+
Vec3,
|
| 9 |
+
Vec2,
|
| 10 |
+
isclose,
|
| 11 |
+
v3_add,
|
| 12 |
+
v3_mul,
|
| 13 |
+
v3_dist,
|
| 14 |
+
v3_lerp,
|
| 15 |
+
v3_from_angle,
|
| 16 |
+
normalize_rad_angle,
|
| 17 |
+
)
|
| 18 |
+
from .matrix44 cimport Matrix44
|
| 19 |
+
from libc.math cimport ceil, tan, M_PI
|
| 20 |
+
from .construct import arc_angle_span_deg
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ezdxf.math import UVec
|
| 24 |
+
from ezdxf.math.ellipse import ConstructionEllipse
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
'Bezier4P', 'cubic_bezier_arc_parameters',
|
| 28 |
+
'cubic_bezier_from_arc', 'cubic_bezier_from_ellipse',
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
cdef extern from "constants.h":
|
| 32 |
+
const double ABS_TOL
|
| 33 |
+
const double REL_TOL
|
| 34 |
+
const double M_TAU
|
| 35 |
+
|
| 36 |
+
cdef double DEG2RAD = M_PI / 180.0
|
| 37 |
+
cdef double RECURSION_LIMIT = 1000
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
cdef class Bezier4P:
|
| 41 |
+
cdef:
|
| 42 |
+
FastCubicCurve curve # pyright: ignore
|
| 43 |
+
readonly Vec3 start_point
|
| 44 |
+
Vec3 cp1
|
| 45 |
+
Vec3 cp2
|
| 46 |
+
readonly Vec3 end_point
|
| 47 |
+
|
| 48 |
+
def __cinit__(self, defpoints: Sequence[UVec]):
|
| 49 |
+
if not isinstance(defpoints[0], (Vec2, Vec3)):
|
| 50 |
+
warnings.warn(
|
| 51 |
+
DeprecationWarning,
|
| 52 |
+
"Bezier4P requires defpoints of type Vec2 or Vec3 in the future",
|
| 53 |
+
)
|
| 54 |
+
if len(defpoints) == 4:
|
| 55 |
+
self.start_point = Vec3(defpoints[0])
|
| 56 |
+
self.cp1 = Vec3(defpoints[1])
|
| 57 |
+
self.cp2 = Vec3(defpoints[2])
|
| 58 |
+
self.end_point = Vec3(defpoints[3])
|
| 59 |
+
|
| 60 |
+
self.curve = FastCubicCurve(
|
| 61 |
+
self.start_point,
|
| 62 |
+
self.cp1,
|
| 63 |
+
self.cp2,
|
| 64 |
+
self.end_point
|
| 65 |
+
)
|
| 66 |
+
else:
|
| 67 |
+
raise ValueError("Four control points required.")
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def control_points(self) -> tuple[Vec3, Vec3, Vec3, Vec3]:
|
| 71 |
+
return self.start_point, self.cp1, self.cp2, self.end_point
|
| 72 |
+
|
| 73 |
+
def __reduce__(self):
|
| 74 |
+
return Bezier4P, (self.control_points,)
|
| 75 |
+
|
| 76 |
+
def point(self, double t) -> Vec3:
|
| 77 |
+
if 0.0 <= t <= 1.0:
|
| 78 |
+
return self.curve.point(t)
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError("t not in range [0 to 1]")
|
| 81 |
+
|
| 82 |
+
def tangent(self, double t) -> Vec3:
|
| 83 |
+
if 0.0 <= t <= 1.0:
|
| 84 |
+
return self.curve.tangent(t)
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError("t not in range [0 to 1]")
|
| 87 |
+
|
| 88 |
+
def approximate(self, int segments) -> list[Vec3]:
|
| 89 |
+
cdef double delta_t
|
| 90 |
+
cdef int segment
|
| 91 |
+
cdef list points = [self.start_point]
|
| 92 |
+
|
| 93 |
+
if segments < 1:
|
| 94 |
+
raise ValueError(segments)
|
| 95 |
+
delta_t = 1.0 / segments
|
| 96 |
+
for segment in range(1, segments):
|
| 97 |
+
points.append(self.curve.point(delta_t * segment))
|
| 98 |
+
points.append(self.end_point)
|
| 99 |
+
return points
|
| 100 |
+
|
| 101 |
+
def flattening(self, double distance, int segments = 4) -> list[Vec3]:
|
| 102 |
+
cdef double dt = 1.0 / segments
|
| 103 |
+
cdef double t0 = 0.0, t1
|
| 104 |
+
cdef _Flattening f = _Flattening(self, distance)
|
| 105 |
+
cdef Vec3 start_point = self.start_point
|
| 106 |
+
cdef Vec3 end_point
|
| 107 |
+
while t0 < 1.0:
|
| 108 |
+
t1 = t0 + dt
|
| 109 |
+
if isclose(t1, 1.0, REL_TOL, ABS_TOL):
|
| 110 |
+
end_point = self.end_point
|
| 111 |
+
t1 = 1.0
|
| 112 |
+
else:
|
| 113 |
+
end_point = self.curve.point(t1)
|
| 114 |
+
f.reset_recursion_check()
|
| 115 |
+
f.flatten(start_point, end_point, t0, t1)
|
| 116 |
+
if f.has_recursion_error():
|
| 117 |
+
raise RecursionError(
|
| 118 |
+
"Bezier4P flattening error, check for very large coordinates"
|
| 119 |
+
)
|
| 120 |
+
t0 = t1
|
| 121 |
+
start_point = end_point
|
| 122 |
+
|
| 123 |
+
return f.points
|
| 124 |
+
|
| 125 |
+
def approximated_length(self, segments: int = 128) -> float:
|
| 126 |
+
cdef double length = 0.0
|
| 127 |
+
cdef bint start_flag = 0
|
| 128 |
+
cdef Vec3 prev_point, point
|
| 129 |
+
|
| 130 |
+
for point in self.approximate(segments):
|
| 131 |
+
if start_flag:
|
| 132 |
+
length += v3_dist(prev_point, point)
|
| 133 |
+
else:
|
| 134 |
+
start_flag = 1
|
| 135 |
+
prev_point = point
|
| 136 |
+
return length
|
| 137 |
+
|
| 138 |
+
def reverse(self) -> Bezier4P:
|
| 139 |
+
return Bezier4P((self.end_point, self.cp2, self.cp1, self.start_point))
|
| 140 |
+
|
| 141 |
+
def transform(self, Matrix44 m) -> Bezier4P:
|
| 142 |
+
return Bezier4P(tuple(m.transform_vertices(self.control_points)))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
cdef class _Flattening:
|
| 146 |
+
cdef FastCubicCurve curve # pyright: ignore
|
| 147 |
+
cdef double distance
|
| 148 |
+
cdef list points
|
| 149 |
+
cdef int _recursion_level
|
| 150 |
+
cdef int _recursion_error
|
| 151 |
+
|
| 152 |
+
def __cinit__(self, Bezier4P curve, double distance):
|
| 153 |
+
self.curve = curve.curve
|
| 154 |
+
self.distance = distance
|
| 155 |
+
self.points = [curve.start_point]
|
| 156 |
+
self._recursion_level = 0
|
| 157 |
+
self._recursion_error = 0
|
| 158 |
+
|
| 159 |
+
cdef has_recursion_error(self):
|
| 160 |
+
return self._recursion_error
|
| 161 |
+
|
| 162 |
+
cdef reset_recursion_check(self):
|
| 163 |
+
self._recursion_level = 0
|
| 164 |
+
self._recursion_error = 0
|
| 165 |
+
|
| 166 |
+
cdef flatten(
|
| 167 |
+
self,
|
| 168 |
+
Vec3 start_point,
|
| 169 |
+
Vec3 end_point,
|
| 170 |
+
double start_t,
|
| 171 |
+
double end_t
|
| 172 |
+
):
|
| 173 |
+
# Keep in sync with CPython implementation: ezdxf/math/_bezier4p.py
|
| 174 |
+
# Test suite: 630a
|
| 175 |
+
if self._recursion_level > RECURSION_LIMIT:
|
| 176 |
+
self._recursion_error = 1
|
| 177 |
+
return
|
| 178 |
+
self._recursion_level += 1
|
| 179 |
+
cdef double mid_t = (start_t + end_t) * 0.5
|
| 180 |
+
cdef Vec3 mid_point = self.curve.point(mid_t)
|
| 181 |
+
cdef double d = v3_dist(mid_point, v3_lerp(start_point, end_point, 0.5))
|
| 182 |
+
if d < self.distance:
|
| 183 |
+
self.points.append(end_point)
|
| 184 |
+
else:
|
| 185 |
+
self.flatten(start_point, mid_point, start_t, mid_t)
|
| 186 |
+
self.flatten(mid_point, end_point, mid_t, end_t)
|
| 187 |
+
self._recursion_level -= 1
|
| 188 |
+
|
| 189 |
+
cdef double DEFAULT_TANGENT_FACTOR = 4.0 / 3.0 # 1.333333333333333333
|
| 190 |
+
cdef double OPTIMIZED_TANGENT_FACTOR = 1.3324407374108935
|
| 191 |
+
cdef double TANGENT_FACTOR = DEFAULT_TANGENT_FACTOR
|
| 192 |
+
|
| 193 |
+
@cython.cdivision(True)
|
| 194 |
+
def cubic_bezier_arc_parameters(
|
| 195 |
+
double start_angle,
|
| 196 |
+
double end_angle,
|
| 197 |
+
int segments = 1,
|
| 198 |
+
) -> Iterator[tuple[Vec3, Vec3, Vec3, Vec3]]:
|
| 199 |
+
if segments < 1:
|
| 200 |
+
raise ValueError('Invalid argument segments (>= 1).')
|
| 201 |
+
cdef double delta_angle = end_angle - start_angle
|
| 202 |
+
cdef int arc_count
|
| 203 |
+
if delta_angle > 0:
|
| 204 |
+
arc_count = <int> ceil(delta_angle / M_PI * 2.0)
|
| 205 |
+
if segments > arc_count:
|
| 206 |
+
arc_count = segments
|
| 207 |
+
else:
|
| 208 |
+
raise ValueError('Delta angle from start- to end angle has to be > 0.')
|
| 209 |
+
|
| 210 |
+
cdef double segment_angle = delta_angle / arc_count
|
| 211 |
+
cdef double tangent_length = TANGENT_FACTOR * tan(segment_angle / 4.0)
|
| 212 |
+
cdef double angle = start_angle
|
| 213 |
+
cdef Vec3 start_point, end_point, cp1, cp2
|
| 214 |
+
end_point = v3_from_angle(angle, 1.0)
|
| 215 |
+
|
| 216 |
+
for _ in range(arc_count):
|
| 217 |
+
start_point = end_point
|
| 218 |
+
angle += segment_angle
|
| 219 |
+
end_point = v3_from_angle(angle, 1.0)
|
| 220 |
+
cp1 = Vec3()
|
| 221 |
+
cp1.x = start_point.x - start_point.y * tangent_length
|
| 222 |
+
cp1.y = start_point.y + start_point.x * tangent_length
|
| 223 |
+
cp2 = Vec3()
|
| 224 |
+
cp2.x = end_point.x + end_point.y * tangent_length
|
| 225 |
+
cp2.y = end_point.y - end_point.x * tangent_length
|
| 226 |
+
yield start_point, cp1, cp2, end_point
|
| 227 |
+
|
| 228 |
+
def cubic_bezier_from_arc(
|
| 229 |
+
center = (0, 0),
|
| 230 |
+
double radius = 1.0,
|
| 231 |
+
double start_angle = 0.0,
|
| 232 |
+
double end_angle = 360.0,
|
| 233 |
+
int segments = 1
|
| 234 |
+
) -> Iterable[Bezier4P]:
|
| 235 |
+
cdef Vec3 center_ = Vec3(center)
|
| 236 |
+
cdef Vec3 tmp
|
| 237 |
+
cdef list res
|
| 238 |
+
cdef int i
|
| 239 |
+
cdef double angle_span = arc_angle_span_deg(start_angle, end_angle)
|
| 240 |
+
if abs(angle_span) < 1e-9:
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
cdef double s = start_angle
|
| 244 |
+
start_angle = (s * DEG2RAD) % M_TAU
|
| 245 |
+
end_angle = (s + angle_span) * DEG2RAD
|
| 246 |
+
while start_angle > end_angle:
|
| 247 |
+
end_angle += M_TAU
|
| 248 |
+
|
| 249 |
+
for control_points in cubic_bezier_arc_parameters(start_angle, end_angle, segments):
|
| 250 |
+
res = []
|
| 251 |
+
for i in range(4):
|
| 252 |
+
tmp = <Vec3> control_points[i]
|
| 253 |
+
res.append(v3_add(center_, v3_mul(tmp, radius)))
|
| 254 |
+
yield Bezier4P(res)
|
| 255 |
+
|
| 256 |
+
def cubic_bezier_from_ellipse(
|
| 257 |
+
ellipse: ConstructionEllipse,
|
| 258 |
+
int segments = 1
|
| 259 |
+
) -> Iterator[Bezier4P]:
|
| 260 |
+
cdef double param_span = ellipse.param_span
|
| 261 |
+
if abs(param_span) < 1e-9:
|
| 262 |
+
return
|
| 263 |
+
|
| 264 |
+
cdef double start_angle = normalize_rad_angle(ellipse.start_param)
|
| 265 |
+
cdef double end_angle = start_angle + param_span
|
| 266 |
+
|
| 267 |
+
while start_angle > end_angle:
|
| 268 |
+
end_angle += M_TAU
|
| 269 |
+
|
| 270 |
+
cdef Vec3 center = Vec3(ellipse.center)
|
| 271 |
+
cdef Vec3 x_axis = Vec3(ellipse.major_axis)
|
| 272 |
+
cdef Vec3 y_axis = Vec3(ellipse.minor_axis)
|
| 273 |
+
cdef Vec3 cp
|
| 274 |
+
cdef Vec3 c_res
|
| 275 |
+
cdef list res
|
| 276 |
+
for control_points in cubic_bezier_arc_parameters(start_angle, end_angle, segments):
|
| 277 |
+
res = list()
|
| 278 |
+
for i in range(4):
|
| 279 |
+
cp = <Vec3> control_points[i]
|
| 280 |
+
c_res = v3_add_3(center, v3_mul(x_axis, cp.x), v3_mul(y_axis, cp.y))
|
| 281 |
+
res.append(c_res)
|
| 282 |
+
yield Bezier4P(res)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
cdef Vec3 v3_add_3(Vec3 a, Vec3 b, Vec3 c):
|
| 286 |
+
cdef Vec3 result = Vec3()
|
| 287 |
+
|
| 288 |
+
result.x = a.x + b.x + c.x
|
| 289 |
+
result.y = a.y + b.y + c.y
|
| 290 |
+
result.z = a.z + b.z + c.z
|
| 291 |
+
|
| 292 |
+
return result
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
cdef class FastCubicCurve:
|
| 296 |
+
cdef:
|
| 297 |
+
double[3] offset
|
| 298 |
+
double[3] p1
|
| 299 |
+
double[3] p2
|
| 300 |
+
double[3] p3
|
| 301 |
+
|
| 302 |
+
def __cinit__(self, Vec3 p0, Vec3 p1, Vec3 p2, Vec3 p3):
|
| 303 |
+
cdef:
|
| 304 |
+
double x = p0.x
|
| 305 |
+
double y = p0.y
|
| 306 |
+
double z = p0.z
|
| 307 |
+
|
| 308 |
+
self.offset[0] = x
|
| 309 |
+
self.offset[1] = y
|
| 310 |
+
self.offset[2] = z
|
| 311 |
+
|
| 312 |
+
# 1st control point (p0) is always (0, 0, 0)
|
| 313 |
+
self.p1[0] = p1.x - x
|
| 314 |
+
self.p1[1] = p1.y - y
|
| 315 |
+
self.p1[2] = p1.z - z
|
| 316 |
+
|
| 317 |
+
self.p2[0] = p2.x - x
|
| 318 |
+
self.p2[1] = p2.y - y
|
| 319 |
+
self.p2[2] = p2.z - z
|
| 320 |
+
|
| 321 |
+
self.p3[0] = p3.x - x
|
| 322 |
+
self.p3[1] = p3.y - y
|
| 323 |
+
self.p3[2] = p3.z - z
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
cdef Vec3 point(self, double t):
|
| 327 |
+
# 1st control point (p0) is always (0, 0, 0)
|
| 328 |
+
# => p0 * a is always (0, 0, 0)
|
| 329 |
+
cdef:
|
| 330 |
+
Vec3 result = Vec3()
|
| 331 |
+
double t2 = t * t
|
| 332 |
+
double _1_minus_t = 1.0 - t
|
| 333 |
+
# a = (1 - t) ** 3
|
| 334 |
+
double b = 3.0 * _1_minus_t * _1_minus_t * t
|
| 335 |
+
double c = 3.0 * _1_minus_t * t2
|
| 336 |
+
double d = t2 * t
|
| 337 |
+
|
| 338 |
+
iadd_mul(result, self.p1, b)
|
| 339 |
+
iadd_mul(result, self.p2, c)
|
| 340 |
+
iadd_mul(result, self.p3, d)
|
| 341 |
+
|
| 342 |
+
# add offset at last - it is maybe very large
|
| 343 |
+
result.x += self.offset[0]
|
| 344 |
+
result.y += self.offset[1]
|
| 345 |
+
result.z += self.offset[2]
|
| 346 |
+
|
| 347 |
+
return result
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
cdef Vec3 tangent(self, double t):
|
| 351 |
+
# tangent vector is independent from offset location!
|
| 352 |
+
cdef:
|
| 353 |
+
Vec3 result = Vec3()
|
| 354 |
+
double t2 = t * t
|
| 355 |
+
# a = -3 * (1 - t) ** 2
|
| 356 |
+
double b = 3.0 * (1.0 - 4.0 * t + 3.0 * t2)
|
| 357 |
+
double c = 3.0 * t * (2.0 - 3.0 * t)
|
| 358 |
+
double d = 3.0 * t2
|
| 359 |
+
|
| 360 |
+
iadd_mul(result, self.p1, b)
|
| 361 |
+
iadd_mul(result, self.p2, c)
|
| 362 |
+
iadd_mul(result, self.p3, d)
|
| 363 |
+
|
| 364 |
+
return result
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
cdef void iadd_mul(Vec3 a, double[3] b, double c):
|
| 368 |
+
a.x += b[0] * c
|
| 369 |
+
a.y += b[1] * c
|
| 370 |
+
a.z += b[2] * c
|
| 371 |
+
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bspline.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/bspline.pyx
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2021-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import Iterable, Sequence, Iterator
|
| 5 |
+
import cython
|
| 6 |
+
from cpython.mem cimport PyMem_Malloc, PyMem_Free
|
| 7 |
+
from .vector cimport Vec3, isclose, v3_mul, v3_sub
|
| 8 |
+
|
| 9 |
+
__all__ = ['Basis', 'Evaluator']
|
| 10 |
+
|
| 11 |
+
cdef extern from "constants.h":
|
| 12 |
+
const double ABS_TOL
|
| 13 |
+
const double REL_TOL
|
| 14 |
+
const int MAX_SPLINE_ORDER
|
| 15 |
+
|
| 16 |
+
# factorial from 0 to 18
|
| 17 |
+
cdef double[19] FACTORIAL = [
|
| 18 |
+
1., 1., 2., 6., 24., 120., 720., 5040., 40320., 362880., 3628800.,
|
| 19 |
+
39916800., 479001600., 6227020800., 87178291200., 1307674368000.,
|
| 20 |
+
20922789888000., 355687428096000., 6402373705728000.
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
NULL_LIST = [0.0]
|
| 24 |
+
ONE_LIST = [1.0]
|
| 25 |
+
|
| 26 |
+
cdef Vec3 NULLVEC = Vec3()
|
| 27 |
+
|
| 28 |
+
@cython.cdivision(True)
|
| 29 |
+
cdef double binomial_coefficient(int k, int i):
|
| 30 |
+
cdef double k_fact = FACTORIAL[k]
|
| 31 |
+
cdef double i_fact = FACTORIAL[i]
|
| 32 |
+
cdef double k_i_fact
|
| 33 |
+
if i > k:
|
| 34 |
+
return 0.0
|
| 35 |
+
k_i_fact = FACTORIAL[k - i]
|
| 36 |
+
return k_fact / (k_i_fact * i_fact)
|
| 37 |
+
|
| 38 |
+
@cython.boundscheck(False)
|
| 39 |
+
cdef int bisect_right(double *a, double x, int lo, int hi):
|
| 40 |
+
cdef int mid
|
| 41 |
+
while lo < hi:
|
| 42 |
+
mid = (lo + hi) // 2
|
| 43 |
+
if x < a[mid]:
|
| 44 |
+
hi = mid
|
| 45 |
+
else:
|
| 46 |
+
lo = mid + 1
|
| 47 |
+
return lo
|
| 48 |
+
|
| 49 |
+
cdef reset_double_array(double *a, int count, double value):
|
| 50 |
+
cdef int i
|
| 51 |
+
for i in range(count):
|
| 52 |
+
a[i] = value
|
| 53 |
+
|
| 54 |
+
cdef class Basis:
|
| 55 |
+
""" Immutable Basis function class. """
|
| 56 |
+
# public:
|
| 57 |
+
cdef readonly int order
|
| 58 |
+
cdef readonly int count
|
| 59 |
+
cdef readonly double max_t
|
| 60 |
+
cdef tuple weights_ # public attribute for Cython Evaluator
|
| 61 |
+
# private:
|
| 62 |
+
cdef double *_knots
|
| 63 |
+
cdef int knot_count
|
| 64 |
+
|
| 65 |
+
def __cinit__(
|
| 66 |
+
self, knots: Iterable[float],
|
| 67 |
+
int order,
|
| 68 |
+
int count,
|
| 69 |
+
weights: Sequence[float] = None
|
| 70 |
+
):
|
| 71 |
+
if order < 2 or order >= MAX_SPLINE_ORDER:
|
| 72 |
+
raise ValueError('invalid order')
|
| 73 |
+
self.order = order
|
| 74 |
+
if count < 2:
|
| 75 |
+
raise ValueError('invalid count')
|
| 76 |
+
self.count = count
|
| 77 |
+
self.knot_count = self.order + self.count
|
| 78 |
+
self.weights_ = tuple(float(x) for x in weights) if weights else tuple()
|
| 79 |
+
|
| 80 |
+
cdef Py_ssize_t i = len(self.weights_)
|
| 81 |
+
if i != 0 and i != self.count:
|
| 82 |
+
raise ValueError('invalid weight count')
|
| 83 |
+
|
| 84 |
+
knots = [float(x) for x in knots]
|
| 85 |
+
if len(knots) != self.knot_count:
|
| 86 |
+
raise ValueError('invalid knot count')
|
| 87 |
+
|
| 88 |
+
self._knots = <double *> PyMem_Malloc(self.knot_count * sizeof(double))
|
| 89 |
+
for i in range(self.knot_count):
|
| 90 |
+
self._knots[i] = knots[i]
|
| 91 |
+
self.max_t = self._knots[self.knot_count - 1]
|
| 92 |
+
|
| 93 |
+
def __dealloc__(self):
|
| 94 |
+
PyMem_Free(self._knots)
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def degree(self) -> int:
|
| 98 |
+
return self.order - 1
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def knots(self) -> tuple[float, ...]:
|
| 102 |
+
return tuple(x for x in self._knots[:self.knot_count])
|
| 103 |
+
|
| 104 |
+
@property
|
| 105 |
+
def weights(self) -> tuple[float, ...]:
|
| 106 |
+
return self.weights_
|
| 107 |
+
|
| 108 |
+
@property
|
| 109 |
+
def is_rational(self) -> bool:
|
| 110 |
+
""" Returns ``True`` if curve is a rational B-spline. (has weights) """
|
| 111 |
+
return bool(self.weights_)
|
| 112 |
+
|
| 113 |
+
cpdef list basis_vector(self, double t):
|
| 114 |
+
""" Returns the expanded basis vector. """
|
| 115 |
+
|
| 116 |
+
cdef int span = self.find_span(t)
|
| 117 |
+
cdef int p = self.order - 1
|
| 118 |
+
cdef int front = span - p
|
| 119 |
+
cdef int back = self.count - span - 1
|
| 120 |
+
cdef list result
|
| 121 |
+
if front > 0:
|
| 122 |
+
result = NULL_LIST * front
|
| 123 |
+
result.extend(self.basis_funcs(span, t))
|
| 124 |
+
else:
|
| 125 |
+
result = self.basis_funcs(span, t)
|
| 126 |
+
if back > 0:
|
| 127 |
+
result.extend(NULL_LIST * back)
|
| 128 |
+
return result
|
| 129 |
+
|
| 130 |
+
cpdef int find_span(self, double u):
|
| 131 |
+
""" Determine the knot span index. """
|
| 132 |
+
# Linear search is more reliable than binary search of the Algorithm A2.1
|
| 133 |
+
# from The NURBS Book by Piegl & Tiller.
|
| 134 |
+
cdef double *knots = self._knots
|
| 135 |
+
cdef int count = self.count # text book: n+1
|
| 136 |
+
cdef int p = self.order - 1
|
| 137 |
+
cdef int span
|
| 138 |
+
if u >= knots[count]: # special case
|
| 139 |
+
return count - 1
|
| 140 |
+
|
| 141 |
+
# common clamped spline:
|
| 142 |
+
if knots[p] == 0.0: # use binary search
|
| 143 |
+
# This is fast and works most of the time,
|
| 144 |
+
# but Test 621 : test_weired_closed_spline()
|
| 145 |
+
# goes into an infinity loop, because of
|
| 146 |
+
# a weird knot configuration.
|
| 147 |
+
return bisect_right(knots, u, p, count) - 1
|
| 148 |
+
else: # use linear search
|
| 149 |
+
span = 0
|
| 150 |
+
while knots[span] <= u and span < count:
|
| 151 |
+
span += 1
|
| 152 |
+
return span - 1
|
| 153 |
+
|
| 154 |
+
cpdef list basis_funcs(self, int span, double u):
|
| 155 |
+
# Source: The NURBS Book: Algorithm A2.2
|
| 156 |
+
cdef int order = self.order
|
| 157 |
+
cdef double *knots = self._knots
|
| 158 |
+
cdef double[MAX_SPLINE_ORDER] N, left, right # pyright: ignore
|
| 159 |
+
cdef list result
|
| 160 |
+
reset_double_array(N, order, 0.0)
|
| 161 |
+
reset_double_array(left, order, 0.0)
|
| 162 |
+
reset_double_array(right, order, 0.0)
|
| 163 |
+
|
| 164 |
+
cdef int j, r, i1
|
| 165 |
+
cdef double temp, saved, temp_r, temp_l
|
| 166 |
+
N[0] = 1.0
|
| 167 |
+
for j in range(1, order):
|
| 168 |
+
i1 = span + 1 - j
|
| 169 |
+
if i1 < 0:
|
| 170 |
+
i1 = 0
|
| 171 |
+
left[j] = u - knots[i1]
|
| 172 |
+
right[j] = knots[span + j] - u
|
| 173 |
+
saved = 0.0
|
| 174 |
+
for r in range(j):
|
| 175 |
+
temp_r = right[r + 1]
|
| 176 |
+
temp_l = left[j - r]
|
| 177 |
+
temp = N[r] / (temp_r + temp_l)
|
| 178 |
+
N[r] = saved + temp_r * temp
|
| 179 |
+
saved = temp_l * temp
|
| 180 |
+
N[j] = saved
|
| 181 |
+
result = [x for x in N[:order]]
|
| 182 |
+
if self.is_rational:
|
| 183 |
+
return self.span_weighting(result, span)
|
| 184 |
+
else:
|
| 185 |
+
return result
|
| 186 |
+
|
| 187 |
+
cpdef list span_weighting(self, nbasis: list[float], int span):
|
| 188 |
+
cdef list products = [
|
| 189 |
+
nb * w for nb, w in zip(
|
| 190 |
+
nbasis,
|
| 191 |
+
self.weights_[span - self.order + 1: span + 1]
|
| 192 |
+
)
|
| 193 |
+
]
|
| 194 |
+
if len(products) != len(nbasis):
|
| 195 |
+
return nbasis
|
| 196 |
+
s = sum(products)
|
| 197 |
+
if s != 0:
|
| 198 |
+
return [p / s for p in products]
|
| 199 |
+
else:
|
| 200 |
+
return nbasis
|
| 201 |
+
|
| 202 |
+
cpdef list basis_funcs_derivatives(self, int span, double u, int n = 1):
|
| 203 |
+
# pyright: reportUndefinedVariable=false
|
| 204 |
+
# pyright flags Cython multi-arrays incorrect:
|
| 205 |
+
# cdef double[4][4] a # this is a valid array definition in Cython!
|
| 206 |
+
# https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#c-arrays
|
| 207 |
+
# Source: The NURBS Book: Algorithm A2.3
|
| 208 |
+
cdef int order = self.order
|
| 209 |
+
cdef int p = order - 1
|
| 210 |
+
if n > p:
|
| 211 |
+
n = p
|
| 212 |
+
cdef double *knots = self._knots
|
| 213 |
+
cdef double[MAX_SPLINE_ORDER] left, right # pyright: ignore
|
| 214 |
+
reset_double_array(left, order, 1.0)
|
| 215 |
+
reset_double_array(right, order, 1.0)
|
| 216 |
+
|
| 217 |
+
cdef double[MAX_SPLINE_ORDER][MAX_SPLINE_ORDER] ndu # pyright: ignore
|
| 218 |
+
reset_double_array(<double *> ndu, MAX_SPLINE_ORDER*MAX_SPLINE_ORDER, 1.0)
|
| 219 |
+
|
| 220 |
+
cdef int j, r, i1
|
| 221 |
+
cdef double temp, saved, tmp_r, tmp_l
|
| 222 |
+
for j in range(1, order):
|
| 223 |
+
i1 = span + 1 - j
|
| 224 |
+
if i1 < 0:
|
| 225 |
+
i1 = 0
|
| 226 |
+
left[j] = u - knots[i1]
|
| 227 |
+
right[j] = knots[span + j] - u
|
| 228 |
+
saved = 0.0
|
| 229 |
+
for r in range(j):
|
| 230 |
+
# lower triangle
|
| 231 |
+
tmp_r = right[r + 1]
|
| 232 |
+
tmp_l = left[j - r]
|
| 233 |
+
ndu[j][r] = tmp_r + tmp_l
|
| 234 |
+
temp = ndu[r][j - 1] / ndu[j][r]
|
| 235 |
+
# upper triangle
|
| 236 |
+
ndu[r][j] = saved + (tmp_r * temp)
|
| 237 |
+
saved = tmp_l * temp
|
| 238 |
+
ndu[j][j] = saved
|
| 239 |
+
|
| 240 |
+
# load the basis_vector functions
|
| 241 |
+
cdef double[MAX_SPLINE_ORDER][MAX_SPLINE_ORDER] derivatives # pyright: ignore
|
| 242 |
+
reset_double_array(
|
| 243 |
+
<double *> derivatives, MAX_SPLINE_ORDER*MAX_SPLINE_ORDER, 0.0
|
| 244 |
+
)
|
| 245 |
+
for j in range(order):
|
| 246 |
+
derivatives[0][j] = ndu[j][p]
|
| 247 |
+
|
| 248 |
+
# loop over function index
|
| 249 |
+
cdef double[2][MAX_SPLINE_ORDER] a # pyright: ignore
|
| 250 |
+
reset_double_array(<double *> a, 2*MAX_SPLINE_ORDER, 1.0)
|
| 251 |
+
|
| 252 |
+
cdef int s1, s2, k, rk, pk, j1, j2, t
|
| 253 |
+
cdef double d
|
| 254 |
+
for r in range(order):
|
| 255 |
+
s1 = 0
|
| 256 |
+
s2 = 1
|
| 257 |
+
# alternate rows in array a
|
| 258 |
+
a[0][0] = 1.0
|
| 259 |
+
|
| 260 |
+
# loop to compute kth derivative
|
| 261 |
+
for k in range(1, n + 1):
|
| 262 |
+
d = 0.0
|
| 263 |
+
rk = r - k
|
| 264 |
+
pk = p - k
|
| 265 |
+
if r >= k:
|
| 266 |
+
a[s2][0] = a[s1][0] / ndu[pk + 1][rk]
|
| 267 |
+
d = a[s2][0] * ndu[rk][pk]
|
| 268 |
+
if rk >= -1:
|
| 269 |
+
j1 = 1
|
| 270 |
+
else:
|
| 271 |
+
j1 = -rk
|
| 272 |
+
if (r - 1) <= pk:
|
| 273 |
+
j2 = k - 1
|
| 274 |
+
else:
|
| 275 |
+
j2 = p - r
|
| 276 |
+
for j in range(j1, j2 + 1):
|
| 277 |
+
a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]
|
| 278 |
+
d += (a[s2][j] * ndu[rk + j][pk])
|
| 279 |
+
if r <= pk:
|
| 280 |
+
a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]
|
| 281 |
+
d += (a[s2][k] * ndu[r][pk])
|
| 282 |
+
derivatives[k][r] = d
|
| 283 |
+
|
| 284 |
+
# Switch rows
|
| 285 |
+
t = s1
|
| 286 |
+
s1 = s2
|
| 287 |
+
s2 = t
|
| 288 |
+
|
| 289 |
+
# Multiply through by the correct factors
|
| 290 |
+
cdef double rr = p
|
| 291 |
+
for k in range(1, n + 1):
|
| 292 |
+
for j in range(order):
|
| 293 |
+
derivatives[k][j] *= rr
|
| 294 |
+
rr *= (p - k)
|
| 295 |
+
|
| 296 |
+
# return result as Python lists
|
| 297 |
+
cdef list result = [], row
|
| 298 |
+
for k in range(0, n + 1):
|
| 299 |
+
row = []
|
| 300 |
+
result.append(row)
|
| 301 |
+
for j in range(order):
|
| 302 |
+
row.append(derivatives[k][j])
|
| 303 |
+
return result
|
| 304 |
+
|
| 305 |
+
cdef class Evaluator:
|
| 306 |
+
""" B-spline curve point and curve derivative evaluator. """
|
| 307 |
+
cdef Basis _basis
|
| 308 |
+
cdef tuple _control_points
|
| 309 |
+
|
| 310 |
+
def __cinit__(self, basis: Basis, control_points: Sequence[Vec3]):
|
| 311 |
+
self._basis = basis
|
| 312 |
+
self._control_points = Vec3.tuple(control_points)
|
| 313 |
+
|
| 314 |
+
cpdef Vec3 point(self, double u):
|
| 315 |
+
# Source: The NURBS Book: Algorithm A3.1
|
| 316 |
+
cdef Basis basis = self._basis
|
| 317 |
+
if isclose(u, basis.max_t, REL_TOL, ABS_TOL):
|
| 318 |
+
u = basis.max_t
|
| 319 |
+
cdef:
|
| 320 |
+
int p = basis.order - 1
|
| 321 |
+
int span = basis.find_span(u)
|
| 322 |
+
list N = basis.basis_funcs(span, u)
|
| 323 |
+
int i
|
| 324 |
+
Vec3 cpoint, v3_sum = Vec3()
|
| 325 |
+
tuple control_points = self._control_points
|
| 326 |
+
double factor
|
| 327 |
+
|
| 328 |
+
for i in range(p + 1):
|
| 329 |
+
factor = <double> N[i]
|
| 330 |
+
cpoint = <Vec3> control_points[span - p + i]
|
| 331 |
+
v3_sum.x += cpoint.x * factor
|
| 332 |
+
v3_sum.y += cpoint.y * factor
|
| 333 |
+
v3_sum.z += cpoint.z * factor
|
| 334 |
+
return v3_sum
|
| 335 |
+
|
| 336 |
+
def points(self, t: Iterable[float]) -> Iterator[Vec3]:
|
| 337 |
+
cdef double u
|
| 338 |
+
for u in t:
|
| 339 |
+
yield self.point(u)
|
| 340 |
+
|
| 341 |
+
cpdef list derivative(self, double u, int n = 1):
|
| 342 |
+
""" Return point and derivatives up to n <= degree for parameter u. """
|
| 343 |
+
# Source: The NURBS Book: Algorithm A3.2
|
| 344 |
+
|
| 345 |
+
cdef Basis basis = self._basis
|
| 346 |
+
if isclose(u, basis.max_t, REL_TOL, ABS_TOL):
|
| 347 |
+
u = basis.max_t
|
| 348 |
+
cdef:
|
| 349 |
+
list CK = [], CKw = [], wders = []
|
| 350 |
+
tuple control_points = self._control_points
|
| 351 |
+
tuple weights
|
| 352 |
+
Vec3 cpoint, v3_sum
|
| 353 |
+
double wder, bas_func_weight, bas_func
|
| 354 |
+
int k, j, i, p = basis.degree
|
| 355 |
+
int span = basis.find_span(u)
|
| 356 |
+
list basis_funcs_ders = basis.basis_funcs_derivatives(span, u, n)
|
| 357 |
+
|
| 358 |
+
if basis.is_rational:
|
| 359 |
+
# Homogeneous point representation required:
|
| 360 |
+
# (x*w, y*w, z*w, w)
|
| 361 |
+
weights = basis.weights_
|
| 362 |
+
for k in range(n + 1):
|
| 363 |
+
v3_sum = Vec3()
|
| 364 |
+
wder = 0.0
|
| 365 |
+
for j in range(p + 1):
|
| 366 |
+
i = span - p + j
|
| 367 |
+
bas_func_weight = basis_funcs_ders[k][j] * weights[i]
|
| 368 |
+
# control_point * weight * bas_func_der = (x*w, y*w, z*w) * bas_func_der
|
| 369 |
+
cpoint = <Vec3> control_points[i]
|
| 370 |
+
v3_sum.x += cpoint.x * bas_func_weight
|
| 371 |
+
v3_sum.y += cpoint.y * bas_func_weight
|
| 372 |
+
v3_sum.z += cpoint.z * bas_func_weight
|
| 373 |
+
wder += bas_func_weight
|
| 374 |
+
CKw.append(v3_sum)
|
| 375 |
+
wders.append(wder)
|
| 376 |
+
|
| 377 |
+
# Source: The NURBS Book: Algorithm A4.2
|
| 378 |
+
for k in range(n + 1):
|
| 379 |
+
v3_sum = CKw[k]
|
| 380 |
+
for j in range(1, k + 1):
|
| 381 |
+
bas_func_weight = binomial_coefficient(k, j) * wders[j]
|
| 382 |
+
v3_sum = v3_sub(
|
| 383 |
+
v3_sum,
|
| 384 |
+
v3_mul(CK[k - j], bas_func_weight)
|
| 385 |
+
)
|
| 386 |
+
CK.append(v3_sum / wders[0])
|
| 387 |
+
else:
|
| 388 |
+
for k in range(n + 1):
|
| 389 |
+
v3_sum = Vec3()
|
| 390 |
+
for j in range(p + 1):
|
| 391 |
+
bas_func = basis_funcs_ders[k][j]
|
| 392 |
+
cpoint = <Vec3> control_points[span - p + j]
|
| 393 |
+
v3_sum.x += cpoint.x * bas_func
|
| 394 |
+
v3_sum.y += cpoint.y * bas_func
|
| 395 |
+
v3_sum.z += cpoint.z * bas_func
|
| 396 |
+
CK.append(v3_sum)
|
| 397 |
+
return CK
|
| 398 |
+
|
| 399 |
+
def derivatives(self, t: Iterable[float], int n = 1) -> Iterator[list[Vec3]]:
|
| 400 |
+
cdef double u
|
| 401 |
+
for u in t:
|
| 402 |
+
yield self.derivative(u, n)
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/constants.h
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
// License: MIT License
|
| 3 |
+
// global constants
|
| 4 |
+
#define ABS_TOL 1e-12
|
| 5 |
+
#define REL_TOL 1e-9
|
| 6 |
+
#define M_TAU 6.283185307179586
|
| 7 |
+
// AutoCAD limits the degree of SPLINE to 11 or order = 12
|
| 8 |
+
#define MAX_SPLINE_ORDER 12
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/construct.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2020-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import Iterable, TYPE_CHECKING, Sequence, Optional
|
| 5 |
+
from libc.math cimport fabs, M_PI, M_PI_2, M_PI_4, M_E, sin, tan, pow, atan, log
|
| 6 |
+
from .vector cimport (
|
| 7 |
+
isclose,
|
| 8 |
+
Vec2,
|
| 9 |
+
v2_isclose,
|
| 10 |
+
Vec3,
|
| 11 |
+
v3_sub,
|
| 12 |
+
v3_add,
|
| 13 |
+
v3_mul,
|
| 14 |
+
v3_normalize,
|
| 15 |
+
v3_cross,
|
| 16 |
+
v3_magnitude_sqr,
|
| 17 |
+
v3_isclose,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
import cython
|
| 21 |
+
|
| 22 |
+
if TYPE_CHECKING:
|
| 23 |
+
from ezdxf.math import UVec
|
| 24 |
+
|
| 25 |
+
cdef extern from "constants.h":
|
| 26 |
+
const double ABS_TOL
|
| 27 |
+
const double REL_TOL
|
| 28 |
+
const double M_TAU
|
| 29 |
+
|
| 30 |
+
cdef double RAD_ABS_TOL = 1e-15
|
| 31 |
+
cdef double DEG_ABS_TOL = 1e-13
|
| 32 |
+
cdef double TOLERANCE = 1e-10
|
| 33 |
+
|
| 34 |
+
def has_clockwise_orientation(vertices: Iterable[UVec]) -> bool:
|
| 35 |
+
""" Returns True if 2D `vertices` have clockwise orientation. Ignores
|
| 36 |
+
z-axis of all vertices.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
vertices: iterable of :class:`Vec2` compatible objects
|
| 40 |
+
|
| 41 |
+
Raises:
|
| 42 |
+
ValueError: less than 3 vertices
|
| 43 |
+
|
| 44 |
+
"""
|
| 45 |
+
cdef list _vertices = [Vec2(v) for v in vertices]
|
| 46 |
+
if len(_vertices) < 3:
|
| 47 |
+
raise ValueError('At least 3 vertices required.')
|
| 48 |
+
|
| 49 |
+
cdef Vec2 p1 = <Vec2> _vertices[0]
|
| 50 |
+
cdef Vec2 p2 = <Vec2> _vertices[-1]
|
| 51 |
+
cdef double s = 0.0
|
| 52 |
+
cdef Py_ssize_t index
|
| 53 |
+
|
| 54 |
+
# Using the same tolerance as the Python implementation:
|
| 55 |
+
if not v2_isclose(p1, p2, REL_TOL, ABS_TOL):
|
| 56 |
+
_vertices.append(p1)
|
| 57 |
+
|
| 58 |
+
for index in range(1, len(_vertices)):
|
| 59 |
+
p2 = <Vec2> _vertices[index]
|
| 60 |
+
s += (p2.x - p1.x) * (p2.y + p1.y)
|
| 61 |
+
p1 = p2
|
| 62 |
+
return s > 0.0
|
| 63 |
+
|
| 64 |
+
def intersection_line_line_2d(
|
| 65 |
+
line1: Sequence[Vec2],
|
| 66 |
+
line2: Sequence[Vec2],
|
| 67 |
+
bint virtual=True,
|
| 68 |
+
double abs_tol=TOLERANCE) -> Optional[Vec2]:
|
| 69 |
+
"""
|
| 70 |
+
Compute the intersection of two lines in the xy-plane.
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
line1: start- and end point of first line to test
|
| 74 |
+
e.g. ((x1, y1), (x2, y2)).
|
| 75 |
+
line2: start- and end point of second line to test
|
| 76 |
+
e.g. ((x3, y3), (x4, y4)).
|
| 77 |
+
virtual: ``True`` returns any intersection point, ``False`` returns
|
| 78 |
+
only real intersection points.
|
| 79 |
+
abs_tol: tolerance for intersection test.
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
``None`` if there is no intersection point (parallel lines) or
|
| 83 |
+
intersection point as :class:`Vec2`
|
| 84 |
+
|
| 85 |
+
"""
|
| 86 |
+
# Algorithm based on: http://paulbourke.net/geometry/pointlineplane/
|
| 87 |
+
# chapter: Intersection point of two line segments in 2 dimensions
|
| 88 |
+
cdef Vec2 s1, s2, c1, c2, res
|
| 89 |
+
cdef double s1x, s1y, s2x, s2y, c1x, c1y, c2x, c2y, den, us, uc
|
| 90 |
+
cdef double lwr = 0.0, upr = 1.0
|
| 91 |
+
|
| 92 |
+
s1 = line1[0]
|
| 93 |
+
s2 = line1[1]
|
| 94 |
+
c1 = line2[0]
|
| 95 |
+
c2 = line2[1]
|
| 96 |
+
|
| 97 |
+
s1x = s1.x
|
| 98 |
+
s1y = s1.y
|
| 99 |
+
s2x = s2.x
|
| 100 |
+
s2y = s2.y
|
| 101 |
+
c1x = c1.x
|
| 102 |
+
c1y = c1.y
|
| 103 |
+
c2x = c2.x
|
| 104 |
+
c2y = c2.y
|
| 105 |
+
|
| 106 |
+
den = (c2y - c1y) * (s2x - s1x) - (c2x - c1x) * (s2y - s1y)
|
| 107 |
+
|
| 108 |
+
if fabs(den) <= abs_tol:
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# den near zero is checked by if-statement above:
|
| 113 |
+
with cython.cdivision(True):
|
| 114 |
+
us = ((c2x - c1x) * (s1y - c1y) - (c2y - c1y) * (s1x - c1x)) / den
|
| 115 |
+
|
| 116 |
+
res = Vec2(s1x + us * (s2x - s1x), s1y + us * (s2y - s1y))
|
| 117 |
+
if virtual:
|
| 118 |
+
return res
|
| 119 |
+
|
| 120 |
+
# 0 = intersection point is the start point of the line
|
| 121 |
+
# 1 = intersection point is the end point of the line
|
| 122 |
+
# otherwise: linear interpolation
|
| 123 |
+
if lwr <= us <= upr: # intersection point is on the subject line
|
| 124 |
+
with cython.cdivision(True):
|
| 125 |
+
uc = ((s2x - s1x) * (s1y - c1y) - (s2y - s1y) * (s1x - c1x)) / den
|
| 126 |
+
if lwr <= uc <= upr: # intersection point is on the clipping line
|
| 127 |
+
return res
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
cdef double _determinant(Vec3 v1, Vec3 v2, Vec3 v3):
|
| 131 |
+
return v1.x * v2.y * v3.z + v1.y * v2.z * v3.x + \
|
| 132 |
+
v1.z * v2.x * v3.y - v1.z * v2.y * v3.x - \
|
| 133 |
+
v1.x * v2.z * v3.y - v1.y * v2.x * v3.z
|
| 134 |
+
|
| 135 |
+
def intersection_ray_ray_3d(
|
| 136 |
+
ray1: tuple[Vec3, Vec3],
|
| 137 |
+
ray2: tuple[Vec3, Vec3],
|
| 138 |
+
double abs_tol=TOLERANCE
|
| 139 |
+
) -> Sequence[Vec3]:
|
| 140 |
+
"""
|
| 141 |
+
Calculate intersection of two 3D rays, returns a 0-tuple for parallel rays,
|
| 142 |
+
a 1-tuple for intersecting rays and a 2-tuple for not intersecting and not
|
| 143 |
+
parallel rays with points of closest approach on each ray.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
ray1: first ray as tuple of two points as Vec3() objects
|
| 147 |
+
ray2: second ray as tuple of two points as Vec3() objects
|
| 148 |
+
abs_tol: absolute tolerance for comparisons
|
| 149 |
+
|
| 150 |
+
"""
|
| 151 |
+
# source: http://www.realtimerendering.com/intersections.html#I304
|
| 152 |
+
cdef:
|
| 153 |
+
Vec3 o2_o1
|
| 154 |
+
double det1, det2
|
| 155 |
+
Vec3 o1 = Vec3(ray1[0])
|
| 156 |
+
Vec3 p1 = Vec3(ray1[1])
|
| 157 |
+
Vec3 o2 = Vec3(ray2[0])
|
| 158 |
+
Vec3 p2 = Vec3(ray2[1])
|
| 159 |
+
Vec3 d1 = v3_normalize(v3_sub(p1, o1), 1.0)
|
| 160 |
+
Vec3 d2 = v3_normalize(v3_sub(p2, o2), 1.0)
|
| 161 |
+
Vec3 d1xd2 = v3_cross(d1, d2)
|
| 162 |
+
double denominator = v3_magnitude_sqr(d1xd2)
|
| 163 |
+
|
| 164 |
+
if denominator <= abs_tol:
|
| 165 |
+
# ray1 is parallel to ray2
|
| 166 |
+
return tuple()
|
| 167 |
+
else:
|
| 168 |
+
o2_o1 = v3_sub(o2, o1)
|
| 169 |
+
det1 = _determinant(o2_o1, d2, d1xd2)
|
| 170 |
+
det2 = _determinant(o2_o1, d1, d1xd2)
|
| 171 |
+
with cython.cdivision(True): # denominator check is already done
|
| 172 |
+
p1 = v3_add(o1, v3_mul(d1, (det1 / denominator)))
|
| 173 |
+
p2 = v3_add(o2, v3_mul(d2, (det2 / denominator)))
|
| 174 |
+
|
| 175 |
+
if v3_isclose(p1, p2, abs_tol, abs_tol):
|
| 176 |
+
# ray1 and ray2 have an intersection point
|
| 177 |
+
return p1,
|
| 178 |
+
else:
|
| 179 |
+
# ray1 and ray2 do not have an intersection point,
|
| 180 |
+
# p1 and p2 are the points of closest approach on each ray
|
| 181 |
+
return p1, p2
|
| 182 |
+
|
| 183 |
+
def arc_angle_span_deg(double start, double end) -> float:
|
| 184 |
+
if isclose(start, end, REL_TOL, DEG_ABS_TOL):
|
| 185 |
+
return 0.0
|
| 186 |
+
|
| 187 |
+
start %= 360.0
|
| 188 |
+
if isclose(start, end % 360.0, REL_TOL, DEG_ABS_TOL):
|
| 189 |
+
return 360.0
|
| 190 |
+
|
| 191 |
+
if not isclose(end, 360.0, REL_TOL, DEG_ABS_TOL):
|
| 192 |
+
end %= 360.0
|
| 193 |
+
|
| 194 |
+
if end < start:
|
| 195 |
+
end += 360.0
|
| 196 |
+
return end - start
|
| 197 |
+
|
| 198 |
+
def arc_angle_span_rad(double start, double end) -> float:
|
| 199 |
+
if isclose(start, end, REL_TOL, RAD_ABS_TOL):
|
| 200 |
+
return 0.0
|
| 201 |
+
|
| 202 |
+
start %= M_TAU
|
| 203 |
+
if isclose(start, end % M_TAU, REL_TOL, RAD_ABS_TOL):
|
| 204 |
+
return M_TAU
|
| 205 |
+
|
| 206 |
+
if not isclose(end, M_TAU, REL_TOL, RAD_ABS_TOL):
|
| 207 |
+
end %= M_TAU
|
| 208 |
+
|
| 209 |
+
if end < start:
|
| 210 |
+
end += M_TAU
|
| 211 |
+
return end - start
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def is_point_in_polygon_2d(
|
| 215 |
+
point: Vec2, polygon: list[Vec2], double abs_tol=TOLERANCE
|
| 216 |
+
) -> int:
|
| 217 |
+
"""
|
| 218 |
+
Test if `point` is inside `polygon`. Returns +1 for inside, 0 for on the
|
| 219 |
+
boundary and -1 for outside.
|
| 220 |
+
|
| 221 |
+
Supports convex and concave polygons with clockwise or counter-clockwise oriented
|
| 222 |
+
polygon vertices. Does not raise an exception for degenerated polygons.
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
point: 2D point to test as :class:`Vec2`
|
| 227 |
+
polygon: list of 2D points as :class:`Vec2`
|
| 228 |
+
abs_tol: tolerance for distance check
|
| 229 |
+
|
| 230 |
+
Returns:
|
| 231 |
+
+1 for inside, 0 for on the boundary, -1 for outside
|
| 232 |
+
|
| 233 |
+
"""
|
| 234 |
+
# Source: http://www.faqs.org/faqs/graphics/algorithms-faq/
|
| 235 |
+
# Subject 2.03: How do I find if a point lies within a polygon?
|
| 236 |
+
# Numpy version was just 10x faster, this version is 23x faster than the Python
|
| 237 |
+
# version!
|
| 238 |
+
cdef double a, b, c, d, x, y, x1, y1, x2, y2
|
| 239 |
+
cdef list vertices = polygon
|
| 240 |
+
cdef Vec2 p1, p2
|
| 241 |
+
cdef int size, last, i
|
| 242 |
+
cdef bint inside = 0
|
| 243 |
+
|
| 244 |
+
size = len(vertices)
|
| 245 |
+
if size < 3: # empty polygon
|
| 246 |
+
return -1
|
| 247 |
+
last = size - 1
|
| 248 |
+
p1 = <Vec2> vertices[0]
|
| 249 |
+
p2 = <Vec2> vertices[last]
|
| 250 |
+
|
| 251 |
+
if v2_isclose(p1, p2, REL_TOL, ABS_TOL): # open polygon
|
| 252 |
+
size -= 1
|
| 253 |
+
last -= 1
|
| 254 |
+
if size < 3:
|
| 255 |
+
return -1
|
| 256 |
+
|
| 257 |
+
x = point.x
|
| 258 |
+
y = point.y
|
| 259 |
+
p1 = <Vec2> vertices[last]
|
| 260 |
+
x1 = p1.x
|
| 261 |
+
y1 = p1.y
|
| 262 |
+
|
| 263 |
+
for i in range(size):
|
| 264 |
+
p2 = <Vec2> vertices[i]
|
| 265 |
+
x2 = p2.x
|
| 266 |
+
y2 = p2.y
|
| 267 |
+
|
| 268 |
+
# is point on polygon boundary line:
|
| 269 |
+
# is point in x-range of line
|
| 270 |
+
a, b = (x2, x1) if x2 < x1 else (x1, x2)
|
| 271 |
+
if a <= x <= b:
|
| 272 |
+
# is point in y-range of line
|
| 273 |
+
c, d = (y2, y1) if y2 < y1 else (y1, y2)
|
| 274 |
+
if (c <= y <= d) and fabs(
|
| 275 |
+
(y2 - y1) * x - (x2 - x1) * y + (x2 * y1 - y2 * x1)
|
| 276 |
+
) <= abs_tol:
|
| 277 |
+
return 0 # on boundary line
|
| 278 |
+
if ((y1 <= y < y2) or (y2 <= y < y1)) and (
|
| 279 |
+
x < (x2 - x1) * (y - y1) / (y2 - y1) + x1
|
| 280 |
+
):
|
| 281 |
+
inside = not inside
|
| 282 |
+
x1 = x2
|
| 283 |
+
y1 = y2
|
| 284 |
+
if inside:
|
| 285 |
+
return 1 # inside polygon
|
| 286 |
+
else:
|
| 287 |
+
return -1 # outside polygon
|
| 288 |
+
|
| 289 |
+
cdef double WGS84_SEMI_MAJOR_AXIS = 6378137
|
| 290 |
+
cdef double WGS84_SEMI_MINOR_AXIS = 6356752.3142
|
| 291 |
+
cdef double WGS84_ELLIPSOID_ECCENTRIC = 0.08181919092890624
|
| 292 |
+
cdef double RADIANS = M_PI / 180.0
|
| 293 |
+
cdef double DEGREES = 180.0 / M_PI
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def gps_to_world_mercator(double longitude, double latitude) -> tuple[float, float]:
|
| 297 |
+
"""Transform GPS (long/lat) to World Mercator.
|
| 298 |
+
|
| 299 |
+
Transform WGS84 `EPSG:4326 <https://epsg.io/4326>`_ location given as
|
| 300 |
+
latitude and longitude in decimal degrees as used by GPS into World Mercator
|
| 301 |
+
cartesian 2D coordinates in meters `EPSG:3395 <https://epsg.io/3395>`_.
|
| 302 |
+
|
| 303 |
+
Args:
|
| 304 |
+
longitude: represents the longitude value (East-West) in decimal degrees
|
| 305 |
+
latitude: represents the latitude value (North-South) in decimal degrees.
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
# From: https://epsg.io/4326
|
| 309 |
+
# EPSG:4326 WGS84 - World Geodetic System 1984, used in GPS
|
| 310 |
+
# To: https://epsg.io/3395
|
| 311 |
+
# EPSG:3395 - World Mercator
|
| 312 |
+
# Source: https://gis.stackexchange.com/questions/259121/transformation-functions-for-epsg3395-projection-vs-epsg3857
|
| 313 |
+
longitude = longitude * RADIANS # east
|
| 314 |
+
latitude = latitude * RADIANS # north
|
| 315 |
+
cdef double e_sin_lat = sin(latitude) * WGS84_ELLIPSOID_ECCENTRIC
|
| 316 |
+
cdef double c = pow(
|
| 317 |
+
(1.0 - e_sin_lat) / (1.0 + e_sin_lat), WGS84_ELLIPSOID_ECCENTRIC / 2.0
|
| 318 |
+
) # 7-7 p.44
|
| 319 |
+
y = WGS84_SEMI_MAJOR_AXIS * log(tan(M_PI_4 + latitude / 2.0) * c) # 7-7 p.44
|
| 320 |
+
x = WGS84_SEMI_MAJOR_AXIS * longitude
|
| 321 |
+
return x, y
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def world_mercator_to_gps(double x, double y, double tol = 1e-6) -> tuple[float, float]:
|
| 325 |
+
"""Transform World Mercator to GPS.
|
| 326 |
+
|
| 327 |
+
Transform WGS84 World Mercator `EPSG:3395 <https://epsg.io/3395>`_
|
| 328 |
+
location given as cartesian 2D coordinates x, y in meters into WGS84 decimal
|
| 329 |
+
degrees as longitude and latitude `EPSG:4326 <https://epsg.io/4326>`_ as
|
| 330 |
+
used by GPS.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
x: coordinate WGS84 World Mercator
|
| 334 |
+
y: coordinate WGS84 World Mercator
|
| 335 |
+
tol: accuracy for latitude calculation
|
| 336 |
+
|
| 337 |
+
"""
|
| 338 |
+
# From: https://epsg.io/3395
|
| 339 |
+
# EPSG:3395 - World Mercator
|
| 340 |
+
# To: https://epsg.io/4326
|
| 341 |
+
# EPSG:4326 WGS84 - World Geodetic System 1984, used in GPS
|
| 342 |
+
# Source: Map Projections - A Working Manual
|
| 343 |
+
# https://pubs.usgs.gov/pp/1395/report.pdf
|
| 344 |
+
cdef double eccentric_2 = WGS84_ELLIPSOID_ECCENTRIC / 2.0
|
| 345 |
+
cdef double t = pow(M_E, (-y / WGS84_SEMI_MAJOR_AXIS)) # 7-10 p.44
|
| 346 |
+
cdef double e_sin_lat, latitude, latitude_prev
|
| 347 |
+
|
| 348 |
+
latitude_prev = M_PI_2 - 2.0 * atan(t) # 7-11 p.45
|
| 349 |
+
while True:
|
| 350 |
+
e_sin_lat = sin(latitude_prev) * WGS84_ELLIPSOID_ECCENTRIC
|
| 351 |
+
latitude = M_PI_2 - 2.0 * atan(
|
| 352 |
+
t * pow(((1.0 - e_sin_lat) / (1.0 + e_sin_lat)), eccentric_2)
|
| 353 |
+
) # 7-9 p.44
|
| 354 |
+
if fabs(latitude - latitude_prev) < tol:
|
| 355 |
+
break
|
| 356 |
+
latitude_prev = latitude
|
| 357 |
+
|
| 358 |
+
longitude = x / WGS84_SEMI_MAJOR_AXIS # 7-12 p.45
|
| 359 |
+
return longitude * DEGREES, latitude * DEGREES
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/linetypes.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/linetypes.pyx
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import Iterator, TYPE_CHECKING, Sequence
|
| 5 |
+
import cython
|
| 6 |
+
from cpython.mem cimport PyMem_Malloc, PyMem_Free
|
| 7 |
+
from .vector cimport Vec3, v3_isclose, v3_sub, v3_add, v3_mul, v3_magnitude
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
from ezdxf.math import UVec
|
| 11 |
+
|
| 12 |
+
__all__ = ["_LineTypeRenderer"]
|
| 13 |
+
LineSegment = tuple[Vec3, Vec3]
|
| 14 |
+
|
| 15 |
+
cdef extern from "constants.h":
|
| 16 |
+
const double ABS_TOL
|
| 17 |
+
const double REL_TOL
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
cdef class _LineTypeRenderer:
|
| 21 |
+
cdef double *dashes
|
| 22 |
+
cdef int dash_count
|
| 23 |
+
cdef readonly bint is_solid
|
| 24 |
+
cdef bint is_dash
|
| 25 |
+
cdef int current_dash
|
| 26 |
+
cdef double current_dash_length
|
| 27 |
+
|
| 28 |
+
def __init__(self, dashes: Sequence[float]):
|
| 29 |
+
cdef list _dashes = list(dashes)
|
| 30 |
+
cdef int i
|
| 31 |
+
|
| 32 |
+
self.dash_count = len(_dashes)
|
| 33 |
+
self.dashes = <double *> PyMem_Malloc(self.dash_count * sizeof(double))
|
| 34 |
+
for i in range(self.dash_count):
|
| 35 |
+
self.dashes[i] = _dashes[i]
|
| 36 |
+
|
| 37 |
+
self.is_solid = True
|
| 38 |
+
self.is_dash = False
|
| 39 |
+
self.current_dash = 0
|
| 40 |
+
self.current_dash_length = 0.0
|
| 41 |
+
|
| 42 |
+
if self.dash_count > 1:
|
| 43 |
+
self.is_solid = False
|
| 44 |
+
self.current_dash_length = self.dashes[0]
|
| 45 |
+
self.is_dash = True
|
| 46 |
+
|
| 47 |
+
def __dealloc__(self):
|
| 48 |
+
PyMem_Free(self.dashes)
|
| 49 |
+
|
| 50 |
+
def line_segment(self, start: UVec, end: UVec) -> Iterator[LineSegment]:
|
| 51 |
+
cdef Vec3 v3_start = Vec3(start)
|
| 52 |
+
cdef Vec3 v3_end = Vec3(end)
|
| 53 |
+
cdef Vec3 segment_vec, segment_dir
|
| 54 |
+
cdef double segment_length, dash_length
|
| 55 |
+
cdef list dashes = []
|
| 56 |
+
|
| 57 |
+
if self.is_solid or v3_isclose(v3_start, v3_end, REL_TOL, ABS_TOL):
|
| 58 |
+
yield v3_start, v3_end
|
| 59 |
+
return
|
| 60 |
+
|
| 61 |
+
segment_vec = v3_sub(v3_end, v3_start)
|
| 62 |
+
segment_length = v3_magnitude(segment_vec)
|
| 63 |
+
with cython.cdivision:
|
| 64 |
+
segment_dir = v3_mul(segment_vec, 1.0 / segment_length) # normalize
|
| 65 |
+
|
| 66 |
+
self._render_dashes(segment_length, dashes)
|
| 67 |
+
for dash_length in dashes:
|
| 68 |
+
v3_end = v3_add(v3_start, v3_mul(segment_dir, abs(dash_length)))
|
| 69 |
+
if dash_length > 0:
|
| 70 |
+
yield v3_start, v3_end
|
| 71 |
+
v3_start = v3_end
|
| 72 |
+
|
| 73 |
+
cdef _render_dashes(self, double length, list dashes):
|
| 74 |
+
if length <= self.current_dash_length:
|
| 75 |
+
self.current_dash_length -= length
|
| 76 |
+
dashes.append(length if self.is_dash else -length)
|
| 77 |
+
if self.current_dash_length < ABS_TOL:
|
| 78 |
+
self._cycle_dashes()
|
| 79 |
+
else:
|
| 80 |
+
# Avoid deep recursions!
|
| 81 |
+
while length > self.current_dash_length:
|
| 82 |
+
length -= self.current_dash_length
|
| 83 |
+
self._render_dashes(self.current_dash_length, dashes)
|
| 84 |
+
if length > 0.0:
|
| 85 |
+
self._render_dashes(length, dashes)
|
| 86 |
+
|
| 87 |
+
cdef _cycle_dashes(self):
|
| 88 |
+
with cython.cdivision:
|
| 89 |
+
self.current_dash = (self.current_dash + 1) % self.dash_count
|
| 90 |
+
self.current_dash_length = self.dashes[self.current_dash]
|
| 91 |
+
self.is_dash = not self.is_dash
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/mapbox_earcut.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/mapbox_earcut.pyx
ADDED
|
@@ -0,0 +1,835 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Source: https://github.com/mapbox/earcut
|
| 3 |
+
# License: ISC License (MIT compatible)
|
| 4 |
+
#
|
| 5 |
+
# Copyright (c) 2016, Mapbox
|
| 6 |
+
#
|
| 7 |
+
# Permission to use, copy, modify, and/or distribute this software for any purpose
|
| 8 |
+
# with or without fee is hereby granted, provided that the above copyright notice
|
| 9 |
+
# and this permission notice appear in all copies.
|
| 10 |
+
#
|
| 11 |
+
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
| 12 |
+
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
| 13 |
+
# FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
| 14 |
+
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
| 15 |
+
# OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
| 16 |
+
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
| 17 |
+
# THIS SOFTWARE.
|
| 18 |
+
#
|
| 19 |
+
# Cython implementation of module ezdxf.math._mapbox_earcut.py
|
| 20 |
+
# Copyright (c) 2022, Manfred Moitzi
|
| 21 |
+
# License: MIT License
|
| 22 |
+
# type: ignore
|
| 23 |
+
from libc.math cimport fmin, fmax, fabs, INFINITY
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cdef class Node:
|
| 27 |
+
cdef:
|
| 28 |
+
int i
|
| 29 |
+
double x
|
| 30 |
+
double y
|
| 31 |
+
int z
|
| 32 |
+
bint steiner
|
| 33 |
+
object point
|
| 34 |
+
Node prev
|
| 35 |
+
Node next
|
| 36 |
+
Node prev_z
|
| 37 |
+
Node next_z
|
| 38 |
+
|
| 39 |
+
def __cinit__(self, int i, object point):
|
| 40 |
+
self.i = i
|
| 41 |
+
self.point = point
|
| 42 |
+
self.x = point.x
|
| 43 |
+
self.y = point.y
|
| 44 |
+
self.z = 0
|
| 45 |
+
self.steiner = False
|
| 46 |
+
self.prev = None
|
| 47 |
+
self.next = None
|
| 48 |
+
self.prev_z = None
|
| 49 |
+
self.next_z = None
|
| 50 |
+
|
| 51 |
+
cdef bint equals(self, Node other):
|
| 52 |
+
return self.x == other.x and self.y == other.y
|
| 53 |
+
|
| 54 |
+
def node_key(Node node):
|
| 55 |
+
return node.x, node.y
|
| 56 |
+
|
| 57 |
+
def earcut(list exterior, list holes):
|
| 58 |
+
"""Implements a modified ear slicing algorithm, optimized by z-order
|
| 59 |
+
curve hashing and extended to handle holes, twisted polygons, degeneracies
|
| 60 |
+
and self-intersections in a way that doesn't guarantee correctness of
|
| 61 |
+
triangulation, but attempts to always produce acceptable results for
|
| 62 |
+
practical data.
|
| 63 |
+
|
| 64 |
+
Source: https://github.com/mapbox/earcut
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
exterior: outer path as list of points as objects which provide a
|
| 68 |
+
`x`- and a `y`-attribute
|
| 69 |
+
holes: list of holes, each hole is list of points, a hole with
|
| 70 |
+
a single points is a Steiner point
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
Returns a list of triangles, each triangle is a tuple of three points,
|
| 74 |
+
the output points are the same objects as the input points.
|
| 75 |
+
|
| 76 |
+
"""
|
| 77 |
+
cdef:
|
| 78 |
+
Node outer_node
|
| 79 |
+
list triangles = []
|
| 80 |
+
double max_x, max_y, x, y
|
| 81 |
+
double min_x = 0.0
|
| 82 |
+
double min_y = 0.0
|
| 83 |
+
double inv_size = 0.0
|
| 84 |
+
|
| 85 |
+
if not exterior:
|
| 86 |
+
return triangles
|
| 87 |
+
|
| 88 |
+
outer_node = linked_list(exterior, 0, ccw=True)
|
| 89 |
+
if outer_node is None or outer_node.next is outer_node.prev:
|
| 90 |
+
return triangles
|
| 91 |
+
|
| 92 |
+
if holes:
|
| 93 |
+
outer_node = eliminate_holes(holes, len(exterior), outer_node)
|
| 94 |
+
|
| 95 |
+
# if the shape is not too simple, we'll use z-order curve hash later
|
| 96 |
+
# calculate polygon bbox
|
| 97 |
+
if len(exterior) > 80:
|
| 98 |
+
min_x = max_x = exterior[0].x
|
| 99 |
+
min_y = max_y = exterior[0].y
|
| 100 |
+
for point in exterior:
|
| 101 |
+
x = point.x
|
| 102 |
+
y = point.y
|
| 103 |
+
min_x = fmin(min_x, x)
|
| 104 |
+
min_y = fmin(min_y, y)
|
| 105 |
+
max_x = fmax(max_x, x)
|
| 106 |
+
max_y = fmax(max_y, y)
|
| 107 |
+
|
| 108 |
+
# min_x, min_y and inv_size are later used to transform coords into
|
| 109 |
+
# integers for z-order calculation
|
| 110 |
+
inv_size = fmax(max_x - min_x, max_y - min_y)
|
| 111 |
+
inv_size = 32767 / inv_size if inv_size != 0 else 0
|
| 112 |
+
|
| 113 |
+
earcut_linked(outer_node, triangles, min_x, min_y, inv_size, 0)
|
| 114 |
+
return triangles
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
cdef Node linked_list(list points, int start, bint ccw):
|
| 118 |
+
"""Create a circular doubly linked list from polygon points in the specified
|
| 119 |
+
winding order
|
| 120 |
+
"""
|
| 121 |
+
cdef:
|
| 122 |
+
Node last = None
|
| 123 |
+
int end
|
| 124 |
+
|
| 125 |
+
if ccw is (signed_area(points) < 0):
|
| 126 |
+
for point in points:
|
| 127 |
+
last = insert_node(start, point, last)
|
| 128 |
+
start += 1
|
| 129 |
+
else:
|
| 130 |
+
end = start + len(points)
|
| 131 |
+
for point in reversed(points):
|
| 132 |
+
last = insert_node(end, point, last)
|
| 133 |
+
end -= 1
|
| 134 |
+
|
| 135 |
+
# open polygon: where the 1st vertex is not coincident with the last vertex
|
| 136 |
+
if last and last.equals(last.next):
|
| 137 |
+
remove_node(last)
|
| 138 |
+
last = last.next
|
| 139 |
+
return last
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
cdef double signed_area(list points):
|
| 143 |
+
cdef:
|
| 144 |
+
double s = 0.0
|
| 145 |
+
double point_x, prev_x, point_y, prev_y
|
| 146 |
+
if not len(points):
|
| 147 |
+
return s
|
| 148 |
+
prev = points[-1]
|
| 149 |
+
prev_x = prev.x
|
| 150 |
+
prev_y = prev.y
|
| 151 |
+
for point in points:
|
| 152 |
+
point_x = point.x
|
| 153 |
+
point_y = point.y
|
| 154 |
+
s += (point_x - prev_x) * (point_y + prev_y)
|
| 155 |
+
prev_x = point_x
|
| 156 |
+
prev_y = point_y
|
| 157 |
+
# s < 0 is counter-clockwise
|
| 158 |
+
# s > 0 is clockwise
|
| 159 |
+
return s
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
cdef double area(Node p, Node q, Node r):
|
| 163 |
+
"""Returns signed area of a triangle"""
|
| 164 |
+
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
cdef bint is_valid_diagonal(Node a, Node b):
|
| 168 |
+
"""Check if a diagonal between two polygon nodes is valid (lies in polygon
|
| 169 |
+
interior)
|
| 170 |
+
"""
|
| 171 |
+
return (
|
| 172 |
+
a.next.i != b.i
|
| 173 |
+
and a.prev.i != b.i
|
| 174 |
+
and not intersects_polygon(a, b) # doesn't intersect other edges
|
| 175 |
+
and (
|
| 176 |
+
locally_inside(a, b)
|
| 177 |
+
and locally_inside(b, a)
|
| 178 |
+
and middle_inside(a, b)
|
| 179 |
+
and (
|
| 180 |
+
area(a.prev, a, b.prev) or area(a, b.prev, b)
|
| 181 |
+
) # does not create opposite-facing sectors
|
| 182 |
+
or a.equals(b)
|
| 183 |
+
and area(a.prev, a, a.next) > 0
|
| 184 |
+
and area(b.prev, b, b.next) > 0
|
| 185 |
+
) # special zero-length case
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
cdef bint intersects_polygon(Node a, Node b):
|
| 190 |
+
"""Check if a polygon diagonal intersects any polygon segments"""
|
| 191 |
+
cdef Node p = a
|
| 192 |
+
while True:
|
| 193 |
+
if (
|
| 194 |
+
p.i != a.i
|
| 195 |
+
and p.next.i != a.i
|
| 196 |
+
and p.i != b.i
|
| 197 |
+
and p.next.i != b.i
|
| 198 |
+
and intersects(p, p.next, a, b)
|
| 199 |
+
):
|
| 200 |
+
return True
|
| 201 |
+
p = p.next
|
| 202 |
+
if p is a:
|
| 203 |
+
break
|
| 204 |
+
return False
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
cdef int sign(double num):
|
| 208 |
+
if num < 0.0:
|
| 209 |
+
return -1
|
| 210 |
+
if num > 0.0:
|
| 211 |
+
return 1
|
| 212 |
+
return 0
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
cdef bint on_segment(p: Node, q: Node, r: Node):
|
| 216 |
+
return fmax(p.x, r.x) >= q.x >= fmin(p.x, r.x) and fmax(
|
| 217 |
+
p.y, r.y
|
| 218 |
+
) >= q.y >= fmin(p.y, r.y)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
cdef bint intersects(Node p1, Node q1, Node p2, Node q2):
|
| 222 |
+
"""check if two segments intersect"""
|
| 223 |
+
cdef:
|
| 224 |
+
int o1 = sign(area(p1, q1, p2))
|
| 225 |
+
int o2 = sign(area(p1, q1, q2))
|
| 226 |
+
int o3 = sign(area(p2, q2, p1))
|
| 227 |
+
int o4 = sign(area(p2, q2, q1))
|
| 228 |
+
|
| 229 |
+
if o1 != o2 and o3 != o4:
|
| 230 |
+
return True # general case
|
| 231 |
+
|
| 232 |
+
if o1 == 0 and on_segment(p1, p2, q1):
|
| 233 |
+
return True # p1, q1 and p2 are collinear and p2 lies on p1q1
|
| 234 |
+
if o2 == 0 and on_segment(p1, q2, q1):
|
| 235 |
+
return True # p1, q1 and q2 are collinear and q2 lies on p1q1
|
| 236 |
+
if o3 == 0 and on_segment(p2, p1, q2):
|
| 237 |
+
return True # p2, q2 and p1 are collinear and p1 lies on p2q2
|
| 238 |
+
if o4 == 0 and on_segment(p2, q1, q2):
|
| 239 |
+
return True # p2, q2 and q1 are collinear and q1 lies on p2q2
|
| 240 |
+
return False
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
cdef Node insert_node(int i, point, Node last):
|
| 244 |
+
"""create a node and optionally link it with previous one (in a circular
|
| 245 |
+
doubly linked list)
|
| 246 |
+
"""
|
| 247 |
+
cdef Node p = Node(i, point)
|
| 248 |
+
|
| 249 |
+
if last is None:
|
| 250 |
+
p.prev = p
|
| 251 |
+
p.next = p
|
| 252 |
+
else:
|
| 253 |
+
p.next = last.next
|
| 254 |
+
p.prev = last
|
| 255 |
+
last.next.prev = p
|
| 256 |
+
last.next = p
|
| 257 |
+
return p
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
cdef remove_node(Node p):
|
| 261 |
+
p.next.prev = p.prev
|
| 262 |
+
p.prev.next = p.next
|
| 263 |
+
|
| 264 |
+
if p.prev_z is not None:
|
| 265 |
+
p.prev_z.next_z = p.next_z
|
| 266 |
+
if p.next_z is not None:
|
| 267 |
+
p.next_z.prev_z = p.prev_z
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
cdef Node eliminate_holes(list holes, int start, Node outer_node):
|
| 271 |
+
"""link every hole into the outer loop, producing a single-ring polygon
|
| 272 |
+
without holes
|
| 273 |
+
"""
|
| 274 |
+
cdef:
|
| 275 |
+
list queue = []
|
| 276 |
+
list hole
|
| 277 |
+
for hole in holes:
|
| 278 |
+
if len(hole) < 1: # skip empty holes
|
| 279 |
+
continue
|
| 280 |
+
# hole vertices in clockwise order
|
| 281 |
+
_list = linked_list(hole, start, ccw=False)
|
| 282 |
+
if _list is _list.next:
|
| 283 |
+
_list.steiner = True
|
| 284 |
+
start += len(hole)
|
| 285 |
+
queue.append(get_leftmost(_list))
|
| 286 |
+
queue.sort(key=node_key)
|
| 287 |
+
|
| 288 |
+
# process holes from left to right
|
| 289 |
+
for hole_ in queue:
|
| 290 |
+
outer_node = eliminate_hole(hole_, outer_node)
|
| 291 |
+
return outer_node
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
cdef Node eliminate_hole(Node hole, Node outer_node):
|
| 295 |
+
"""Find a bridge between vertices that connects hole with an outer ring and
|
| 296 |
+
link it
|
| 297 |
+
"""
|
| 298 |
+
cdef:
|
| 299 |
+
Node bridge = find_hole_bridge(hole, outer_node)
|
| 300 |
+
Node bridge_reverse
|
| 301 |
+
|
| 302 |
+
if bridge is None:
|
| 303 |
+
return outer_node
|
| 304 |
+
|
| 305 |
+
bridge_reverse = split_polygon(bridge, hole)
|
| 306 |
+
|
| 307 |
+
# filter collinear points around the cuts
|
| 308 |
+
filter_points(bridge_reverse, bridge_reverse.next)
|
| 309 |
+
return filter_points(bridge, bridge.next)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
cdef Node filter_points(Node start, Node end = None):
|
| 313 |
+
"""eliminate colinear or duplicate points"""
|
| 314 |
+
cdef:
|
| 315 |
+
Node p
|
| 316 |
+
bint again
|
| 317 |
+
|
| 318 |
+
if start is None:
|
| 319 |
+
return start
|
| 320 |
+
if end is None:
|
| 321 |
+
end = start
|
| 322 |
+
|
| 323 |
+
p = start
|
| 324 |
+
while True:
|
| 325 |
+
again = False
|
| 326 |
+
if not p.steiner and (
|
| 327 |
+
p.equals(p.next) or area(p.prev, p, p.next) == 0
|
| 328 |
+
):
|
| 329 |
+
remove_node(p)
|
| 330 |
+
p = end = p.prev
|
| 331 |
+
if p is p.next:
|
| 332 |
+
break
|
| 333 |
+
again = True
|
| 334 |
+
else:
|
| 335 |
+
p = p.next
|
| 336 |
+
if not (again or p is not end):
|
| 337 |
+
break
|
| 338 |
+
return end
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# main ear slicing loop which triangulates a polygon (given as a linked list)
|
| 342 |
+
cdef earcut_linked(
|
| 343 |
+
Node ear,
|
| 344 |
+
list triangles,
|
| 345 |
+
double min_x,
|
| 346 |
+
double min_y,
|
| 347 |
+
double inv_size,
|
| 348 |
+
int pass_,
|
| 349 |
+
):
|
| 350 |
+
cdef:
|
| 351 |
+
Node stop, prev, next
|
| 352 |
+
bint _is_ear
|
| 353 |
+
|
| 354 |
+
if ear is None:
|
| 355 |
+
return
|
| 356 |
+
|
| 357 |
+
# interlink polygon nodes in z-order
|
| 358 |
+
if not pass_ and inv_size:
|
| 359 |
+
index_curve(ear, min_x, min_y, inv_size)
|
| 360 |
+
|
| 361 |
+
stop = ear
|
| 362 |
+
|
| 363 |
+
# iterate through ears, slicing them one by one
|
| 364 |
+
while ear.prev is not ear.next:
|
| 365 |
+
prev = ear.prev
|
| 366 |
+
next = ear.next
|
| 367 |
+
|
| 368 |
+
_is_ear = (
|
| 369 |
+
is_ear_hashed(ear, min_x, min_y, inv_size)
|
| 370 |
+
if inv_size
|
| 371 |
+
else is_ear(ear)
|
| 372 |
+
)
|
| 373 |
+
if _is_ear:
|
| 374 |
+
# cut off the triangle
|
| 375 |
+
triangles.append((prev.point, ear.point, next.point))
|
| 376 |
+
remove_node(ear)
|
| 377 |
+
|
| 378 |
+
# skipping the next vertex leads to less sliver triangles
|
| 379 |
+
ear = next.next
|
| 380 |
+
stop = next.next
|
| 381 |
+
continue
|
| 382 |
+
|
| 383 |
+
ear = next
|
| 384 |
+
|
| 385 |
+
# if we looped through the whole remaining polygon and can't find any more ears
|
| 386 |
+
if ear is stop:
|
| 387 |
+
# try filtering points and slicing again
|
| 388 |
+
if not pass_:
|
| 389 |
+
earcut_linked(
|
| 390 |
+
filter_points(ear),
|
| 391 |
+
triangles,
|
| 392 |
+
min_x,
|
| 393 |
+
min_y,
|
| 394 |
+
inv_size,
|
| 395 |
+
1,
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
# if this didn't work, try curing all small self-intersections locally
|
| 399 |
+
elif pass_ == 1:
|
| 400 |
+
ear = cure_local_intersections(filter_points(ear), triangles)
|
| 401 |
+
earcut_linked(ear, triangles, min_x, min_y, inv_size, 2)
|
| 402 |
+
|
| 403 |
+
# as a last resort, try splitting the remaining polygon into two
|
| 404 |
+
elif pass_ == 2:
|
| 405 |
+
split_ear_cut(ear, triangles, min_x, min_y, inv_size)
|
| 406 |
+
break
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
cdef bint is_ear(Node ear):
|
| 410 |
+
"""check whether a polygon node forms a valid ear with adjacent nodes"""
|
| 411 |
+
cdef:
|
| 412 |
+
Node a = ear.prev
|
| 413 |
+
Node b = ear
|
| 414 |
+
Node c = ear.next
|
| 415 |
+
Node p
|
| 416 |
+
double x0, x1, y0, y1
|
| 417 |
+
|
| 418 |
+
if area(a, b, c) >= 0:
|
| 419 |
+
return False # reflex, can't be an ear
|
| 420 |
+
|
| 421 |
+
# now make sure we don't have other points inside the potential ear
|
| 422 |
+
# triangle bbox
|
| 423 |
+
x0 = fmin(a.x, fmin(b.x, c.x))
|
| 424 |
+
x1 = fmax(a.x, fmax(b.x, c.x))
|
| 425 |
+
y0 = fmin(a.y, fmin(b.y, c.y))
|
| 426 |
+
y1 = fmax(a.y, fmax(b.y, c.y))
|
| 427 |
+
p = c.next
|
| 428 |
+
|
| 429 |
+
while p is not a:
|
| 430 |
+
if (
|
| 431 |
+
x0 <= p.x <= x1
|
| 432 |
+
and y0 <= p.y <= y1
|
| 433 |
+
and point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y)
|
| 434 |
+
and area(p.prev, p, p.next) >= 0
|
| 435 |
+
):
|
| 436 |
+
return False
|
| 437 |
+
p = p.next
|
| 438 |
+
|
| 439 |
+
return True
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
cdef bint is_ear_hashed(Node ear, double min_x, double min_y, double inv_size):
|
| 443 |
+
cdef:
|
| 444 |
+
Node a = ear.prev
|
| 445 |
+
Node b = ear
|
| 446 |
+
Node c = ear.next
|
| 447 |
+
double x0, x1, y0, y1, min_z, max_z
|
| 448 |
+
Node p, n
|
| 449 |
+
|
| 450 |
+
if area(a, b, c) >= 0:
|
| 451 |
+
return False # reflex, can't be an ear
|
| 452 |
+
|
| 453 |
+
# triangle bbox
|
| 454 |
+
x0 = fmin(a.x, fmin(b.x, c.x))
|
| 455 |
+
x1 = fmax(a.x, fmax(b.x, c.x))
|
| 456 |
+
y0 = fmin(a.y, fmin(b.y, c.y))
|
| 457 |
+
y1 = fmax(a.y, fmax(b.y, c.y))
|
| 458 |
+
|
| 459 |
+
# z-order range for the current triangle bbox;
|
| 460 |
+
min_z = z_order(x0, y0, min_x, min_y, inv_size)
|
| 461 |
+
max_z = z_order(x1, y1, min_x, min_y, inv_size)
|
| 462 |
+
|
| 463 |
+
p = ear.prev_z
|
| 464 |
+
n = ear.next_z
|
| 465 |
+
|
| 466 |
+
# look for points inside the triangle in both directions
|
| 467 |
+
while p and p.z >= min_z and n and n.z <= max_z:
|
| 468 |
+
if (
|
| 469 |
+
x0 <= p.x <= x1
|
| 470 |
+
and y0 <= p.y <= y1
|
| 471 |
+
and p is not a
|
| 472 |
+
and p is not c
|
| 473 |
+
and point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y)
|
| 474 |
+
and area(p.prev, p, p.next) >= 0
|
| 475 |
+
):
|
| 476 |
+
return False
|
| 477 |
+
p = p.prev_z
|
| 478 |
+
|
| 479 |
+
if (
|
| 480 |
+
x0 <= n.x <= x1
|
| 481 |
+
and y0 <= n.y <= y1
|
| 482 |
+
and n is not a
|
| 483 |
+
and n is not c
|
| 484 |
+
and point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y)
|
| 485 |
+
and area(n.prev, n, n.next) >= 0
|
| 486 |
+
):
|
| 487 |
+
return False
|
| 488 |
+
n = n.next_z
|
| 489 |
+
|
| 490 |
+
# look for remaining points in decreasing z-order
|
| 491 |
+
while p and p.z >= min_z:
|
| 492 |
+
if (
|
| 493 |
+
x0 <= p.x <= x1
|
| 494 |
+
and y0 <= p.y <= y1
|
| 495 |
+
and p is not a
|
| 496 |
+
and p is not c
|
| 497 |
+
and point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y)
|
| 498 |
+
and area(p.prev, p, p.next) >= 0
|
| 499 |
+
):
|
| 500 |
+
return False
|
| 501 |
+
p = p.prev_z
|
| 502 |
+
|
| 503 |
+
# look for remaining points in increasing z-order
|
| 504 |
+
while n and n.z <= max_z:
|
| 505 |
+
if (
|
| 506 |
+
x0 <= n.x <= x1
|
| 507 |
+
and y0 <= n.y <= y1
|
| 508 |
+
and n is not a
|
| 509 |
+
and n is not c
|
| 510 |
+
and point_in_triangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y)
|
| 511 |
+
and area(n.prev, n, n.next) >= 0
|
| 512 |
+
):
|
| 513 |
+
return False
|
| 514 |
+
n = n.next_z
|
| 515 |
+
return True
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
cdef Node get_leftmost(Node start):
|
| 519 |
+
"""Find the leftmost node of a polygon ring"""
|
| 520 |
+
cdef:
|
| 521 |
+
Node p = start
|
| 522 |
+
Node leftmost = start
|
| 523 |
+
|
| 524 |
+
while True:
|
| 525 |
+
if p.x < leftmost.x or (p.x == leftmost.x and p.y < leftmost.y):
|
| 526 |
+
leftmost = p
|
| 527 |
+
p = p.next
|
| 528 |
+
if p is start:
|
| 529 |
+
break
|
| 530 |
+
return leftmost
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
cdef bint point_in_triangle(
|
| 534 |
+
double ax,
|
| 535 |
+
double ay,
|
| 536 |
+
double bx,
|
| 537 |
+
double by_,
|
| 538 |
+
double cx,
|
| 539 |
+
double cy,
|
| 540 |
+
double px,
|
| 541 |
+
double py,
|
| 542 |
+
):
|
| 543 |
+
"""Check if a point lies within a convex triangle"""
|
| 544 |
+
return (
|
| 545 |
+
(cx - px) * (ay - py) >= (ax - px) * (cy - py)
|
| 546 |
+
and (ax - px) * (by_ - py) >= (bx - px) * (ay - py)
|
| 547 |
+
and (bx - px) * (cy - py) >= (cx - px) * (by_ - py)
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
cdef bint sector_contains_sector(Node m, Node p):
|
| 552 |
+
"""Whether sector in vertex m contains sector in vertex p in the same
|
| 553 |
+
coordinates.
|
| 554 |
+
"""
|
| 555 |
+
return area(m.prev, m, p.prev) < 0 and area(p.next, m, m.next) < 0
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
cdef index_curve(Node start, double min_x, double min_y, double inv_size):
|
| 559 |
+
"""Interlink polygon nodes in z-order"""
|
| 560 |
+
cdef Node p = start
|
| 561 |
+
while True:
|
| 562 |
+
if p.z == 0:
|
| 563 |
+
p.z = z_order(p.x, p.y, min_x, min_y, inv_size)
|
| 564 |
+
p.prev_z = p.prev
|
| 565 |
+
p.next_z = p.next
|
| 566 |
+
p = p.next
|
| 567 |
+
if p is start:
|
| 568 |
+
break
|
| 569 |
+
|
| 570 |
+
p.prev_z.next_z = None
|
| 571 |
+
p.prev_z = None
|
| 572 |
+
|
| 573 |
+
sort_linked(p)
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
cdef int z_order(
|
| 577 |
+
double x0, double y0, double min_x, double min_y, double inv_size
|
| 578 |
+
):
|
| 579 |
+
"""Z-order of a point given coords and inverse of the longer side of data
|
| 580 |
+
bbox.
|
| 581 |
+
"""
|
| 582 |
+
# coords are transformed into non-negative 15-bit integer range
|
| 583 |
+
cdef:
|
| 584 |
+
int x = int((x0 - min_x) * inv_size)
|
| 585 |
+
int y = int ((y0 - min_y) * inv_size)
|
| 586 |
+
|
| 587 |
+
x = (x | (x << 8)) & 0x00FF00FF
|
| 588 |
+
x = (x | (x << 4)) & 0x0F0F0F0F
|
| 589 |
+
x = (x | (x << 2)) & 0x33333333
|
| 590 |
+
x = (x | (x << 1)) & 0x55555555
|
| 591 |
+
|
| 592 |
+
y = (y | (y << 8)) & 0x00FF00FF
|
| 593 |
+
y = (y | (y << 4)) & 0x0F0F0F0F
|
| 594 |
+
y = (y | (y << 2)) & 0x33333333
|
| 595 |
+
y = (y | (y << 1)) & 0x55555555
|
| 596 |
+
|
| 597 |
+
return x | (y << 1)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
# Simon Tatham's linked list merge sort algorithm
|
| 601 |
+
# http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
|
| 602 |
+
cdef Node sort_linked(Node head):
|
| 603 |
+
cdef:
|
| 604 |
+
int in_size = 1
|
| 605 |
+
int num_merges, p_size, q_size, i
|
| 606 |
+
Node tail, p, q, e
|
| 607 |
+
|
| 608 |
+
while True:
|
| 609 |
+
p = head
|
| 610 |
+
head = None
|
| 611 |
+
tail = None
|
| 612 |
+
num_merges = 0
|
| 613 |
+
while p:
|
| 614 |
+
num_merges += 1
|
| 615 |
+
q = p
|
| 616 |
+
p_size = 0
|
| 617 |
+
for i in range(in_size):
|
| 618 |
+
p_size += 1
|
| 619 |
+
q = q.next_z
|
| 620 |
+
if not q:
|
| 621 |
+
break
|
| 622 |
+
q_size = in_size
|
| 623 |
+
while p_size > 0 or (q_size > 0 and q):
|
| 624 |
+
if p_size != 0 and (q_size == 0 or not q or p.z <= q.z):
|
| 625 |
+
e = p
|
| 626 |
+
p = p.next_z
|
| 627 |
+
p_size -= 1
|
| 628 |
+
else:
|
| 629 |
+
e = q
|
| 630 |
+
q = q.next_z
|
| 631 |
+
q_size -= 1
|
| 632 |
+
|
| 633 |
+
if tail:
|
| 634 |
+
tail.next_z = e
|
| 635 |
+
else:
|
| 636 |
+
head = e
|
| 637 |
+
e.prev_z = tail
|
| 638 |
+
tail = e
|
| 639 |
+
p = q
|
| 640 |
+
tail.next_z = None
|
| 641 |
+
in_size *= 2
|
| 642 |
+
if num_merges <= 1:
|
| 643 |
+
break
|
| 644 |
+
return head
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
cdef Node split_polygon(Node a, Node b):
|
| 648 |
+
"""Link two polygon vertices with a bridge.
|
| 649 |
+
|
| 650 |
+
If the vertices belong to the same ring, it splits polygon into two.
|
| 651 |
+
If one belongs to the outer ring and another to a hole, it merges it into a
|
| 652 |
+
single ring.
|
| 653 |
+
"""
|
| 654 |
+
cdef :
|
| 655 |
+
Node a2 = Node(a.i, a.point)
|
| 656 |
+
Node b2 = Node(b.i, b.point)
|
| 657 |
+
Node an = a.next
|
| 658 |
+
Node bp = b.prev
|
| 659 |
+
|
| 660 |
+
a.next = b
|
| 661 |
+
b.prev = a
|
| 662 |
+
|
| 663 |
+
a2.next = an
|
| 664 |
+
an.prev = a2
|
| 665 |
+
|
| 666 |
+
b2.next = a2
|
| 667 |
+
a2.prev = b2
|
| 668 |
+
|
| 669 |
+
bp.next = b2
|
| 670 |
+
b2.prev = bp
|
| 671 |
+
|
| 672 |
+
return b2
|
| 673 |
+
|
| 674 |
+
|
| 675 |
+
# go through all polygon nodes and cure small local self-intersections
|
| 676 |
+
cdef Node cure_local_intersections(Node start, list triangles):
|
| 677 |
+
cdef:
|
| 678 |
+
Node p = start
|
| 679 |
+
Node a, b
|
| 680 |
+
while True:
|
| 681 |
+
a = p.prev
|
| 682 |
+
b = p.next.next
|
| 683 |
+
|
| 684 |
+
if (
|
| 685 |
+
not a.equals(b)
|
| 686 |
+
and intersects(a, p, p.next, b)
|
| 687 |
+
and locally_inside(a, b)
|
| 688 |
+
and locally_inside(b, a)
|
| 689 |
+
):
|
| 690 |
+
triangles.append((a.point, p.point, b.point))
|
| 691 |
+
# remove two nodes involved
|
| 692 |
+
remove_node(p)
|
| 693 |
+
remove_node(p.next)
|
| 694 |
+
p = start = b
|
| 695 |
+
|
| 696 |
+
p = p.next
|
| 697 |
+
if p is start:
|
| 698 |
+
break
|
| 699 |
+
return filter_points(p)
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
cdef split_ear_cut(
|
| 703 |
+
Node start,
|
| 704 |
+
list triangles,
|
| 705 |
+
double min_x,
|
| 706 |
+
double min_y,
|
| 707 |
+
double inv_size,
|
| 708 |
+
):
|
| 709 |
+
"""Try splitting polygon into two and triangulate them independently"""
|
| 710 |
+
# look for a valid diagonal that divides the polygon into two
|
| 711 |
+
cdef:
|
| 712 |
+
Node a = start
|
| 713 |
+
Node b, c
|
| 714 |
+
|
| 715 |
+
while True:
|
| 716 |
+
b = a.next.next
|
| 717 |
+
while b is not a.prev:
|
| 718 |
+
if a.i != b.i and is_valid_diagonal(a, b):
|
| 719 |
+
# split the polygon in two by the diagonal
|
| 720 |
+
c = split_polygon(a, b)
|
| 721 |
+
|
| 722 |
+
# filter colinear points around the cuts
|
| 723 |
+
a = filter_points(a, a.next)
|
| 724 |
+
c = filter_points(c, c.next)
|
| 725 |
+
|
| 726 |
+
# run earcut on each half
|
| 727 |
+
earcut_linked(a, triangles, min_x, min_y, inv_size, 0)
|
| 728 |
+
earcut_linked(c, triangles, min_x, min_y, inv_size, 0)
|
| 729 |
+
return
|
| 730 |
+
b = b.next
|
| 731 |
+
a = a.next
|
| 732 |
+
if a is start:
|
| 733 |
+
break
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
# David Eberly's algorithm for finding a bridge between hole and outer polygon
|
| 737 |
+
cdef Node find_hole_bridge(Node hole, Node outer_node):
|
| 738 |
+
cdef:
|
| 739 |
+
Node p = outer_node
|
| 740 |
+
Node m = None
|
| 741 |
+
Node stop
|
| 742 |
+
double hx = hole.x
|
| 743 |
+
double hy = hole.y
|
| 744 |
+
double qx = -INFINITY
|
| 745 |
+
double mx, my, tan_min, tan
|
| 746 |
+
|
| 747 |
+
# find a segment intersected by a ray from the hole's leftmost point to the left;
|
| 748 |
+
# segment's endpoint with lesser x will be potential connection point
|
| 749 |
+
while True:
|
| 750 |
+
if p.y >= hy >= p.next.y != p.y:
|
| 751 |
+
x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y)
|
| 752 |
+
if hx >= x > qx:
|
| 753 |
+
qx = x
|
| 754 |
+
m = p if p.x < p.next.x else p.next
|
| 755 |
+
if x == hx:
|
| 756 |
+
# hole touches outer segment; pick leftmost endpoint
|
| 757 |
+
return m
|
| 758 |
+
p = p.next
|
| 759 |
+
if p is outer_node:
|
| 760 |
+
break
|
| 761 |
+
|
| 762 |
+
if m is None:
|
| 763 |
+
return None
|
| 764 |
+
|
| 765 |
+
# look for points inside the triangle of hole point, segment intersection and endpoint;
|
| 766 |
+
# if there are no points found, we have a valid connection;
|
| 767 |
+
# otherwise choose the point of the minimum angle with the ray as connection point
|
| 768 |
+
stop = m
|
| 769 |
+
mx = m.x
|
| 770 |
+
my = m.y
|
| 771 |
+
tan_min = INFINITY
|
| 772 |
+
p = m
|
| 773 |
+
|
| 774 |
+
while True:
|
| 775 |
+
if (
|
| 776 |
+
hx >= p.x >= mx
|
| 777 |
+
and hx != p.x
|
| 778 |
+
and point_in_triangle(
|
| 779 |
+
hx if hy < my else qx,
|
| 780 |
+
hy,
|
| 781 |
+
mx,
|
| 782 |
+
my,
|
| 783 |
+
qx if hy < my else hx,
|
| 784 |
+
hy,
|
| 785 |
+
p.x,
|
| 786 |
+
p.y,
|
| 787 |
+
)
|
| 788 |
+
):
|
| 789 |
+
tan = fabs(hy - p.y) / (hx - p.x) # tangential
|
| 790 |
+
if locally_inside(p, hole) and (
|
| 791 |
+
tan < tan_min
|
| 792 |
+
or (
|
| 793 |
+
tan == tan_min
|
| 794 |
+
and (
|
| 795 |
+
p.x > m.x
|
| 796 |
+
or (p.x == m.x and sector_contains_sector(m, p))
|
| 797 |
+
)
|
| 798 |
+
)
|
| 799 |
+
):
|
| 800 |
+
m = p
|
| 801 |
+
tan_min = tan
|
| 802 |
+
p = p.next
|
| 803 |
+
if p is stop:
|
| 804 |
+
break
|
| 805 |
+
return m
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
cdef bint locally_inside(Node a, Node b):
|
| 809 |
+
"""Check if a polygon diagonal is locally inside the polygon"""
|
| 810 |
+
return (
|
| 811 |
+
area(a, b, a.next) >= 0 and area(a, a.prev, b) >= 0
|
| 812 |
+
if area(a.prev, a, a.next) < 0
|
| 813 |
+
else area(a, b, a.prev) < 0 or area(a, a.next, b) < 0
|
| 814 |
+
)
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
cdef bint middle_inside(Node a, Node b):
|
| 818 |
+
"""Check if the middle point of a polygon diagonal is inside the polygon"""
|
| 819 |
+
cdef:
|
| 820 |
+
Node p = a
|
| 821 |
+
bint inside = False
|
| 822 |
+
double px = (a.x + b.x) / 2
|
| 823 |
+
double py = (a.y + b.y) / 2
|
| 824 |
+
|
| 825 |
+
while True:
|
| 826 |
+
if (
|
| 827 |
+
((p.y > py) != (p.next.y > py))
|
| 828 |
+
and p.next.y != p.y
|
| 829 |
+
and (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)
|
| 830 |
+
):
|
| 831 |
+
inside = not inside
|
| 832 |
+
p = p.next
|
| 833 |
+
if p is a:
|
| 834 |
+
break
|
| 835 |
+
return inside
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.pxd
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2020-2023, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from .vector cimport Vec3
|
| 5 |
+
|
| 6 |
+
cdef class Matrix44:
|
| 7 |
+
cdef double m[16]
|
| 8 |
+
cdef Vec3 get_ux(self: Matrix44)
|
| 9 |
+
cdef Vec3 get_uy(self: Matrix44)
|
| 10 |
+
cdef Vec3 get_uz(self: Matrix44)
|
| 11 |
+
|
| 12 |
+
cdef inline swap(double *a, double *b):
|
| 13 |
+
cdef double tmp = a[0]
|
| 14 |
+
a[0] = b[0]
|
| 15 |
+
b[0] = tmp
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/matrix44.pyx
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2020-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing import Sequence, Iterable, Tuple, TYPE_CHECKING, Iterator
|
| 5 |
+
from itertools import chain
|
| 6 |
+
import math
|
| 7 |
+
import numpy as np
|
| 8 |
+
import cython
|
| 9 |
+
|
| 10 |
+
from .vector cimport (
|
| 11 |
+
Vec2, Vec3, v3_normalize, v3_isclose, v3_cross, v3_dot,
|
| 12 |
+
)
|
| 13 |
+
from .vector import X_AXIS, Y_AXIS, Z_AXIS, NULLVEC
|
| 14 |
+
|
| 15 |
+
from libc.math cimport fabs, sin, cos, tan
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from ezdxf.math import UVec
|
| 19 |
+
|
| 20 |
+
cdef extern from "constants.h":
|
| 21 |
+
const double ABS_TOL
|
| 22 |
+
const double REL_TOL
|
| 23 |
+
|
| 24 |
+
cdef double[16] IDENTITY = [
|
| 25 |
+
1.0, 0.0, 0.0, 0.0,
|
| 26 |
+
0.0, 1.0, 0.0, 0.0,
|
| 27 |
+
0.0, 0.0, 1.0, 0.0,
|
| 28 |
+
0.0, 0.0, 0.0, 1.0
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
cdef void set_floats(double *m, object values) except *:
|
| 32 |
+
cdef int i = 0
|
| 33 |
+
for v in values:
|
| 34 |
+
if i < 16: # Do not write beyond array bounds
|
| 35 |
+
m[i] = v
|
| 36 |
+
i += 1
|
| 37 |
+
if i != 16:
|
| 38 |
+
raise ValueError("invalid argument count")
|
| 39 |
+
|
| 40 |
+
cdef class Matrix44:
|
| 41 |
+
def __cinit__(self, *args):
|
| 42 |
+
cdef int nargs = len(args)
|
| 43 |
+
if nargs == 0: # default constructor Matrix44(): fastest setup
|
| 44 |
+
self.m = IDENTITY # memcopy!
|
| 45 |
+
elif nargs == 1: # 16 numbers: slow setup
|
| 46 |
+
set_floats(self.m, args[0])
|
| 47 |
+
elif nargs == 4: # 4 rows of 4 numbers: slowest setup
|
| 48 |
+
set_floats(self.m, chain(*args))
|
| 49 |
+
else:
|
| 50 |
+
raise ValueError("invalid argument count: 4 row vectors or "
|
| 51 |
+
"iterable of 16 numbers")
|
| 52 |
+
|
| 53 |
+
def __reduce__(self):
|
| 54 |
+
return Matrix44, (tuple(self),)
|
| 55 |
+
|
| 56 |
+
def __getitem__(self, tuple index) -> float:
|
| 57 |
+
cdef int row = index[0]
|
| 58 |
+
cdef int col = index[1]
|
| 59 |
+
cdef int i = row * 4 + col
|
| 60 |
+
|
| 61 |
+
if 0 <= i < 16 and 0 <= col < 4:
|
| 62 |
+
return self.m[i]
|
| 63 |
+
else:
|
| 64 |
+
raise IndexError(f'index out of range: {index}')
|
| 65 |
+
|
| 66 |
+
def __setitem__(self, tuple index, double value):
|
| 67 |
+
cdef int row = index[0]
|
| 68 |
+
cdef int col = index[1]
|
| 69 |
+
cdef int i = row * 4 + col
|
| 70 |
+
|
| 71 |
+
if 0 <= i < 16 and 0 <= col < 4:
|
| 72 |
+
self.m[i] = value
|
| 73 |
+
else:
|
| 74 |
+
raise IndexError(f'index out of range: {index}')
|
| 75 |
+
|
| 76 |
+
def __iter__(self):
|
| 77 |
+
cdef int i
|
| 78 |
+
for i in range(16):
|
| 79 |
+
yield self.m[i]
|
| 80 |
+
|
| 81 |
+
def __repr__(self) -> str:
|
| 82 |
+
def format_row(row):
|
| 83 |
+
return "(%s)" % ", ".join(str(value) for value in row)
|
| 84 |
+
|
| 85 |
+
return "Matrix44(%s)" % \
|
| 86 |
+
", ".join(format_row(row) for row in self.rows())
|
| 87 |
+
|
| 88 |
+
def get_2d_transformation(self) -> Tuple[float, ...]:
|
| 89 |
+
cdef double *m = self.m
|
| 90 |
+
return m[0], m[1], 0.0, m[4], m[5], 0.0, m[12], m[13], 1.0
|
| 91 |
+
|
| 92 |
+
@staticmethod
|
| 93 |
+
def from_2d_transformation(components: Sequence[float]) -> Matrix44:
|
| 94 |
+
if len(components) != 6:
|
| 95 |
+
raise ValueError(
|
| 96 |
+
"First 2 columns of a 3x3 matrix required: m11, m12, m21, m22, m31, m32"
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
m44 = Matrix44()
|
| 100 |
+
m44.m[0] = components[0]
|
| 101 |
+
m44.m[1] = components[1]
|
| 102 |
+
m44.m[4] = components[2]
|
| 103 |
+
m44.m[5] = components[3]
|
| 104 |
+
m44.m[12] = components[4]
|
| 105 |
+
m44.m[13] = components[5]
|
| 106 |
+
return m44
|
| 107 |
+
|
| 108 |
+
def get_row(self, int row) -> Tuple[float, ...]:
|
| 109 |
+
cdef int index = row * 4
|
| 110 |
+
if 0 <= index < 13:
|
| 111 |
+
return self.m[index], self.m[index + 1], self.m[index + 2], self.m[
|
| 112 |
+
index + 3]
|
| 113 |
+
else:
|
| 114 |
+
raise IndexError(f'invalid row index: {row}')
|
| 115 |
+
|
| 116 |
+
def set_row(self, int row, values: Sequence[float]) -> None:
|
| 117 |
+
cdef Py_ssize_t count = len(values)
|
| 118 |
+
cdef Py_ssize_t start = row * 4
|
| 119 |
+
cdef Py_ssize_t i
|
| 120 |
+
if 0 <= row < 4:
|
| 121 |
+
if count > 4:
|
| 122 |
+
count = 4
|
| 123 |
+
for i in range(count):
|
| 124 |
+
self.m[start + i] = values[i]
|
| 125 |
+
else:
|
| 126 |
+
raise IndexError(f'invalid row index: {row}')
|
| 127 |
+
|
| 128 |
+
def get_col(self, int col) -> Tuple[float, ...]:
|
| 129 |
+
if 0 <= col < 4:
|
| 130 |
+
return self.m[col], self.m[col + 4], \
|
| 131 |
+
self.m[col + 8], self.m[col + 12]
|
| 132 |
+
else:
|
| 133 |
+
raise IndexError(f'invalid col index: {col}')
|
| 134 |
+
|
| 135 |
+
def set_col(self, int col, values: Sequence[float]):
|
| 136 |
+
cdef Py_ssize_t count = len(values)
|
| 137 |
+
cdef Py_ssize_t i
|
| 138 |
+
if 0 <= col < 4:
|
| 139 |
+
if count > 4:
|
| 140 |
+
count = 4
|
| 141 |
+
for i in range(count):
|
| 142 |
+
self.m[col + i * 4] = values[i]
|
| 143 |
+
else:
|
| 144 |
+
raise IndexError(f'invalid col index: {col}')
|
| 145 |
+
|
| 146 |
+
def rows(self) -> Iterator[Tuple[float, ...]]:
|
| 147 |
+
return (self.get_row(index) for index in (0, 1, 2, 3))
|
| 148 |
+
|
| 149 |
+
def columns(self) -> Iterator[Tuple[float, ...]]:
|
| 150 |
+
return (self.get_col(index) for index in (0, 1, 2, 3))
|
| 151 |
+
|
| 152 |
+
def copy(self) -> Matrix44:
|
| 153 |
+
cdef Matrix44 _copy = Matrix44()
|
| 154 |
+
_copy.m = self.m
|
| 155 |
+
return _copy
|
| 156 |
+
|
| 157 |
+
__copy__ = copy
|
| 158 |
+
|
| 159 |
+
@property
|
| 160 |
+
def origin(self) -> Vec3:
|
| 161 |
+
cdef Vec3 v = Vec3()
|
| 162 |
+
v.x = self.m[12]
|
| 163 |
+
v.y = self.m[13]
|
| 164 |
+
v.z = self.m[14]
|
| 165 |
+
return v
|
| 166 |
+
|
| 167 |
+
@origin.setter
|
| 168 |
+
def origin(self, v: UVec) -> None:
|
| 169 |
+
cdef Vec3 origin = Vec3(v)
|
| 170 |
+
self.m[12] = origin.x
|
| 171 |
+
self.m[13] = origin.y
|
| 172 |
+
self.m[14] = origin.z
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def ux(self) -> Vec3:
|
| 176 |
+
return self.get_ux()
|
| 177 |
+
|
| 178 |
+
cdef Vec3 get_ux(self):
|
| 179 |
+
cdef Vec3 v = Vec3()
|
| 180 |
+
v.x = self.m[0]
|
| 181 |
+
v.y = self.m[1]
|
| 182 |
+
v.z = self.m[2]
|
| 183 |
+
return v
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def uy(self) -> Vec3:
|
| 187 |
+
return self.get_uy()
|
| 188 |
+
|
| 189 |
+
cdef Vec3 get_uy(self):
|
| 190 |
+
cdef Vec3 v = Vec3()
|
| 191 |
+
v.x = self.m[4]
|
| 192 |
+
v.y = self.m[5]
|
| 193 |
+
v.z = self.m[6]
|
| 194 |
+
return v
|
| 195 |
+
|
| 196 |
+
@property
|
| 197 |
+
def uz(self) -> Vec3:
|
| 198 |
+
return self.get_uz()
|
| 199 |
+
|
| 200 |
+
cdef Vec3 get_uz(self):
|
| 201 |
+
cdef Vec3 v = Vec3()
|
| 202 |
+
v.x = self.m[8]
|
| 203 |
+
v.y = self.m[9]
|
| 204 |
+
v.z = self.m[10]
|
| 205 |
+
return v
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
def is_cartesian(self) -> bool:
|
| 209 |
+
cdef Vec3 x_axis = v3_cross(self.get_uy(), self.get_uz())
|
| 210 |
+
return v3_isclose(x_axis, self.get_ux(), REL_TOL, ABS_TOL)
|
| 211 |
+
|
| 212 |
+
@property
|
| 213 |
+
def is_orthogonal(self) -> bool:
|
| 214 |
+
cdef Vec3 ux = v3_normalize(self.get_ux(), 1.0)
|
| 215 |
+
cdef Vec3 uy = v3_normalize(self.get_uy(), 1.0)
|
| 216 |
+
cdef Vec3 uz = v3_normalize(self.get_uz(), 1.0)
|
| 217 |
+
return fabs(v3_dot(ux, uy)) < 1e-9 and \
|
| 218 |
+
fabs(v3_dot(ux, uz)) < 1e-9 and \
|
| 219 |
+
fabs(v3_dot(uy, uz)) < 1e-9
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def scale(double sx, sy = None, sz = None) -> Matrix44:
|
| 223 |
+
cdef Matrix44 mat = Matrix44()
|
| 224 |
+
mat.m[0] = sx
|
| 225 |
+
mat.m[5] = sx if sy is None else sy
|
| 226 |
+
mat.m[10] = sx if sz is None else sz
|
| 227 |
+
return mat
|
| 228 |
+
|
| 229 |
+
@staticmethod
|
| 230 |
+
def translate(double dx, double dy, double dz) -> Matrix44:
|
| 231 |
+
cdef Matrix44 mat = Matrix44()
|
| 232 |
+
mat.m[12] = dx
|
| 233 |
+
mat.m[13] = dy
|
| 234 |
+
mat.m[14] = dz
|
| 235 |
+
return mat
|
| 236 |
+
|
| 237 |
+
@staticmethod
|
| 238 |
+
def x_rotate(double angle) -> Matrix44:
|
| 239 |
+
cdef Matrix44 mat = Matrix44()
|
| 240 |
+
cdef double cos_a = cos(angle)
|
| 241 |
+
cdef double sin_a = sin(angle)
|
| 242 |
+
mat.m[5] = cos_a
|
| 243 |
+
mat.m[6] = sin_a
|
| 244 |
+
mat.m[9] = -sin_a
|
| 245 |
+
mat.m[10] = cos_a
|
| 246 |
+
return mat
|
| 247 |
+
|
| 248 |
+
@staticmethod
|
| 249 |
+
def y_rotate(double angle) -> Matrix44:
|
| 250 |
+
cdef Matrix44 mat = Matrix44()
|
| 251 |
+
cdef double cos_a = cos(angle)
|
| 252 |
+
cdef double sin_a = sin(angle)
|
| 253 |
+
mat.m[0] = cos_a
|
| 254 |
+
mat.m[2] = -sin_a
|
| 255 |
+
mat.m[8] = sin_a
|
| 256 |
+
mat.m[10] = cos_a
|
| 257 |
+
return mat
|
| 258 |
+
|
| 259 |
+
@staticmethod
|
| 260 |
+
def z_rotate(double angle) -> Matrix44:
|
| 261 |
+
cdef Matrix44 mat = Matrix44()
|
| 262 |
+
cdef double cos_a = cos(angle)
|
| 263 |
+
cdef double sin_a = sin(angle)
|
| 264 |
+
mat.m[0] = cos_a
|
| 265 |
+
mat.m[1] = sin_a
|
| 266 |
+
mat.m[4] = -sin_a
|
| 267 |
+
mat.m[5] = cos_a
|
| 268 |
+
return mat
|
| 269 |
+
|
| 270 |
+
@staticmethod
|
| 271 |
+
def axis_rotate(axis: UVec, double angle) -> Matrix44:
|
| 272 |
+
cdef Matrix44 mat = Matrix44()
|
| 273 |
+
cdef double cos_a = cos(angle)
|
| 274 |
+
cdef double sin_a = sin(angle)
|
| 275 |
+
cdef double one_m_cos = 1.0 - cos_a
|
| 276 |
+
cdef Vec3 _axis = Vec3(axis).normalize()
|
| 277 |
+
cdef double x = _axis.x
|
| 278 |
+
cdef double y = _axis.y
|
| 279 |
+
cdef double z = _axis.z
|
| 280 |
+
|
| 281 |
+
mat.m[0] = x * x * one_m_cos + cos_a
|
| 282 |
+
mat.m[1] = y * x * one_m_cos + z * sin_a
|
| 283 |
+
mat.m[2] = x * z * one_m_cos - y * sin_a
|
| 284 |
+
|
| 285 |
+
mat.m[4] = x * y * one_m_cos - z * sin_a
|
| 286 |
+
mat.m[5] = y * y * one_m_cos + cos_a
|
| 287 |
+
mat.m[6] = y * z * one_m_cos + x * sin_a
|
| 288 |
+
|
| 289 |
+
mat.m[8] = x * z * one_m_cos + y * sin_a
|
| 290 |
+
mat.m[9] = y * z * one_m_cos - x * sin_a
|
| 291 |
+
mat.m[10] = z * z * one_m_cos + cos_a
|
| 292 |
+
|
| 293 |
+
return mat
|
| 294 |
+
|
| 295 |
+
@staticmethod
|
| 296 |
+
def xyz_rotate(double angle_x, double angle_y,
|
| 297 |
+
double angle_z) -> Matrix44:
|
| 298 |
+
cdef Matrix44 mat = Matrix44()
|
| 299 |
+
cdef double cx = cos(angle_x)
|
| 300 |
+
cdef double sx = sin(angle_x)
|
| 301 |
+
cdef double cy = cos(angle_y)
|
| 302 |
+
cdef double sy = sin(angle_y)
|
| 303 |
+
cdef double cz = cos(angle_z)
|
| 304 |
+
cdef double sz = sin(angle_z)
|
| 305 |
+
cdef double sxsy = sx * sy
|
| 306 |
+
cdef double cxsy = cx * sy
|
| 307 |
+
|
| 308 |
+
mat.m[0] = cy * cz
|
| 309 |
+
mat.m[1] = sxsy * cz + cx * sz
|
| 310 |
+
mat.m[2] = -cxsy * cz + sx * sz
|
| 311 |
+
mat.m[4] = -cy * sz
|
| 312 |
+
mat.m[5] = -sxsy * sz + cx * cz
|
| 313 |
+
mat.m[6] = cxsy * sz + sx * cz
|
| 314 |
+
mat.m[8] = sy
|
| 315 |
+
mat.m[9] = -sx * cy
|
| 316 |
+
mat.m[10] = cx * cy
|
| 317 |
+
return mat
|
| 318 |
+
|
| 319 |
+
@staticmethod
|
| 320 |
+
def shear_xy(double angle_x = 0, double angle_y = 0) -> Matrix44:
|
| 321 |
+
cdef Matrix44 mat = Matrix44()
|
| 322 |
+
cdef double tx = tan(angle_x)
|
| 323 |
+
cdef double ty = tan(angle_y)
|
| 324 |
+
mat.m[1] = ty
|
| 325 |
+
mat.m[4] = tx
|
| 326 |
+
return mat
|
| 327 |
+
|
| 328 |
+
@staticmethod
|
| 329 |
+
def perspective_projection(double left, double right, double top,
|
| 330 |
+
double bottom, double near,
|
| 331 |
+
double far) -> Matrix44:
|
| 332 |
+
cdef Matrix44 mat = Matrix44()
|
| 333 |
+
mat.m[0] = (2. * near) / (right - left)
|
| 334 |
+
mat.m[5] = (2. * near) / (top - bottom)
|
| 335 |
+
mat.m[8] = (right + left) / (right - left)
|
| 336 |
+
mat.m[9] = (top + bottom) / (top - bottom)
|
| 337 |
+
mat.m[10] = -((far + near) / (far - near))
|
| 338 |
+
mat.m[11] = -1
|
| 339 |
+
mat.m[14] = -((2. * far * near) / (far - near))
|
| 340 |
+
return mat
|
| 341 |
+
|
| 342 |
+
@staticmethod
|
| 343 |
+
def perspective_projection_fov(fov: float, aspect: float, near: float,
|
| 344 |
+
far: float) -> Matrix44:
|
| 345 |
+
vrange = near * math.tan(fov / 2.)
|
| 346 |
+
left = -vrange * aspect
|
| 347 |
+
right = vrange * aspect
|
| 348 |
+
bottom = -vrange
|
| 349 |
+
top = vrange
|
| 350 |
+
return Matrix44.perspective_projection(left, right, bottom, top, near,
|
| 351 |
+
far)
|
| 352 |
+
|
| 353 |
+
@staticmethod
|
| 354 |
+
def chain(*matrices: Matrix44) -> Matrix44:
|
| 355 |
+
cdef Matrix44 transformation = Matrix44()
|
| 356 |
+
for matrix in matrices:
|
| 357 |
+
transformation *= matrix
|
| 358 |
+
return transformation
|
| 359 |
+
|
| 360 |
+
def __imul__(self, Matrix44 other) -> Matrix44:
|
| 361 |
+
cdef double[16] m1 = self.m
|
| 362 |
+
cdef double *m2 = other.m
|
| 363 |
+
|
| 364 |
+
self.m[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + \
|
| 365 |
+
m1[3] * m2[12]
|
| 366 |
+
self.m[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + \
|
| 367 |
+
m1[3] * m2[13]
|
| 368 |
+
self.m[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + \
|
| 369 |
+
m1[3] * m2[14]
|
| 370 |
+
self.m[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + \
|
| 371 |
+
m1[3] * m2[15]
|
| 372 |
+
|
| 373 |
+
self.m[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + \
|
| 374 |
+
m1[7] * m2[12]
|
| 375 |
+
self.m[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + \
|
| 376 |
+
m1[7] * m2[13]
|
| 377 |
+
self.m[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + \
|
| 378 |
+
m1[7] * m2[14]
|
| 379 |
+
self.m[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + \
|
| 380 |
+
m1[7] * m2[15]
|
| 381 |
+
|
| 382 |
+
self.m[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + \
|
| 383 |
+
m1[11] * m2[12]
|
| 384 |
+
self.m[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + \
|
| 385 |
+
m1[11] * m2[13]
|
| 386 |
+
self.m[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + \
|
| 387 |
+
m1[11] * m2[14]
|
| 388 |
+
self.m[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + \
|
| 389 |
+
m1[11] * m2[15]
|
| 390 |
+
|
| 391 |
+
self.m[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + \
|
| 392 |
+
m1[15] * m2[12]
|
| 393 |
+
self.m[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + \
|
| 394 |
+
m1[15] * m2[13]
|
| 395 |
+
self.m[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + \
|
| 396 |
+
m1[15] * m2[14]
|
| 397 |
+
self.m[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + \
|
| 398 |
+
m1[15] * m2[15]
|
| 399 |
+
return self
|
| 400 |
+
|
| 401 |
+
def __mul__(self, Matrix44 other) -> Matrix44:
|
| 402 |
+
cdef Matrix44 res_matrix = self.copy()
|
| 403 |
+
return res_matrix.__imul__(other)
|
| 404 |
+
|
| 405 |
+
# __matmul__ = __mul__ does not work!
|
| 406 |
+
|
| 407 |
+
def __matmul__(self, Matrix44 other) -> Matrix44:
|
| 408 |
+
cdef Matrix44 res_matrix = self.copy()
|
| 409 |
+
return res_matrix.__imul__(other)
|
| 410 |
+
|
| 411 |
+
def transpose(self) -> None:
|
| 412 |
+
swap(&self.m[1], &self.m[4])
|
| 413 |
+
swap(&self.m[2], &self.m[8])
|
| 414 |
+
swap(&self.m[3], &self.m[12])
|
| 415 |
+
swap(&self.m[6], &self.m[9])
|
| 416 |
+
swap(&self.m[7], &self.m[13])
|
| 417 |
+
swap(&self.m[11], &self.m[14])
|
| 418 |
+
|
| 419 |
+
def determinant(self) -> float:
|
| 420 |
+
cdef double *m = self.m
|
| 421 |
+
return m[0] * m[5] * m[10] * m[15] - m[0] * m[5] * m[11] * m[14] + \
|
| 422 |
+
m[0] * m[6] * m[11] * m[13] - m[0] * m[6] * m[9] * m[15] + \
|
| 423 |
+
m[0] * m[7] * m[9] * m[14] - m[0] * m[7] * m[10] * m[13] - \
|
| 424 |
+
m[1] * m[6] * m[11] * m[12] + m[1] * m[6] * m[8] * m[15] - \
|
| 425 |
+
m[1] * m[7] * m[8] * m[14] + m[1] * m[7] * m[10] * m[12] - \
|
| 426 |
+
m[1] * m[4] * m[10] * m[15] + m[1] * m[4] * m[11] * m[14] + \
|
| 427 |
+
m[2] * m[7] * m[8] * m[13] - m[2] * m[7] * m[9] * m[12] + \
|
| 428 |
+
m[2] * m[4] * m[9] * m[15] - m[2] * m[4] * m[11] * m[13] + \
|
| 429 |
+
m[2] * m[5] * m[11] * m[12] - m[2] * m[5] * m[8] * m[15] - \
|
| 430 |
+
m[3] * m[4] * m[9] * m[14] + m[3] * m[4] * m[10] * m[13] - \
|
| 431 |
+
m[3] * m[5] * m[10] * m[12] + m[3] * m[5] * m[8] * m[14] - \
|
| 432 |
+
m[3] * m[6] * m[8] * m[13] + m[3] * m[6] * m[9] * m[12]
|
| 433 |
+
|
| 434 |
+
def inverse(self) -> None:
|
| 435 |
+
cdef double[16] m = self.m # memcopy
|
| 436 |
+
cdef double det = self.determinant()
|
| 437 |
+
cdef double f = 1. / det
|
| 438 |
+
self.m[0] = (m[6] * m[11] * m[13] - m[7] * m[10] * m[13] + m[7] * m[9] *
|
| 439 |
+
m[14] - m[5] * m[11] * m[14] - m[6] * m[9] * m[15] + m[5] *
|
| 440 |
+
m[10] * m[15]) * f
|
| 441 |
+
|
| 442 |
+
self.m[1] = (m[3] * m[10] * m[13] - m[2] * m[11] * m[13] - m[3] * m[9] *
|
| 443 |
+
m[14] + m[1] * m[11] * m[14] + m[2] * m[9] * m[15] -
|
| 444 |
+
m[1] * m[10] * m[15]) * f
|
| 445 |
+
self.m[2] = (m[2] * m[7] * m[13] - m[3] * m[6] * m[13] + m[3] * m[5] *
|
| 446 |
+
m[14] - m[1] * m[7] * m[14] - m[2] * m[5] * m[15] +
|
| 447 |
+
m[1] * m[6] * m[15]) * f
|
| 448 |
+
|
| 449 |
+
self.m[3] = (m[3] * m[6] * m[9] - m[2] * m[7] * m[9] - m[3] * m[5] *
|
| 450 |
+
m[10] + m[1] * m[7] * m[10] + m[2] * m[5] * m[11] - m[1] *
|
| 451 |
+
m[6] * m[11]) * f
|
| 452 |
+
|
| 453 |
+
self.m[4] = (m[7] * m[10] * m[12] - m[6] * m[11] * m[12] - m[7] * m[8] *
|
| 454 |
+
m[14] + m[4] * m[11] * m[14] + m[6] * m[8] * m[15] -
|
| 455 |
+
m[4] * m[10] * m[15]) * f
|
| 456 |
+
|
| 457 |
+
self.m[5] = (m[2] * m[11] * m[12] - m[3] * m[10] * m[12] + m[3] * m[8] *
|
| 458 |
+
m[14] - m[0] * m[11] * m[14] - m[2] * m[8] * m[15] +
|
| 459 |
+
m[0] * m[10] * m[15]) * f
|
| 460 |
+
|
| 461 |
+
self.m[6] = (m[3] * m[6] * m[12] - m[2] * m[7] * m[12] - m[3] * m[4] *
|
| 462 |
+
m[14] + m[0] * m[7] * m[14] + m[2] * m[4] * m[15] -
|
| 463 |
+
m[0] * m[6] * m[15]) * f
|
| 464 |
+
|
| 465 |
+
self.m[7] = (m[2] * m[7] * m[8] - m[3] * m[6] * m[8] + m[3] * m[4] *
|
| 466 |
+
m[10] - m[0] * m[7] * m[10] - m[2] * m[4] * m[11] +
|
| 467 |
+
m[0] * m[6] * m[11]) * f
|
| 468 |
+
|
| 469 |
+
self.m[8] = (m[5] * m[11] * m[12] - m[7] * m[9] * m[12] + m[7] * m[8] *
|
| 470 |
+
m[13] - m[4] * m[11] * m[13] - m[5] * m[8] * m[15] +
|
| 471 |
+
m[4] * m[9] * m[15]) * f
|
| 472 |
+
|
| 473 |
+
self.m[9] = (m[3] * m[9] * m[12] - m[1] * m[11] * m[12] - m[3] *
|
| 474 |
+
m[8] * m[13] + m[0] * m[11] * m[13] + m[1] * m[8] *
|
| 475 |
+
m[15] - m[0] * m[9] * m[15]) * f
|
| 476 |
+
|
| 477 |
+
self.m[10] = (m[1] * m[7] * m[12] - m[3] * m[5] * m[12] + m[3] *
|
| 478 |
+
m[4] * m[13] - m[0] * m[7] * m[13] - m[1] * m[4] *
|
| 479 |
+
m[15] + m[0] * m[5] * m[15]) * f
|
| 480 |
+
|
| 481 |
+
self.m[11] = (m[3] * m[5] * m[8] - m[1] * m[7] * m[8] - m[3] * m[4] *
|
| 482 |
+
m[9] + m[0] * m[7] * m[9] + m[1] * m[4] * m[11] -
|
| 483 |
+
m[0] * m[5] * m[11]) * f
|
| 484 |
+
|
| 485 |
+
self.m[12] = (m[6] * m[9] * m[12] - m[5] * m[10] * m[12] - m[6] *
|
| 486 |
+
m[8] * m[13] + m[4] * m[10] * m[13] + m[5] * m[8] *
|
| 487 |
+
m[14] - m[4] * m[9] * m[14]) * f
|
| 488 |
+
|
| 489 |
+
self.m[13] = (m[1] * m[10] * m[12] - m[2] * m[9] * m[12] + m[2] *
|
| 490 |
+
m[8] * m[13] - m[0] * m[10] * m[13] - m[1] * m[8] *
|
| 491 |
+
m[14] + m[0] * m[9] * m[14]) * f
|
| 492 |
+
|
| 493 |
+
self.m[14] = (m[2] * m[5] * m[12] - m[1] * m[6] * m[12] - m[2] *
|
| 494 |
+
m[4] * m[13] + m[0] * m[6] * m[13] + m[1] * m[4] *
|
| 495 |
+
m[14] - m[0] * m[5] * m[14]) * f
|
| 496 |
+
|
| 497 |
+
self.m[15] = (m[1] * m[6] * m[8] - m[2] * m[5] * m[8] + m[2] * m[4] *
|
| 498 |
+
m[9] - m[0] * m[6] * m[9] - m[1] * m[4] * m[10] +
|
| 499 |
+
m[0] * m[5] * m[10]) * f
|
| 500 |
+
|
| 501 |
+
@staticmethod
|
| 502 |
+
def ucs(ux=X_AXIS, uy=Y_AXIS, uz=Z_AXIS, origin=NULLVEC) -> Matrix44:
|
| 503 |
+
cdef Matrix44 mat = Matrix44()
|
| 504 |
+
cdef Vec3 _ux = Vec3(ux)
|
| 505 |
+
cdef Vec3 _uy = Vec3(uy)
|
| 506 |
+
cdef Vec3 _uz = Vec3(uz)
|
| 507 |
+
cdef Vec3 _origin = Vec3(origin)
|
| 508 |
+
|
| 509 |
+
mat.m[0] = _ux.x
|
| 510 |
+
mat.m[1] = _ux.y
|
| 511 |
+
mat.m[2] = _ux.z
|
| 512 |
+
|
| 513 |
+
mat.m[4] = _uy.x
|
| 514 |
+
mat.m[5] = _uy.y
|
| 515 |
+
mat.m[6] = _uy.z
|
| 516 |
+
|
| 517 |
+
mat.m[8] = _uz.x
|
| 518 |
+
mat.m[9] = _uz.y
|
| 519 |
+
mat.m[10] = _uz.z
|
| 520 |
+
|
| 521 |
+
mat.m[12] = _origin.x
|
| 522 |
+
mat.m[13] = _origin.y
|
| 523 |
+
mat.m[14] = _origin.z
|
| 524 |
+
|
| 525 |
+
return mat
|
| 526 |
+
|
| 527 |
+
def transform(self, vector: UVec) -> Vec3:
|
| 528 |
+
cdef Vec3 res = Vec3(vector)
|
| 529 |
+
cdef double x = res.x
|
| 530 |
+
cdef double y = res.y
|
| 531 |
+
cdef double z = res.z
|
| 532 |
+
cdef double *m = self.m
|
| 533 |
+
|
| 534 |
+
res.x = x * m[0] + y * m[4] + z * m[8] + m[12]
|
| 535 |
+
res.y = x * m[1] + y * m[5] + z * m[9] + m[13]
|
| 536 |
+
res.z = x * m[2] + y * m[6] + z * m[10] + m[14]
|
| 537 |
+
return res
|
| 538 |
+
|
| 539 |
+
def transform_direction(self, vector: UVec, normalize=False) -> Vec3:
|
| 540 |
+
cdef Vec3 res = Vec3(vector)
|
| 541 |
+
cdef double x = res.x
|
| 542 |
+
cdef double y = res.y
|
| 543 |
+
cdef double z = res.z
|
| 544 |
+
cdef double *m = self.m
|
| 545 |
+
|
| 546 |
+
res.x = x * m[0] + y * m[4] + z * m[8]
|
| 547 |
+
res.y = x * m[1] + y * m[5] + z * m[9]
|
| 548 |
+
res.z = x * m[2] + y * m[6] + z * m[10]
|
| 549 |
+
if normalize:
|
| 550 |
+
return v3_normalize(res, 1.0)
|
| 551 |
+
else:
|
| 552 |
+
return res
|
| 553 |
+
|
| 554 |
+
ocs_to_wcs = transform_direction
|
| 555 |
+
|
| 556 |
+
def transform_vertices(self, vectors: Iterable[UVec]) -> Iterator[Vec3]:
|
| 557 |
+
cdef double *m = self.m
|
| 558 |
+
cdef Vec3 res
|
| 559 |
+
cdef double x, y, z
|
| 560 |
+
|
| 561 |
+
for vector in vectors:
|
| 562 |
+
res = Vec3(vector)
|
| 563 |
+
x = res.x
|
| 564 |
+
y = res.y
|
| 565 |
+
z = res.z
|
| 566 |
+
|
| 567 |
+
res.x = x * m[0] + y * m[4] + z * m[8] + m[12]
|
| 568 |
+
res.y = x * m[1] + y * m[5] + z * m[9] + m[13]
|
| 569 |
+
res.z = x * m[2] + y * m[6] + z * m[10] + m[14]
|
| 570 |
+
yield res
|
| 571 |
+
|
| 572 |
+
def fast_2d_transform(self, points: Iterable[UVec]) -> Iterator[Vec2]:
|
| 573 |
+
cdef double m0 = self.m[0]
|
| 574 |
+
cdef double m1 = self.m[1]
|
| 575 |
+
cdef double m4 = self.m[4]
|
| 576 |
+
cdef double m5 = self.m[5]
|
| 577 |
+
cdef double m12 = self.m[12]
|
| 578 |
+
cdef double m13 = self.m[13]
|
| 579 |
+
cdef double x, y
|
| 580 |
+
cdef Vec2 res
|
| 581 |
+
|
| 582 |
+
for pnt in points:
|
| 583 |
+
res = Vec2(pnt)
|
| 584 |
+
x = res.x
|
| 585 |
+
y = res.y
|
| 586 |
+
res.x = x * m0 + y * m4 + m12
|
| 587 |
+
res.y = x * m1 + y * m5 + m13
|
| 588 |
+
yield res
|
| 589 |
+
|
| 590 |
+
def transform_array_inplace(self, array: np.ndarray, ndim: int) -> None:
|
| 591 |
+
"""Transforms a numpy array inplace, the argument `ndim` defines the dimensions
|
| 592 |
+
to transform, this allows 2D/3D transformation on arrays with more columns
|
| 593 |
+
e.g. a polyline array which stores points as (x, y, start_width, end_width,
|
| 594 |
+
bulge) values.
|
| 595 |
+
|
| 596 |
+
"""
|
| 597 |
+
cdef int _ndim = ndim
|
| 598 |
+
if _ndim == 2:
|
| 599 |
+
assert array.shape[1] > 1
|
| 600 |
+
transform_2d_array_inplace(self.m, array, array.shape[0])
|
| 601 |
+
elif _ndim == 3:
|
| 602 |
+
assert array.shape[1] > 2
|
| 603 |
+
transform_3d_array_inplace(self.m, array, array.shape[0])
|
| 604 |
+
else:
|
| 605 |
+
raise ValueError("ndim has to be 2 or 3")
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def transform_directions(
|
| 609 |
+
self, vectors: Iterable[UVec], normalize=False
|
| 610 |
+
) -> Iterator[Vec3]:
|
| 611 |
+
cdef double *m = self.m
|
| 612 |
+
cdef Vec3 res
|
| 613 |
+
cdef double x, y, z
|
| 614 |
+
cdef bint _normalize = normalize
|
| 615 |
+
|
| 616 |
+
for vector in vectors:
|
| 617 |
+
res = Vec3(vector)
|
| 618 |
+
x = res.x
|
| 619 |
+
y = res.y
|
| 620 |
+
z = res.z
|
| 621 |
+
|
| 622 |
+
res.x = x * m[0] + y * m[4] + z * m[8]
|
| 623 |
+
res.y = x * m[1] + y * m[5] + z * m[9]
|
| 624 |
+
res.z = x * m[2] + y * m[6] + z * m[10]
|
| 625 |
+
yield v3_normalize(res, 1.0) if _normalize else res
|
| 626 |
+
|
| 627 |
+
def ucs_vertex_from_wcs(self, wcs: Vec3) -> Vec3:
|
| 628 |
+
return self.ucs_direction_from_wcs(wcs - self.origin)
|
| 629 |
+
|
| 630 |
+
def ucs_direction_from_wcs(self, wcs: UVec) -> Vec3:
|
| 631 |
+
cdef double *m = self.m
|
| 632 |
+
cdef Vec3 res = Vec3(wcs)
|
| 633 |
+
cdef double x = res.x
|
| 634 |
+
cdef double y = res.y
|
| 635 |
+
cdef double z = res.z
|
| 636 |
+
|
| 637 |
+
res.x = x * m[0] + y * m[1] + z * m[2]
|
| 638 |
+
res.y = x * m[4] + y * m[5] + z * m[6]
|
| 639 |
+
res.z = x * m[8] + y * m[9] + z * m[10]
|
| 640 |
+
return res
|
| 641 |
+
|
| 642 |
+
ocs_from_wcs = ucs_direction_from_wcs
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
@cython.boundscheck(False)
|
| 646 |
+
@cython.wraparound(False)
|
| 647 |
+
cdef void transform_2d_array_inplace(double *m, double [:, ::1] array, Py_ssize_t size):
|
| 648 |
+
cdef double m0 = m[0]
|
| 649 |
+
cdef double m1 = m[1]
|
| 650 |
+
cdef double m4 = m[4]
|
| 651 |
+
cdef double m5 = m[5]
|
| 652 |
+
cdef double m12 = m[12]
|
| 653 |
+
cdef double m13 = m[13]
|
| 654 |
+
cdef double x, y
|
| 655 |
+
cdef Py_ssize_t i
|
| 656 |
+
|
| 657 |
+
for i in range(size):
|
| 658 |
+
x = array[i, 0]
|
| 659 |
+
y = array[i, 1]
|
| 660 |
+
array[i, 0] = x * m0 + y * m4 + m12
|
| 661 |
+
array[i, 1] = x * m1 + y * m5 + m13
|
| 662 |
+
|
| 663 |
+
@cython.boundscheck(False)
|
| 664 |
+
@cython.wraparound(False)
|
| 665 |
+
cdef void transform_3d_array_inplace(double *m, double [:, ::1] array, Py_ssize_t size):
|
| 666 |
+
cdef double x, y, z
|
| 667 |
+
cdef Py_ssize_t i
|
| 668 |
+
|
| 669 |
+
for i in range(size):
|
| 670 |
+
x = array[i, 0]
|
| 671 |
+
y = array[i, 1]
|
| 672 |
+
z = array[i, 2]
|
| 673 |
+
|
| 674 |
+
array[i, 0] = x * m[0] + y * m[4] + z * m[8] + m[12]
|
| 675 |
+
array[i, 1] = x * m[1] + y * m[5] + z * m[9] + m[13]
|
| 676 |
+
array[i, 2] = x * m[2] + y * m[6] + z * m[10] + m[14]
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/np_support.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/np_support.pyx
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2023-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
from typing_extensions import TypeAlias
|
| 5 |
+
import numpy as np
|
| 6 |
+
import numpy.typing as npt
|
| 7 |
+
|
| 8 |
+
import cython
|
| 9 |
+
from .vector cimport isclose
|
| 10 |
+
|
| 11 |
+
cdef extern from "constants.h":
|
| 12 |
+
const double ABS_TOL
|
| 13 |
+
const double REL_TOL
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
NDArray: TypeAlias = npt.NDArray[np.float64]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def has_clockwise_orientation(vertices: np.ndarray) -> bool:
|
| 20 |
+
""" Returns True if 2D `vertices` have clockwise orientation. Ignores
|
| 21 |
+
z-axis of all vertices.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
vertices: numpy array
|
| 25 |
+
|
| 26 |
+
Raises:
|
| 27 |
+
ValueError: less than 3 vertices
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
if len(vertices) < 3:
|
| 31 |
+
raise ValueError('At least 3 vertices required.')
|
| 32 |
+
|
| 33 |
+
return _has_clockwise_orientation(vertices, vertices.shape[0])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@cython.boundscheck(False)
|
| 37 |
+
@cython.wraparound(False)
|
| 38 |
+
cdef bint _has_clockwise_orientation(double [:, ::1] vertices, Py_ssize_t size):
|
| 39 |
+
cdef Py_ssize_t index
|
| 40 |
+
cdef Py_ssize_t start
|
| 41 |
+
cdef Py_ssize_t last = size - 1
|
| 42 |
+
cdef double s = 0.0
|
| 43 |
+
cdef double p1x = vertices[0][0]
|
| 44 |
+
cdef double p1y = vertices[0][1]
|
| 45 |
+
cdef double p2x = vertices[last][0]
|
| 46 |
+
cdef double p2y = vertices[last][1]
|
| 47 |
+
|
| 48 |
+
# Using the same tolerance as the Python implementation:
|
| 49 |
+
cdef bint x_is_close = isclose(p1x, p2x, REL_TOL, ABS_TOL)
|
| 50 |
+
cdef bint y_is_close = isclose(p1y, p2y, REL_TOL, ABS_TOL)
|
| 51 |
+
|
| 52 |
+
if x_is_close and y_is_close:
|
| 53 |
+
p1x = vertices[0][0]
|
| 54 |
+
p1y = vertices[0][1]
|
| 55 |
+
start = 1
|
| 56 |
+
else:
|
| 57 |
+
p1x = vertices[last][0]
|
| 58 |
+
p1y = vertices[last][1]
|
| 59 |
+
start = 0
|
| 60 |
+
|
| 61 |
+
for index in range(start, size):
|
| 62 |
+
p2x = vertices[index][0]
|
| 63 |
+
p2y = vertices[index][1]
|
| 64 |
+
s += (p2x - p1x) * (p2y + p1y)
|
| 65 |
+
p1x = p2x
|
| 66 |
+
p1y = p2y
|
| 67 |
+
return s > 0.0
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def lu_decompose(A: NDArray, m1: int, m2: int) -> tuple[NDArray, NDArray, NDArray]:
|
| 71 |
+
upper: np.ndarray = np.array(A, dtype=np.float64)
|
| 72 |
+
n: int = upper.shape[0]
|
| 73 |
+
lower: np.ndarray = np.zeros((n, m1), dtype=np.float64)
|
| 74 |
+
|
| 75 |
+
# Is <np.int_> better to match <int> on all platforms?
|
| 76 |
+
index: np.ndarray = np.zeros((n,), dtype=np.int32)
|
| 77 |
+
_lu_decompose_cext(upper, lower, index, n, m1, m2)
|
| 78 |
+
return upper, lower, index
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@cython.boundscheck(False)
|
| 82 |
+
@cython.wraparound(False)
|
| 83 |
+
cdef _lu_decompose_cext(
|
| 84 |
+
double [:, ::1] upper,
|
| 85 |
+
double [:, ::1] lower,
|
| 86 |
+
int [::1] index,
|
| 87 |
+
int n,
|
| 88 |
+
int m1,
|
| 89 |
+
int m2
|
| 90 |
+
):
|
| 91 |
+
cdef int mm = m1 + m2 + 1
|
| 92 |
+
cdef int l = m1
|
| 93 |
+
cdef int i, j, k
|
| 94 |
+
cdef double dum
|
| 95 |
+
|
| 96 |
+
for i in range(m1):
|
| 97 |
+
for j in range(m1 - i, mm):
|
| 98 |
+
upper[i][j - l] = upper[i][j]
|
| 99 |
+
l -= 1
|
| 100 |
+
for j in range(mm - l - 1, mm):
|
| 101 |
+
upper[i][j] = 0.0
|
| 102 |
+
|
| 103 |
+
l = m1
|
| 104 |
+
for k in range(n):
|
| 105 |
+
dum = upper[k][0]
|
| 106 |
+
i = k
|
| 107 |
+
if l < n:
|
| 108 |
+
l += 1
|
| 109 |
+
for j in range(k + 1, l):
|
| 110 |
+
if abs(upper[j][0]) > abs(dum):
|
| 111 |
+
dum = upper[j][0]
|
| 112 |
+
i = j
|
| 113 |
+
index[k] = i + 1
|
| 114 |
+
if i != k:
|
| 115 |
+
for j in range(mm):
|
| 116 |
+
upper[k][j], upper[i][j] = upper[i][j], upper[k][j]
|
| 117 |
+
|
| 118 |
+
for i in range(k + 1, l):
|
| 119 |
+
dum = upper[i][0] / upper[k][0]
|
| 120 |
+
lower[k][i - k - 1] = dum
|
| 121 |
+
for j in range(1, mm):
|
| 122 |
+
upper[i][j - 1] = upper[i][j] - dum * upper[k][j]
|
| 123 |
+
upper[i][mm - 1] = 0.0
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def solve_vector_banded_matrix(
|
| 127 |
+
x: NDArray,
|
| 128 |
+
upper: NDArray,
|
| 129 |
+
lower: NDArray,
|
| 130 |
+
index: NDArray,
|
| 131 |
+
m1: int,
|
| 132 |
+
m2: int,
|
| 133 |
+
) -> NDArray:
|
| 134 |
+
n: int = upper.shape[0]
|
| 135 |
+
x = np.array(x) # copy x because array x gets modified
|
| 136 |
+
if x.shape[0] != n:
|
| 137 |
+
raise ValueError(
|
| 138 |
+
"Item count of vector <x> has to match the row count of matrix <upper>."
|
| 139 |
+
)
|
| 140 |
+
_solve_vector_banded_matrix_cext(x, upper, lower, index, n, m1, m2)
|
| 141 |
+
return x
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@cython.boundscheck(False)
|
| 145 |
+
@cython.wraparound(False)
|
| 146 |
+
cdef _solve_vector_banded_matrix_cext(
|
| 147 |
+
double [::1] x,
|
| 148 |
+
double [:, ::1] au,
|
| 149 |
+
double [:, ::1] al,
|
| 150 |
+
int [::1] index,
|
| 151 |
+
int n,
|
| 152 |
+
int m1,
|
| 153 |
+
int m2,
|
| 154 |
+
):
|
| 155 |
+
cdef int mm = m1 + m2 + 1
|
| 156 |
+
cdef int l = m1
|
| 157 |
+
cdef int i, j, k
|
| 158 |
+
cdef double dum
|
| 159 |
+
|
| 160 |
+
for k in range(n):
|
| 161 |
+
j = index[k] - 1
|
| 162 |
+
if j != k:
|
| 163 |
+
x[k], x[j] = x[j], x[k]
|
| 164 |
+
if l < n:
|
| 165 |
+
l += 1
|
| 166 |
+
for j in range(k + 1, l):
|
| 167 |
+
x[j] -= al[k][j - k - 1] * x[k]
|
| 168 |
+
|
| 169 |
+
l = 1
|
| 170 |
+
for i in range(n - 1, -1, -1):
|
| 171 |
+
dum = x[i]
|
| 172 |
+
for k in range(1, l):
|
| 173 |
+
dum -= au[i][k] * x[k + i]
|
| 174 |
+
x[i] = dum / au[i][0]
|
| 175 |
+
if l < mm:
|
| 176 |
+
l += 1
|
| 177 |
+
return x
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.c
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.pxd
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# cython: language_level=3
|
| 2 |
+
# Copyright (c) 2020-2024, Manfred Moitzi
|
| 3 |
+
# License: MIT License
|
| 4 |
+
|
| 5 |
+
cdef bint isclose(double a, double b, double rel_tol, double abs_tol)
|
| 6 |
+
cdef double normalize_rad_angle(double a)
|
| 7 |
+
cdef double normalize_deg_angle(double a)
|
| 8 |
+
|
| 9 |
+
cdef class Vec2:
|
| 10 |
+
cdef readonly double x, y
|
| 11 |
+
|
| 12 |
+
# Vec2 C-functions:
|
| 13 |
+
cdef Vec2 v2_add(Vec2 a, Vec2 b)
|
| 14 |
+
cdef Vec2 v2_sub(Vec2 a, Vec2 b)
|
| 15 |
+
cdef Vec2 v2_mul(Vec2 a, double factor)
|
| 16 |
+
cdef Vec2 v2_normalize(Vec2 a, double length)
|
| 17 |
+
cdef double v2_dot(Vec2 a, Vec2 b)
|
| 18 |
+
cdef double v2_det(Vec2 a, Vec2 b)
|
| 19 |
+
cdef double v2_dist(Vec2 a, Vec2 b)
|
| 20 |
+
cdef Vec2 v2_from_angle(double angle, double length)
|
| 21 |
+
cdef double v2_angle_between(Vec2 a, Vec2 b) except -1000
|
| 22 |
+
cdef Vec2 v2_lerp(Vec2 a, Vec2 b, double factor)
|
| 23 |
+
cdef Vec2 v2_ortho(Vec2 a, bint ccw)
|
| 24 |
+
cdef Vec2 v2_project(Vec2 a, Vec2 b)
|
| 25 |
+
cdef bint v2_isclose(Vec2 a, Vec2 b, double rel_tol, double abs_tol)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
cdef class Vec3:
|
| 29 |
+
cdef readonly double x, y, z
|
| 30 |
+
|
| 31 |
+
# Vec3 C-functions:
|
| 32 |
+
cdef Vec3 v3_add(Vec3 a, Vec3 b)
|
| 33 |
+
cdef Vec3 v3_sub(Vec3 a, Vec3 b)
|
| 34 |
+
cdef Vec3 v3_mul(Vec3 a, double factor)
|
| 35 |
+
cdef Vec3 v3_reverse(Vec3 a)
|
| 36 |
+
cdef double v3_dot(Vec3 a, Vec3 b)
|
| 37 |
+
cdef Vec3 v3_cross(Vec3 a, Vec3 b)
|
| 38 |
+
cdef double v3_magnitude_sqr(Vec3 a)
|
| 39 |
+
cdef double v3_magnitude(Vec3 a)
|
| 40 |
+
cdef double v3_dist(Vec3 a, Vec3 b)
|
| 41 |
+
cdef Vec3 v3_from_angle(double angle, double length)
|
| 42 |
+
cdef double v3_angle_between(Vec3 a, Vec3 b) except -1000
|
| 43 |
+
cdef double v3_angle_about(Vec3 a, Vec3 base, Vec3 target)
|
| 44 |
+
cdef Vec3 v3_normalize(Vec3 a, double length)
|
| 45 |
+
cdef Vec3 v3_lerp(Vec3 a, Vec3 b, double factor)
|
| 46 |
+
cdef Vec3 v3_ortho(Vec3 a, bint ccw)
|
| 47 |
+
cdef Vec3 v3_project(Vec3 a, Vec3 b)
|
| 48 |
+
cdef bint v3_isclose(Vec3 a, Vec3 b, double rel_tol, double abs_tol)
|
| 49 |
+
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acc/vector.pyx
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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HECKING, Tuple, Iterator
|
| 6 |
+
from libc.math cimport fabs, sin, cos, M_PI, hypot, atan2, acos, sqrt, fmod
|
| 7 |
+
import random
|
| 8 |
+
|
| 9 |
+
cdef extern from "constants.h":
|
| 10 |
+
const double ABS_TOL
|
| 11 |
+
const double REL_TOL
|
| 12 |
+
const double M_TAU
|
| 13 |
+
|
| 14 |
+
cdef double RAD2DEG = 180.0 / M_PI
|
| 15 |
+
cdef double DEG2RAD = M_PI / 180.0
|
| 16 |
+
|
| 17 |
+
if TYPE_CHECKING:
|
| 18 |
+
from ezdxf.math import AnyVec, UVec
|
| 19 |
+
|
| 20 |
+
cdef bint isclose(double a, double b, double rel_tol, double abs_tol):
|
| 21 |
+
# Has to match the Python implementation!
|
| 22 |
+
cdef double diff = fabs(b - a)
|
| 23 |
+
return diff <= fabs(rel_tol * b) or \
|
| 24 |
+
diff <= fabs(rel_tol * a) or \
|
| 25 |
+
diff <= abs_tol
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
cdef double normalize_rad_angle(double a):
|
| 29 |
+
# Emulate the Python behavior of (a % math.tau)
|
| 30 |
+
cdef double res = fmod(a, M_TAU)
|
| 31 |
+
if res < 0.0:
|
| 32 |
+
res += M_TAU
|
| 33 |
+
return res
|
| 34 |
+
|
| 35 |
+
def _normalize_rad_angle(double angle):
|
| 36 |
+
# just for testing
|
| 37 |
+
return normalize_rad_angle(angle)
|
| 38 |
+
|
| 39 |
+
cdef double normalize_deg_angle(double a):
|
| 40 |
+
# Emulate the Python behavior of (a % 360)
|
| 41 |
+
cdef double res = fmod(a, 360.0)
|
| 42 |
+
if res < 0.0:
|
| 43 |
+
res += 360.0
|
| 44 |
+
return res
|
| 45 |
+
|
| 46 |
+
def _normalize_deg_angle(double angle):
|
| 47 |
+
# just for testing
|
| 48 |
+
return normalize_deg_angle(angle)
|
| 49 |
+
|
| 50 |
+
cdef class Vec2:
|
| 51 |
+
""" Immutable 2D vector.
|
| 52 |
+
|
| 53 |
+
Init:
|
| 54 |
+
|
| 55 |
+
- Vec2(vec2)
|
| 56 |
+
- Vec2(vec3)
|
| 57 |
+
- Vec2((x, y))
|
| 58 |
+
- Vec2((x, y, z)), ignore z-axis
|
| 59 |
+
- Vec2(x, y)
|
| 60 |
+
- Vec2(x, y, z), ignore z-axis
|
| 61 |
+
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __cinit__(self, *args):
|
| 65 |
+
cdef Py_ssize_t count = len(<tuple> args)
|
| 66 |
+
|
| 67 |
+
if count == 0: # fastest init - default constructor
|
| 68 |
+
self.x = 0
|
| 69 |
+
self.y = 0
|
| 70 |
+
return
|
| 71 |
+
|
| 72 |
+
if count == 1:
|
| 73 |
+
arg = args[0]
|
| 74 |
+
if isinstance(arg, Vec2):
|
| 75 |
+
# fast init by Vec2()
|
| 76 |
+
self.x = (<Vec2> arg).x
|
| 77 |
+
self.y = (<Vec2> arg).y
|
| 78 |
+
return
|
| 79 |
+
if isinstance(arg, Vec3):
|
| 80 |
+
# fast init by Vec3()
|
| 81 |
+
self.x = (<Vec3> arg).x
|
| 82 |
+
self.y = (<Vec3> arg).y
|
| 83 |
+
return
|
| 84 |
+
args = arg
|
| 85 |
+
count = len(args)
|
| 86 |
+
|
| 87 |
+
# ignore z-axis but raise error for 4 or more arguments
|
| 88 |
+
if count > 3:
|
| 89 |
+
raise TypeError('invalid argument count')
|
| 90 |
+
|
| 91 |
+
# slow init by sequence
|
| 92 |
+
self.x = args[0]
|
| 93 |
+
self.y = args[1]
|
| 94 |
+
|
| 95 |
+
def __reduce__(self):
|
| 96 |
+
return Vec2, (self.x, self.y)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def vec3(self) -> Vec3:
|
| 100 |
+
return Vec3(self)
|
| 101 |
+
|
| 102 |
+
def round(self, ndigits=None) -> Vec2:
|
| 103 |
+
# only used for testing
|
| 104 |
+
return Vec2(round(self.x, ndigits), round(self.y, ndigits))
|
| 105 |
+
|
| 106 |
+
@staticmethod
|
| 107 |
+
def list(items: Iterable[UVec]) -> List[Vec2]:
|
| 108 |
+
return list(Vec2.generate(items))
|
| 109 |
+
|
| 110 |
+
@staticmethod
|
| 111 |
+
def tuple(items: Iterable[UVec]) -> Sequence[Vec2]:
|
| 112 |
+
return tuple(Vec2.generate(items))
|
| 113 |
+
|
| 114 |
+
@staticmethod
|
| 115 |
+
def generate(items: Iterable[UVec]) -> Iterator[Vec2]:
|
| 116 |
+
return (Vec2(item) for item in items)
|
| 117 |
+
|
| 118 |
+
@staticmethod
|
| 119 |
+
def from_angle(double angle, double length = 1.0) -> Vec2:
|
| 120 |
+
return v2_from_angle(angle, length)
|
| 121 |
+
|
| 122 |
+
@staticmethod
|
| 123 |
+
def from_deg_angle(double angle, double length = 1.0) -> Vec2:
|
| 124 |
+
return v2_from_angle(angle * DEG2RAD, length)
|
| 125 |
+
|
| 126 |
+
def __str__(self) -> str:
|
| 127 |
+
return f'({self.x}, {self.y})'
|
| 128 |
+
|
| 129 |
+
def __repr__(self)-> str:
|
| 130 |
+
return "Vec2" + self.__str__()
|
| 131 |
+
|
| 132 |
+
def __len__(self) -> int:
|
| 133 |
+
return 2
|
| 134 |
+
|
| 135 |
+
def __hash__(self) -> int:
|
| 136 |
+
return hash((self.x, self.y))
|
| 137 |
+
|
| 138 |
+
def copy(self) -> Vec2:
|
| 139 |
+
return self # immutable
|
| 140 |
+
|
| 141 |
+
def __copy__(self) -> Vec2:
|
| 142 |
+
return self # immutable
|
| 143 |
+
|
| 144 |
+
def __deepcopy__(self, memodict: dict) -> Vec2:
|
| 145 |
+
return self # immutable
|
| 146 |
+
|
| 147 |
+
def __getitem__(self, int index) -> float:
|
| 148 |
+
if index == 0:
|
| 149 |
+
return self.x
|
| 150 |
+
elif index == 1:
|
| 151 |
+
return self.y
|
| 152 |
+
else:
|
| 153 |
+
raise IndexError(f'invalid index {index}')
|
| 154 |
+
|
| 155 |
+
def __iter__(self) -> Iterator[float]:
|
| 156 |
+
yield self.x
|
| 157 |
+
yield self.y
|
| 158 |
+
|
| 159 |
+
def __abs__(self) -> float:
|
| 160 |
+
return hypot(self.x, self.y)
|
| 161 |
+
|
| 162 |
+
@property
|
| 163 |
+
def magnitude(self) -> float:
|
| 164 |
+
return hypot(self.x, self.y)
|
| 165 |
+
|
| 166 |
+
@property
|
| 167 |
+
def is_null(self) -> bool:
|
| 168 |
+
return fabs(self.x) <= ABS_TOL and fabs(self.y) <= ABS_TOL
|
| 169 |
+
|
| 170 |
+
@property
|
| 171 |
+
def angle(self) -> float:
|
| 172 |
+
return atan2(self.y, self.x)
|
| 173 |
+
|
| 174 |
+
@property
|
| 175 |
+
def angle_deg(self) -> float:
|
| 176 |
+
return atan2(self.y, self.x) * RAD2DEG
|
| 177 |
+
|
| 178 |
+
def orthogonal(self, ccw: bool = True) -> Vec2:
|
| 179 |
+
return v2_ortho(self, ccw)
|
| 180 |
+
|
| 181 |
+
def lerp(self, other: "AnyVec", double factor = 0.5) -> Vec2:
|
| 182 |
+
cdef Vec2 o = Vec2(other)
|
| 183 |
+
return v2_lerp(self, o, factor)
|
| 184 |
+
|
| 185 |
+
def normalize(self, double length = 1.) -> Vec2:
|
| 186 |
+
return v2_normalize(self, length)
|
| 187 |
+
|
| 188 |
+
def project(self, other: AnyVec) -> Vec2:
|
| 189 |
+
cdef Vec2 o = Vec2(other)
|
| 190 |
+
return v2_project(self, o)
|
| 191 |
+
|
| 192 |
+
def __neg__(self) -> Vec2:
|
| 193 |
+
cdef Vec2 res = Vec2()
|
| 194 |
+
res.x = -self.x
|
| 195 |
+
res.y = -self.y
|
| 196 |
+
return res
|
| 197 |
+
|
| 198 |
+
reversed = __neg__
|
| 199 |
+
|
| 200 |
+
def __bool__(self) -> bool:
|
| 201 |
+
return self.x != 0 or self.y != 0
|
| 202 |
+
|
| 203 |
+
def isclose(self, other: UVec, *, double rel_tol=REL_TOL,
|
| 204 |
+
double abs_tol = ABS_TOL) -> bool:
|
| 205 |
+
cdef Vec2 o = Vec2(other)
|
| 206 |
+
return isclose(self.x, o.x, rel_tol, abs_tol) and \
|
| 207 |
+
isclose(self.y, o.y, rel_tol, abs_tol)
|
| 208 |
+
|
| 209 |
+
def __eq__(self, other: UVec) -> bool:
|
| 210 |
+
if not isinstance(other, Vec2):
|
| 211 |
+
other = Vec2(other)
|
| 212 |
+
return self.x == other.x and self.y == other.y
|
| 213 |
+
|
| 214 |
+
def __lt__(self, other) -> bool:
|
| 215 |
+
cdef Vec2 o = Vec2(other)
|
| 216 |
+
if self.x == o.x:
|
| 217 |
+
return self.y < o.y
|
| 218 |
+
else:
|
| 219 |
+
return self.x < o.x
|
| 220 |
+
|
| 221 |
+
def __add__(self, other: AnyVec) -> Vec2:
|
| 222 |
+
if not isinstance(other, Vec2):
|
| 223 |
+
other = Vec2(other)
|
| 224 |
+
return v2_add(self, <Vec2> other)
|
| 225 |
+
|
| 226 |
+
# __radd__ not supported for Vec2
|
| 227 |
+
|
| 228 |
+
__iadd__ = __add__ # immutable
|
| 229 |
+
|
| 230 |
+
def __sub__(self, other: AnyVec) -> Vec2:
|
| 231 |
+
if not isinstance(other, Vec2):
|
| 232 |
+
other = Vec2(other)
|
| 233 |
+
return v2_sub(self, <Vec2> other)
|
| 234 |
+
|
| 235 |
+
# __rsub__ not supported for Vec2
|
| 236 |
+
|
| 237 |
+
__isub__ = __sub__ # immutable
|
| 238 |
+
|
| 239 |
+
def __mul__(self, factor) -> Vec2:
|
| 240 |
+
if isinstance(self, Vec2):
|
| 241 |
+
return v2_mul(self, factor)
|
| 242 |
+
elif isinstance(factor, Vec2):
|
| 243 |
+
return v2_mul(<Vec2> factor, <double> self)
|
| 244 |
+
else:
|
| 245 |
+
return NotImplemented
|
| 246 |
+
|
| 247 |
+
# Special Cython <(3.0) feature: __rmul__ == __mul__(factor, self)
|
| 248 |
+
|
| 249 |
+
def __rmul__(self, double factor) -> Vec2:
|
| 250 |
+
# for Cython >= 3.0
|
| 251 |
+
return v2_mul(self, factor)
|
| 252 |
+
|
| 253 |
+
__imul__ = __mul__ # immutable
|
| 254 |
+
|
| 255 |
+
def __truediv__(self, double factor) -> Vec2:
|
| 256 |
+
return v2_mul(self, 1.0 / factor)
|
| 257 |
+
|
| 258 |
+
# __rtruediv__ not supported -> TypeError
|
| 259 |
+
|
| 260 |
+
def dot(self, other: AnyVec) -> float:
|
| 261 |
+
cdef Vec2 o = Vec2(other)
|
| 262 |
+
return v2_dot(self, o)
|
| 263 |
+
|
| 264 |
+
def det(self, other: AnyVec) -> float:
|
| 265 |
+
cdef Vec2 o = Vec2(other)
|
| 266 |
+
return v2_det(self, o)
|
| 267 |
+
|
| 268 |
+
def distance(self, other: AnyVec) -> float:
|
| 269 |
+
cdef Vec2 o = Vec2(other)
|
| 270 |
+
return v2_dist(self, o)
|
| 271 |
+
|
| 272 |
+
def angle_between(self, other: AnyVec) -> float:
|
| 273 |
+
cdef Vec2 o = Vec2(other)
|
| 274 |
+
return v2_angle_between(self, o)
|
| 275 |
+
|
| 276 |
+
def rotate(self, double angle) -> Vec2:
|
| 277 |
+
cdef double self_angle = atan2(self.y, self.x)
|
| 278 |
+
cdef double magnitude = hypot(self.x, self.y)
|
| 279 |
+
return v2_from_angle(self_angle + angle, magnitude)
|
| 280 |
+
|
| 281 |
+
def rotate_deg(self, double angle) -> Vec2:
|
| 282 |
+
return self.rotate(angle * DEG2RAD)
|
| 283 |
+
|
| 284 |
+
@staticmethod
|
| 285 |
+
def sum(items: Iterable[Vec2]) -> Vec2:
|
| 286 |
+
cdef Vec2 res = Vec2()
|
| 287 |
+
cdef Vec2 tmp
|
| 288 |
+
res.x = 0.0
|
| 289 |
+
res.y = 0.0
|
| 290 |
+
for v in items:
|
| 291 |
+
tmp = v
|
| 292 |
+
res.x += tmp.x
|
| 293 |
+
res.y += tmp.y
|
| 294 |
+
return res
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
cdef Vec2 v2_add(Vec2 a, Vec2 b):
|
| 298 |
+
res = Vec2()
|
| 299 |
+
res.x = a.x + b.x
|
| 300 |
+
res.y = a.y + b.y
|
| 301 |
+
return res
|
| 302 |
+
|
| 303 |
+
cdef Vec2 v2_sub(Vec2 a, Vec2 b):
|
| 304 |
+
res = Vec2()
|
| 305 |
+
res.x = a.x - b.x
|
| 306 |
+
res.y = a.y - b.y
|
| 307 |
+
return res
|
| 308 |
+
|
| 309 |
+
cdef Vec2 v2_mul(Vec2 a, double factor):
|
| 310 |
+
res = Vec2()
|
| 311 |
+
res.x = a.x * factor
|
| 312 |
+
res.y = a.y * factor
|
| 313 |
+
return res
|
| 314 |
+
|
| 315 |
+
cdef double v2_dot(Vec2 a, Vec2 b):
|
| 316 |
+
return a.x * b.x + a.y * b.y
|
| 317 |
+
|
| 318 |
+
cdef double v2_det(Vec2 a, Vec2 b):
|
| 319 |
+
return a.x * b.y - a.y * b.x
|
| 320 |
+
|
| 321 |
+
cdef double v2_dist(Vec2 a, Vec2 b):
|
| 322 |
+
return hypot(a.x - b.x, a.y - b.y)
|
| 323 |
+
|
| 324 |
+
cdef Vec2 v2_from_angle(double angle, double length):
|
| 325 |
+
cdef Vec2 res = Vec2()
|
| 326 |
+
res.x = cos(angle) * length
|
| 327 |
+
res.y = sin(angle) * length
|
| 328 |
+
return res
|
| 329 |
+
|
| 330 |
+
cdef double v2_angle_between(Vec2 a, Vec2 b) except -1000:
|
| 331 |
+
cdef double cos_theta = v2_dot(v2_normalize(a, 1.0), v2_normalize(b, 1.0))
|
| 332 |
+
# avoid domain errors caused by floating point imprecision:
|
| 333 |
+
if cos_theta < -1.0:
|
| 334 |
+
cos_theta = -1.0
|
| 335 |
+
elif cos_theta > 1.0:
|
| 336 |
+
cos_theta = 1.0
|
| 337 |
+
return acos(cos_theta)
|
| 338 |
+
|
| 339 |
+
cdef Vec2 v2_normalize(Vec2 a, double length):
|
| 340 |
+
cdef double factor = length / hypot(a.x, a.y)
|
| 341 |
+
cdef Vec2 res = Vec2()
|
| 342 |
+
res.x = a.x * factor
|
| 343 |
+
res.y = a.y * factor
|
| 344 |
+
return res
|
| 345 |
+
|
| 346 |
+
cdef Vec2 v2_lerp(Vec2 a, Vec2 b, double factor):
|
| 347 |
+
cdef Vec2 res = Vec2()
|
| 348 |
+
res.x = a.x + (b.x - a.x) * factor
|
| 349 |
+
res.y = a.y + (b.y - a.y) * factor
|
| 350 |
+
return res
|
| 351 |
+
|
| 352 |
+
cdef Vec2 v2_ortho(Vec2 a, bint ccw):
|
| 353 |
+
cdef Vec2 res = Vec2()
|
| 354 |
+
if ccw:
|
| 355 |
+
res.x = -a.y
|
| 356 |
+
res.y = a.x
|
| 357 |
+
else:
|
| 358 |
+
res.x = a.y
|
| 359 |
+
res.y = -a.x
|
| 360 |
+
return res
|
| 361 |
+
|
| 362 |
+
cdef Vec2 v2_project(Vec2 a, Vec2 b):
|
| 363 |
+
cdef Vec2 uv = v2_normalize(a, 1.0)
|
| 364 |
+
return v2_mul(uv, v2_dot(uv, b))
|
| 365 |
+
|
| 366 |
+
cdef bint v2_isclose(Vec2 a, Vec2 b, double rel_tol, double abs_tol):
|
| 367 |
+
return isclose(a.x, b.x, rel_tol, abs_tol) and \
|
| 368 |
+
isclose(a.y, b.y, rel_tol, abs_tol)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
cdef class Vec3:
|
| 372 |
+
""" Immutable 3D vector.
|
| 373 |
+
|
| 374 |
+
Init:
|
| 375 |
+
|
| 376 |
+
- Vec3()
|
| 377 |
+
- Vec3(vec3)
|
| 378 |
+
- Vec3(vec2)
|
| 379 |
+
- Vec3((x, y))
|
| 380 |
+
- Vec3((x, y, z))
|
| 381 |
+
- Vec3(x, y)
|
| 382 |
+
- Vec3(x, y, z)
|
| 383 |
+
|
| 384 |
+
"""
|
| 385 |
+
|
| 386 |
+
def __cinit__(self, *args):
|
| 387 |
+
cdef Py_ssize_t count = len(<tuple> args)
|
| 388 |
+
if count == 0: # fastest init - default constructor
|
| 389 |
+
self.x = 0
|
| 390 |
+
self.y = 0
|
| 391 |
+
self.z = 0
|
| 392 |
+
return
|
| 393 |
+
|
| 394 |
+
if count == 1:
|
| 395 |
+
arg0 = args[0]
|
| 396 |
+
if isinstance(arg0, Vec3):
|
| 397 |
+
# fast init by Vec3()
|
| 398 |
+
self.x = (<Vec3> arg0).x
|
| 399 |
+
self.y = (<Vec3> arg0).y
|
| 400 |
+
self.z = (<Vec3> arg0).z
|
| 401 |
+
return
|
| 402 |
+
if isinstance(arg0, Vec2):
|
| 403 |
+
# fast init by Vec2()
|
| 404 |
+
self.x = (<Vec2> arg0).x
|
| 405 |
+
self.y = (<Vec2> arg0).y
|
| 406 |
+
self.z = 0
|
| 407 |
+
return
|
| 408 |
+
args = arg0
|
| 409 |
+
count = len(args)
|
| 410 |
+
|
| 411 |
+
if count > 3 or count < 2:
|
| 412 |
+
raise TypeError('invalid argument count')
|
| 413 |
+
|
| 414 |
+
# slow init by sequence
|
| 415 |
+
self.x = args[0]
|
| 416 |
+
self.y = args[1]
|
| 417 |
+
if count > 2:
|
| 418 |
+
self.z = args[2]
|
| 419 |
+
else:
|
| 420 |
+
self.z = 0.0
|
| 421 |
+
|
| 422 |
+
def __reduce__(self):
|
| 423 |
+
return Vec3, self.xyz
|
| 424 |
+
|
| 425 |
+
@property
|
| 426 |
+
def xy(self) -> Vec3:
|
| 427 |
+
cdef Vec3 res = Vec3()
|
| 428 |
+
res.x = self.x
|
| 429 |
+
res.y = self.y
|
| 430 |
+
return res
|
| 431 |
+
|
| 432 |
+
@property
|
| 433 |
+
def xyz(self) -> Tuple[float, float, float]:
|
| 434 |
+
return self.x, self.y, self.z
|
| 435 |
+
|
| 436 |
+
@property
|
| 437 |
+
def vec2(self) -> Vec2:
|
| 438 |
+
cdef Vec2 res = Vec2()
|
| 439 |
+
res.x = self.x
|
| 440 |
+
res.y = self.y
|
| 441 |
+
return res
|
| 442 |
+
|
| 443 |
+
def replace(self, x: float = None, y: float = None,
|
| 444 |
+
z: float = None) -> Vec3:
|
| 445 |
+
cdef Vec3 res = Vec3()
|
| 446 |
+
res.x = self.x if x is None else x
|
| 447 |
+
res.y = self.y if y is None else y
|
| 448 |
+
res.z = self.z if z is None else z
|
| 449 |
+
return res
|
| 450 |
+
|
| 451 |
+
def round(self, ndigits: int | None = None) -> Vec3:
|
| 452 |
+
return Vec3(
|
| 453 |
+
round(self.x, ndigits),
|
| 454 |
+
round(self.y, ndigits),
|
| 455 |
+
round(self.z, ndigits),
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
@staticmethod
|
| 459 |
+
def list(items: Iterable[UVec]) -> List[Vec3]:
|
| 460 |
+
return list(Vec3.generate(items))
|
| 461 |
+
|
| 462 |
+
@staticmethod
|
| 463 |
+
def tuple(items: Iterable[UVec]) -> Sequence[Vec3]:
|
| 464 |
+
return tuple(Vec3.generate(items))
|
| 465 |
+
|
| 466 |
+
@staticmethod
|
| 467 |
+
def generate(items: Iterable[UVec]) -> Iterator[Vec3]:
|
| 468 |
+
return (Vec3(item) for item in items)
|
| 469 |
+
|
| 470 |
+
@staticmethod
|
| 471 |
+
def from_angle(double angle, double length = 1.0) -> Vec3:
|
| 472 |
+
return v3_from_angle(angle, length)
|
| 473 |
+
|
| 474 |
+
@staticmethod
|
| 475 |
+
def from_deg_angle(double angle, double length = 1.0) -> Vec3:
|
| 476 |
+
return v3_from_angle(angle * DEG2RAD, length)
|
| 477 |
+
|
| 478 |
+
@staticmethod
|
| 479 |
+
def random(double length = 1.0) -> Vec3:
|
| 480 |
+
cdef Vec3 res = Vec3()
|
| 481 |
+
uniform = random.uniform
|
| 482 |
+
res.x = uniform(-1, 1)
|
| 483 |
+
res.y = uniform(-1, 1)
|
| 484 |
+
res.z = uniform(-1, 1)
|
| 485 |
+
return v3_normalize(res, length)
|
| 486 |
+
|
| 487 |
+
def __str__(self) -> str:
|
| 488 |
+
return f'({self.x}, {self.y}, {self.z})'
|
| 489 |
+
|
| 490 |
+
def __repr__(self)-> str:
|
| 491 |
+
return "Vec3" + self.__str__()
|
| 492 |
+
|
| 493 |
+
def __len__(self) -> int:
|
| 494 |
+
return 3
|
| 495 |
+
|
| 496 |
+
def __hash__(self) -> int:
|
| 497 |
+
return hash(self.xyz)
|
| 498 |
+
|
| 499 |
+
def copy(self) -> Vec3:
|
| 500 |
+
return self # immutable
|
| 501 |
+
|
| 502 |
+
__copy__ = copy
|
| 503 |
+
|
| 504 |
+
def __deepcopy__(self, memodict: dict) -> Vec3:
|
| 505 |
+
return self # immutable!
|
| 506 |
+
|
| 507 |
+
def __getitem__(self, int index) -> float:
|
| 508 |
+
if index == 0:
|
| 509 |
+
return self.x
|
| 510 |
+
elif index == 1:
|
| 511 |
+
return self.y
|
| 512 |
+
elif index == 2:
|
| 513 |
+
return self.z
|
| 514 |
+
else:
|
| 515 |
+
raise IndexError(f'invalid index {index}')
|
| 516 |
+
|
| 517 |
+
def __iter__(self) -> Iterator[float]:
|
| 518 |
+
yield self.x
|
| 519 |
+
yield self.y
|
| 520 |
+
yield self.z
|
| 521 |
+
|
| 522 |
+
def __abs__(self) -> float:
|
| 523 |
+
return v3_magnitude(self)
|
| 524 |
+
|
| 525 |
+
@property
|
| 526 |
+
def magnitude(self) -> float:
|
| 527 |
+
return v3_magnitude(self)
|
| 528 |
+
|
| 529 |
+
@property
|
| 530 |
+
def magnitude_xy(self) -> float:
|
| 531 |
+
return hypot(self.x, self.y)
|
| 532 |
+
|
| 533 |
+
@property
|
| 534 |
+
def magnitude_square(self) -> float:
|
| 535 |
+
return v3_magnitude_sqr(self)
|
| 536 |
+
|
| 537 |
+
@property
|
| 538 |
+
def is_null(self) -> bool:
|
| 539 |
+
return fabs(self.x) <= ABS_TOL and fabs(self.y) <= ABS_TOL and \
|
| 540 |
+
fabs(self.z) <= ABS_TOL
|
| 541 |
+
|
| 542 |
+
def is_parallel(self, other: UVec, *, double rel_tol=REL_TOL,
|
| 543 |
+
double abs_tol = ABS_TOL) -> bool:
|
| 544 |
+
cdef Vec3 o = Vec3(other)
|
| 545 |
+
cdef Vec3 v1 = v3_normalize(self, 1.0)
|
| 546 |
+
cdef Vec3 v2 = v3_normalize(o, 1.0)
|
| 547 |
+
cdef Vec3 neg_v2 = v3_reverse(v2)
|
| 548 |
+
return v3_isclose(v1, v2, rel_tol, abs_tol) or \
|
| 549 |
+
v3_isclose(v1, neg_v2, rel_tol, abs_tol)
|
| 550 |
+
|
| 551 |
+
@property
|
| 552 |
+
def spatial_angle(self) -> float:
|
| 553 |
+
return acos(v3_dot(<Vec3> X_AXIS, v3_normalize(self, 1.0)))
|
| 554 |
+
|
| 555 |
+
@property
|
| 556 |
+
def spatial_angle_deg(self) -> float:
|
| 557 |
+
return self.spatial_angle * RAD2DEG
|
| 558 |
+
|
| 559 |
+
@property
|
| 560 |
+
def angle(self) -> float:
|
| 561 |
+
return atan2(self.y, self.x)
|
| 562 |
+
|
| 563 |
+
@property
|
| 564 |
+
def angle_deg(self) -> float:
|
| 565 |
+
return atan2(self.y, self.x) * RAD2DEG
|
| 566 |
+
|
| 567 |
+
def orthogonal(self, ccw: bool = True) -> Vec3:
|
| 568 |
+
return v3_ortho(self, ccw)
|
| 569 |
+
|
| 570 |
+
def lerp(self, other: UVec, double factor=0.5) -> Vec3:
|
| 571 |
+
if not isinstance(other, Vec3):
|
| 572 |
+
other = Vec3(other)
|
| 573 |
+
return v3_lerp(self, <Vec3> other, factor)
|
| 574 |
+
|
| 575 |
+
def project(self, other: UVec) -> Vec3:
|
| 576 |
+
if not isinstance(other, Vec3):
|
| 577 |
+
other = Vec3(other)
|
| 578 |
+
return v3_project(self, <Vec3> other)
|
| 579 |
+
|
| 580 |
+
def normalize(self, double length = 1.) -> Vec3:
|
| 581 |
+
return v3_normalize(self, length)
|
| 582 |
+
|
| 583 |
+
def reversed(self) -> Vec3:
|
| 584 |
+
return v3_reverse(self)
|
| 585 |
+
|
| 586 |
+
def __neg__(self) -> Vec3:
|
| 587 |
+
return v3_reverse(self)
|
| 588 |
+
|
| 589 |
+
def __bool__(self) -> bool:
|
| 590 |
+
return not self.is_null
|
| 591 |
+
|
| 592 |
+
def isclose(self, other: UVec, *, double rel_tol = REL_TOL,
|
| 593 |
+
double abs_tol = ABS_TOL) -> bool:
|
| 594 |
+
if not isinstance(other, Vec3):
|
| 595 |
+
other = Vec3(other)
|
| 596 |
+
return v3_isclose(self, <Vec3> other, rel_tol, abs_tol)
|
| 597 |
+
|
| 598 |
+
def __eq__(self, other: UVec) -> bool:
|
| 599 |
+
if not isinstance(other, Vec3):
|
| 600 |
+
other = Vec3(other)
|
| 601 |
+
return self.x == other.x and self.y == other.y and self.z == other.z
|
| 602 |
+
|
| 603 |
+
def __lt__(self, other: UVec) -> bool:
|
| 604 |
+
if not isinstance(other, Vec3):
|
| 605 |
+
other = Vec3(other)
|
| 606 |
+
if self.x == (<Vec3> other).x:
|
| 607 |
+
return self.y < (<Vec3> other).y
|
| 608 |
+
else:
|
| 609 |
+
return self.x < (<Vec3> other).x
|
| 610 |
+
|
| 611 |
+
# Special Cython (<3.0) feature: __radd__ == __add__(other, self)
|
| 612 |
+
def __add__(self, other) -> Vec3:
|
| 613 |
+
if not isinstance(self, Vec3):
|
| 614 |
+
# other is the real self
|
| 615 |
+
return v3_add(Vec3(self), <Vec3> other)
|
| 616 |
+
|
| 617 |
+
if not isinstance(other, Vec3):
|
| 618 |
+
other = Vec3(other)
|
| 619 |
+
return v3_add(<Vec3> self, <Vec3> other)
|
| 620 |
+
|
| 621 |
+
__radd__ = __add__ # Cython >= 3.0
|
| 622 |
+
|
| 623 |
+
__iadd__ = __add__ # immutable
|
| 624 |
+
|
| 625 |
+
# Special Cython (<3.0) feature: __rsub__ == __sub__(other, self)
|
| 626 |
+
def __sub__(self, other) -> Vec3:
|
| 627 |
+
if not isinstance(self, Vec3):
|
| 628 |
+
# other is the real self
|
| 629 |
+
return v3_sub(Vec3(self), <Vec3> other)
|
| 630 |
+
|
| 631 |
+
if not isinstance(other, Vec3):
|
| 632 |
+
other = Vec3(other)
|
| 633 |
+
return v3_sub(<Vec3> self, <Vec3> other)
|
| 634 |
+
|
| 635 |
+
def __rsub__(self, other) -> Vec3:
|
| 636 |
+
# for Cython >= 3.0
|
| 637 |
+
return v3_sub(Vec3(other), <Vec3> self)
|
| 638 |
+
|
| 639 |
+
__isub__ = __sub__ # immutable
|
| 640 |
+
|
| 641 |
+
# Special Cython <(3.0) feature: __rmul__ == __mul__(factor, self)
|
| 642 |
+
def __mul__(self, factor) -> Vec3:
|
| 643 |
+
if isinstance(factor, Vec3):
|
| 644 |
+
return v3_mul(<Vec3> factor, self)
|
| 645 |
+
return v3_mul(<Vec3> self, factor)
|
| 646 |
+
|
| 647 |
+
def __rmul__(self, double factor) -> Vec3:
|
| 648 |
+
# for Cython >= 3.0
|
| 649 |
+
return v3_mul(self, factor)
|
| 650 |
+
|
| 651 |
+
__imul__ = __mul__ # immutable
|
| 652 |
+
|
| 653 |
+
def __truediv__(self, double factor) -> Vec3:
|
| 654 |
+
return v3_mul(self, 1.0 / factor)
|
| 655 |
+
|
| 656 |
+
# __rtruediv__ not supported -> TypeError
|
| 657 |
+
|
| 658 |
+
@staticmethod
|
| 659 |
+
def sum(items: Iterable[UVec]) -> Vec3:
|
| 660 |
+
cdef Vec3 res = Vec3()
|
| 661 |
+
cdef Vec3 tmp
|
| 662 |
+
for v in items:
|
| 663 |
+
tmp = Vec3(v)
|
| 664 |
+
res.x += tmp.x
|
| 665 |
+
res.y += tmp.y
|
| 666 |
+
res.z += tmp.z
|
| 667 |
+
return res
|
| 668 |
+
|
| 669 |
+
def dot(self, other: UVec) -> float:
|
| 670 |
+
cdef Vec3 o = Vec3(other)
|
| 671 |
+
return v3_dot(self, o)
|
| 672 |
+
|
| 673 |
+
def cross(self, other: UVec) -> Vec3:
|
| 674 |
+
cdef Vec3 o = Vec3(other)
|
| 675 |
+
return v3_cross(self, o)
|
| 676 |
+
|
| 677 |
+
def distance(self, other: UVec) -> float:
|
| 678 |
+
cdef Vec3 o = Vec3(other)
|
| 679 |
+
return v3_dist(self, o)
|
| 680 |
+
|
| 681 |
+
def angle_between(self, other: UVec) -> float:
|
| 682 |
+
cdef Vec3 o = Vec3(other)
|
| 683 |
+
return v3_angle_between(self, o)
|
| 684 |
+
|
| 685 |
+
def angle_about(self, base: UVec, target: UVec) -> float:
|
| 686 |
+
cdef Vec3 b = Vec3(base)
|
| 687 |
+
cdef Vec3 t = Vec3(target)
|
| 688 |
+
return v3_angle_about(self, b, t)
|
| 689 |
+
|
| 690 |
+
def rotate(self, double angle) -> Vec3:
|
| 691 |
+
cdef double angle_ = atan2(self.y, self.x) + angle
|
| 692 |
+
cdef double magnitude_ = hypot(self.x, self.y)
|
| 693 |
+
cdef Vec3 res = Vec3.from_angle(angle_, magnitude_)
|
| 694 |
+
res.z = self.z
|
| 695 |
+
return res
|
| 696 |
+
|
| 697 |
+
def rotate_deg(self, double angle) -> Vec3:
|
| 698 |
+
return self.rotate(angle * DEG2RAD)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
X_AXIS = Vec3(1, 0, 0)
|
| 702 |
+
Y_AXIS = Vec3(0, 1, 0)
|
| 703 |
+
Z_AXIS = Vec3(0, 0, 1)
|
| 704 |
+
NULLVEC = Vec3(0, 0, 0)
|
| 705 |
+
|
| 706 |
+
cdef Vec3 v3_add(Vec3 a, Vec3 b):
|
| 707 |
+
res = Vec3()
|
| 708 |
+
res.x = a.x + b.x
|
| 709 |
+
res.y = a.y + b.y
|
| 710 |
+
res.z = a.z + b.z
|
| 711 |
+
return res
|
| 712 |
+
|
| 713 |
+
cdef Vec3 v3_sub(Vec3 a, Vec3 b):
|
| 714 |
+
res = Vec3()
|
| 715 |
+
res.x = a.x - b.x
|
| 716 |
+
res.y = a.y - b.y
|
| 717 |
+
res.z = a.z - b.z
|
| 718 |
+
return res
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
cdef Vec3 v3_mul(Vec3 a, double factor):
|
| 722 |
+
res = Vec3()
|
| 723 |
+
res.x = a.x * factor
|
| 724 |
+
res.y = a.y * factor
|
| 725 |
+
res.z = a.z * factor
|
| 726 |
+
return res
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
cdef Vec3 v3_reverse(Vec3 a):
|
| 730 |
+
cdef Vec3 res = Vec3()
|
| 731 |
+
res.x = -a.x
|
| 732 |
+
res.y = -a.y
|
| 733 |
+
res.z = -a.z
|
| 734 |
+
return res
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
cdef double v3_dot(Vec3 a, Vec3 b):
|
| 738 |
+
return a.x * b.x + a.y * b.y + a.z * b.z
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
cdef Vec3 v3_cross(Vec3 a, Vec3 b):
|
| 742 |
+
res = Vec3()
|
| 743 |
+
res.x = a.y * b.z - a.z * b.y
|
| 744 |
+
res.y = a.z * b.x - a.x * b.z
|
| 745 |
+
res.z = a.x * b.y - a.y * b.x
|
| 746 |
+
return res
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
cdef inline double v3_magnitude_sqr(Vec3 a):
|
| 750 |
+
return a.x * a.x + a.y * a.y + a.z * a.z
|
| 751 |
+
|
| 752 |
+
|
| 753 |
+
cdef inline double v3_magnitude(Vec3 a):
|
| 754 |
+
return sqrt(v3_magnitude_sqr(a))
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
cdef double v3_dist(Vec3 a, Vec3 b):
|
| 758 |
+
cdef double dx = a.x - b.x
|
| 759 |
+
cdef double dy = a.y - b.y
|
| 760 |
+
cdef double dz = a.z - b.z
|
| 761 |
+
return sqrt(dx * dx + dy * dy + dz * dz)
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
cdef Vec3 v3_from_angle(double angle, double length):
|
| 765 |
+
cdef Vec3 res = Vec3()
|
| 766 |
+
res.x = cos(angle) * length
|
| 767 |
+
res.y = sin(angle) * length
|
| 768 |
+
return res
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
cdef double v3_angle_between(Vec3 a, Vec3 b) except -1000:
|
| 772 |
+
cdef double cos_theta = v3_dot(v3_normalize(a, 1.0), v3_normalize(b, 1.0))
|
| 773 |
+
# avoid domain errors caused by floating point imprecision:
|
| 774 |
+
if cos_theta < -1.0:
|
| 775 |
+
cos_theta = -1.0
|
| 776 |
+
elif cos_theta > 1.0:
|
| 777 |
+
cos_theta = 1.0
|
| 778 |
+
return acos(cos_theta)
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
cdef double v3_angle_about(Vec3 a, Vec3 base, Vec3 target):
|
| 782 |
+
cdef Vec3 x_axis = v3_normalize(v3_sub(base, v3_project(a, base)), 1.0)
|
| 783 |
+
cdef Vec3 y_axis = v3_normalize(v3_cross(a, x_axis), 1.0)
|
| 784 |
+
cdef double target_projected_x = v3_dot(x_axis, target)
|
| 785 |
+
cdef double target_projected_y = v3_dot(y_axis, target)
|
| 786 |
+
return normalize_rad_angle(atan2(target_projected_y, target_projected_x))
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
cdef Vec3 v3_normalize(Vec3 a, double length):
|
| 790 |
+
cdef double factor = length / v3_magnitude(a)
|
| 791 |
+
cdef Vec3 res = Vec3()
|
| 792 |
+
res.x = a.x * factor
|
| 793 |
+
res.y = a.y * factor
|
| 794 |
+
res.z = a.z * factor
|
| 795 |
+
return res
|
| 796 |
+
|
| 797 |
+
|
| 798 |
+
cdef Vec3 v3_lerp(Vec3 a, Vec3 b, double factor):
|
| 799 |
+
cdef Vec3 res = Vec3()
|
| 800 |
+
res.x = a.x + (b.x - a.x) * factor
|
| 801 |
+
res.y = a.y + (b.y - a.y) * factor
|
| 802 |
+
res.z = a.z + (b.z - a.z) * factor
|
| 803 |
+
return res
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
cdef Vec3 v3_ortho(Vec3 a, bint ccw):
|
| 807 |
+
cdef Vec3 res = Vec3()
|
| 808 |
+
res.z = a.z
|
| 809 |
+
if ccw:
|
| 810 |
+
res.x = -a.y
|
| 811 |
+
res.y = a.x
|
| 812 |
+
else:
|
| 813 |
+
res.x = a.y
|
| 814 |
+
res.y = -a.x
|
| 815 |
+
return res
|
| 816 |
+
|
| 817 |
+
|
| 818 |
+
cdef Vec3 v3_project(Vec3 a, Vec3 b):
|
| 819 |
+
cdef Vec3 uv = v3_normalize(a, 1.0)
|
| 820 |
+
return v3_mul(uv, v3_dot(uv, b))
|
| 821 |
+
|
| 822 |
+
|
| 823 |
+
cdef bint v3_isclose(Vec3 a, Vec3 b, double rel_tol, double abs_tol):
|
| 824 |
+
return isclose(a.x, b.x, rel_tol, abs_tol) and \
|
| 825 |
+
isclose(a.y, b.y, rel_tol, abs_tol) and \
|
| 826 |
+
isclose(a.z, b.z, rel_tol, abs_tol)
|
| 827 |
+
|
| 828 |
+
|
| 829 |
+
def distance(p1: UVec, p2: UVec) -> float:
|
| 830 |
+
cdef Vec3 a = Vec3(p1)
|
| 831 |
+
cdef Vec3 b = Vec3(p2)
|
| 832 |
+
return v3_dist(a, b)
|
| 833 |
+
|
| 834 |
+
|
| 835 |
+
def lerp(p1: UVec, p2: UVec, double factor = 0.5) -> Vec3:
|
| 836 |
+
cdef Vec3 a = Vec3(p1)
|
| 837 |
+
cdef Vec3 b = Vec3(p2)
|
| 838 |
+
return v3_lerp(a, b, factor)
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/api.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
# Public API module (interface)
|
| 4 |
+
"""
|
| 5 |
+
The main goals of this ACIS support library is:
|
| 6 |
+
|
| 7 |
+
1. load and parse simple and known ACIS data structures
|
| 8 |
+
2. create and export simple and known ACIS data structures
|
| 9 |
+
|
| 10 |
+
It is NOT a goal to edit and export arbitrary existing ACIS structures.
|
| 11 |
+
|
| 12 |
+
Don't even try it!
|
| 13 |
+
|
| 14 |
+
This modules do not implement an ACIS kernel!!!
|
| 15 |
+
So tasks beyond stitching some flat polygonal faces to a polyhedron or creating
|
| 16 |
+
simple curves is not possible.
|
| 17 |
+
|
| 18 |
+
To all beginners: GO AWAY!
|
| 19 |
+
|
| 20 |
+
"""
|
| 21 |
+
from .const import (
|
| 22 |
+
AcisException,
|
| 23 |
+
ParsingError,
|
| 24 |
+
InvalidLinkStructure,
|
| 25 |
+
ExportError,
|
| 26 |
+
)
|
| 27 |
+
from .mesh import mesh_from_body, body_from_mesh, vertices_from_body
|
| 28 |
+
from .entities import load, export_sat, export_sab, Body
|
| 29 |
+
from .dbg import AcisDebugger, dump_sab_as_text
|
| 30 |
+
from .dxf import export_dxf, load_dxf
|
| 31 |
+
from .cache import AcisCache
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/cache.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import TYPE_CHECKING, Sequence
|
| 5 |
+
from .entities import Body, load
|
| 6 |
+
from .type_hints import EncodedData
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from ezdxf.entities import DXFEntity
|
| 10 |
+
|
| 11 |
+
__all__ = ["AcisCache"]
|
| 12 |
+
NO_BODIES: Sequence[Body] = tuple()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class AcisCache:
|
| 16 |
+
"""This cache manages ACIS bodies created from SAT or SAB data stored in DXF
|
| 17 |
+
entities.
|
| 18 |
+
|
| 19 |
+
Each entry is a list of ACIS bodies and is indexed by a hash calculated from the
|
| 20 |
+
source content of the SAT or SAB data.
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
def __init__(self) -> None:
|
| 24 |
+
self._entries: dict[int, Sequence[Body]] = {}
|
| 25 |
+
self.hits: int = 0
|
| 26 |
+
self.misses: int = 0
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def hash_data(data: EncodedData) -> int:
|
| 30 |
+
if isinstance(data, list):
|
| 31 |
+
return hash(tuple(data))
|
| 32 |
+
elif isinstance(data, bytearray):
|
| 33 |
+
return hash(bytes(data))
|
| 34 |
+
return hash(data)
|
| 35 |
+
|
| 36 |
+
def __len__(self) -> int:
|
| 37 |
+
return len(self._entries)
|
| 38 |
+
|
| 39 |
+
def get_bodies(self, data: EncodedData) -> Sequence[Body]:
|
| 40 |
+
if not data:
|
| 41 |
+
return NO_BODIES
|
| 42 |
+
|
| 43 |
+
hash_value = AcisCache.hash_data(data)
|
| 44 |
+
bodies = self._entries.get(hash_value, NO_BODIES)
|
| 45 |
+
if bodies is not NO_BODIES:
|
| 46 |
+
self.hits += 1
|
| 47 |
+
return bodies
|
| 48 |
+
|
| 49 |
+
self.misses += 1
|
| 50 |
+
bodies = tuple(load(data))
|
| 51 |
+
self._entries[hash_value] = bodies
|
| 52 |
+
return bodies
|
| 53 |
+
|
| 54 |
+
def from_dxf_entity(self, entity: DXFEntity) -> Sequence[Body]:
|
| 55 |
+
from ezdxf.entities import Body as DxfBody
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
import enum
|
| 4 |
+
from ezdxf.version import __version__
|
| 5 |
+
|
| 6 |
+
# SAT Export Requirements for Autodesk Products
|
| 7 |
+
# ---------------------------------------------
|
| 8 |
+
# Script to create test files:
|
| 9 |
+
# examples/acistools/create_3dsolid_cube.py
|
| 10 |
+
|
| 11 |
+
# DXF R2000, R2004, R2007, R2010: OK, tested with TrueView 2022
|
| 12 |
+
# ACIS version 700
|
| 13 |
+
# ACIS version string: "ACIS 32.0 NT"
|
| 14 |
+
# record count: 0, not required
|
| 15 |
+
# body count: 1, required
|
| 16 |
+
# ASM header: no
|
| 17 |
+
# end-marker: "End-of-ACIS-data"
|
| 18 |
+
|
| 19 |
+
# DXF R2004, R2007, R2010: OK, tested with TrueView 2022
|
| 20 |
+
# ACIS version 20800
|
| 21 |
+
# ACIS version string: "ACIS 208.00 NT"
|
| 22 |
+
# record count: 0, not required
|
| 23 |
+
# body count: n + 1 (asm-header), required
|
| 24 |
+
# ASM header: "208.0.4.7009"
|
| 25 |
+
# end-marker: "End-of-ACIS-data"
|
| 26 |
+
|
| 27 |
+
# SAB Export Requirements for Autodesk Products
|
| 28 |
+
# ---------------------------------------------
|
| 29 |
+
# DXF R2013, R2018: OK, tested with TrueView 2022
|
| 30 |
+
# ACIS version 21800
|
| 31 |
+
# ACIS version string: "ACIS 208.00 NT"
|
| 32 |
+
# record count: 0, not required
|
| 33 |
+
# body count: n + 1 (asm-header), required
|
| 34 |
+
# ASM header: "208.0.4.7009"
|
| 35 |
+
# end-marker: "End-of-ASM-data"
|
| 36 |
+
|
| 37 |
+
ACIS_VERSION = {
|
| 38 |
+
400: "ACIS 4.00 NT", # DXF R2000, no asm header - only R2000
|
| 39 |
+
700: "ACIS 32.0 NT", # DXF R2000-R2010, no asm header
|
| 40 |
+
20800: "ACIS 208.00 NT", # DXF R2013 with asm-header, asm-end-marker
|
| 41 |
+
21800: "ACIS 218.00 NT", # DXF R2013 with asm-header, asm-end-marker
|
| 42 |
+
22300: "ACIS 223.00 NT", # DXF R2018 with asm-header, asm-end-marker
|
| 43 |
+
}
|
| 44 |
+
ASM_VERSION = {
|
| 45 |
+
20800: "208.0.4.7009", # DXF R2004, R2007, R2010
|
| 46 |
+
21800: "208.0.4.7009", # DXF R2013, default version for R2013 and R2018
|
| 47 |
+
22300: "222.0.0.1700", # DXF R2018
|
| 48 |
+
}
|
| 49 |
+
EZDXF_BUILDER_ID = f"ezdxf v{__version__} ACIS Builder"
|
| 50 |
+
MIN_EXPORT_VERSION = 700
|
| 51 |
+
|
| 52 |
+
# ACIS version 700 is the default version for DXF R2000, R2004, R2007 and R2010 (SAT)
|
| 53 |
+
# ACIS version 21800 is the default version for DXF R2013 and R2018 (SAB)
|
| 54 |
+
DEFAULT_SAT_VERSION = 700
|
| 55 |
+
DEFAULT_SAB_VERSION = 21800
|
| 56 |
+
|
| 57 |
+
DATE_FMT = "%a %b %d %H:%M:%S %Y"
|
| 58 |
+
END_OF_ACIS_DATA_SAT = "End-of-ACIS-data"
|
| 59 |
+
END_OF_ACIS_DATA_SAB = b"\x0e\x03End\x0e\x02of\x0e\x04ACIS\x0d\x04data"
|
| 60 |
+
END_OF_ASM_DATA_SAT = "End-of-ASM-data"
|
| 61 |
+
END_OF_ASM_DATA_SAB = b"\x0e\x03End\x0e\x02of\x0e\x03ASM\x0d\x04data"
|
| 62 |
+
BEGIN_OF_ACIS_HISTORY_DATA = "Begin-of-ACIS-History-data"
|
| 63 |
+
END_OF_ACIS_HISTORY_DATA = "End-of-ACIS-History-data"
|
| 64 |
+
DATA_END_MARKERS = (
|
| 65 |
+
END_OF_ACIS_DATA_SAT,
|
| 66 |
+
BEGIN_OF_ACIS_HISTORY_DATA,
|
| 67 |
+
END_OF_ASM_DATA_SAT,
|
| 68 |
+
)
|
| 69 |
+
NULL_PTR_NAME = "null-ptr"
|
| 70 |
+
NONE_ENTITY_NAME = "none-entity"
|
| 71 |
+
NOR_TOL = 1e-10
|
| 72 |
+
RES_TOL = 9.9999999999999995e-7
|
| 73 |
+
|
| 74 |
+
BOOL_SPECIFIER = {
|
| 75 |
+
"forward": True,
|
| 76 |
+
"forward_v": True,
|
| 77 |
+
"reversed": False,
|
| 78 |
+
"reversed_v": False,
|
| 79 |
+
"single": True,
|
| 80 |
+
"double": False,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
ACIS_SIGNATURE = b"ACIS BinaryFile" # DXF R2013/R2018
|
| 84 |
+
ASM_SIGNATURE = b"ASM BinaryFile4" # DXF R2018
|
| 85 |
+
SIGNATURES = [ACIS_SIGNATURE, ASM_SIGNATURE]
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def is_valid_export_version(version: int):
|
| 89 |
+
return version >= MIN_EXPORT_VERSION and version in ACIS_VERSION
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Tags(enum.IntEnum):
|
| 93 |
+
NO_TYPE = 0x00
|
| 94 |
+
BYTE = 0x01 # not used in files!
|
| 95 |
+
CHAR = 0x02 # not used in files!
|
| 96 |
+
SHORT = 0x03 # not used in files!
|
| 97 |
+
INT = 0x04 # 32-bit signed integer
|
| 98 |
+
FLOAT = 0x05 # not used in files!
|
| 99 |
+
DOUBLE = 0x06 # 64-bit double precision floating point value
|
| 100 |
+
STR = 0x07 # count is the following 8-bit uchar
|
| 101 |
+
STR2 = 0x08 # not used in files!
|
| 102 |
+
STR3 = 0x09 # not used in files!
|
| 103 |
+
|
| 104 |
+
# bool value for reversed, double, I - depends on context
|
| 105 |
+
BOOL_TRUE = 0x0A
|
| 106 |
+
|
| 107 |
+
# bool value forward, single, forward_v - depends on context
|
| 108 |
+
BOOL_FALSE = 0x0B
|
| 109 |
+
POINTER = 0x0C
|
| 110 |
+
ENTITY_TYPE = 0x0D
|
| 111 |
+
ENTITY_TYPE_EX = 0x0E
|
| 112 |
+
SUBTYPE_START = 0x0F
|
| 113 |
+
SUBTYPE_END = 0x10
|
| 114 |
+
RECORD_END = 0x11
|
| 115 |
+
LITERAL_STR = 0x12 # count ia a 32-bit uint, see transform entity
|
| 116 |
+
LOCATION_VEC = 0x13 # vector (3 doubles)
|
| 117 |
+
DIRECTION_VEC = 0x14 # vector (3 doubles)
|
| 118 |
+
|
| 119 |
+
# Enumeration are stored as strings in SAT and ints in SAB.
|
| 120 |
+
# It's not possible to translate SAT enums (strings) to SAB enums (int) and
|
| 121 |
+
# vice versa without knowing the implementation details. Each enumeration
|
| 122 |
+
# is specific to the class where it is used.
|
| 123 |
+
ENUM = 0x15
|
| 124 |
+
# 0x16: ???
|
| 125 |
+
UNKNOWN_0x17 = 0x17 # double
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# entity type structure:
|
| 129 |
+
# 0x0D 0x04 (char count of) "body" = SAT "body"
|
| 130 |
+
# 0x0E 0x05 "plane" 0x0D 0x07 "surface" = SAT "plane-surface"
|
| 131 |
+
# 0x0E 0x06 "ref_vt" 0x0E 0x03 "eye" 0x0D 0x06 "attrib" = SAT "ref_vt-eye-attrib"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class Flags(enum.IntFlag):
|
| 135 |
+
HAS_HISTORY = 1
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class AcisException(Exception):
|
| 139 |
+
pass
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class InvalidLinkStructure(AcisException):
|
| 143 |
+
pass
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class ParsingError(AcisException):
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class ExportError(AcisException):
|
| 151 |
+
pass
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class EndOfAcisData(AcisException):
|
| 155 |
+
pass
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
class Features:
|
| 159 |
+
LAW_SPL = 400
|
| 160 |
+
CONE_SCALING = 400
|
| 161 |
+
LOFT_LAW = 400
|
| 162 |
+
REF_MIN_UV_GRID = 400
|
| 163 |
+
VBLEND_AUTO = 400
|
| 164 |
+
BL_ENV_SF = 400
|
| 165 |
+
ELLIPSE_OFFSET = 500
|
| 166 |
+
TOL_MODELING = 500
|
| 167 |
+
APPROX_SUMMARY = 500
|
| 168 |
+
TAPER_SCALING = 500
|
| 169 |
+
LAZY_B_SPLINE = 500
|
| 170 |
+
DM_MULTI_SURF = 500
|
| 171 |
+
GA_COPY_ACTION = 600
|
| 172 |
+
DM_MULTI_SURF_COLOR = 600
|
| 173 |
+
RECAL_SKIN_ERROR = 520
|
| 174 |
+
TAPER_U_RULED = 600
|
| 175 |
+
DM_60 = 600
|
| 176 |
+
LOFT_PCURVE = 600
|
| 177 |
+
EELIST_OWNER = 600
|
| 178 |
+
ANNO_HOOKED = 700
|
| 179 |
+
PATTERN = 700
|
| 180 |
+
ENTITY_TAGS = 700
|
| 181 |
+
AT = 700
|
| 182 |
+
NET_LAW = 700
|
| 183 |
+
STRINGLESS_HISTORY = 700
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/dbg.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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typing import Iterator, Callable, Any
|
| 5 |
+
from .entities import (
|
| 6 |
+
AcisEntity,
|
| 7 |
+
NONE_REF,
|
| 8 |
+
Face,
|
| 9 |
+
Coedge,
|
| 10 |
+
Loop,
|
| 11 |
+
Vertex,
|
| 12 |
+
)
|
| 13 |
+
from . import sab
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AcisDebugger:
|
| 17 |
+
def __init__(self, root: AcisEntity = NONE_REF, start_id: int = 1):
|
| 18 |
+
self._next_id = start_id - 1
|
| 19 |
+
self._root: AcisEntity = root
|
| 20 |
+
self.entities: dict[int, AcisEntity] = dict()
|
| 21 |
+
if not root.is_none:
|
| 22 |
+
self._store_entities(root)
|
| 23 |
+
|
| 24 |
+
@property
|
| 25 |
+
def root(self) -> AcisEntity:
|
| 26 |
+
return self._root
|
| 27 |
+
|
| 28 |
+
def _get_id(self) -> int:
|
| 29 |
+
self._next_id += 1
|
| 30 |
+
return self._next_id
|
| 31 |
+
|
| 32 |
+
def _store_entities(self, entity: AcisEntity) -> None:
|
| 33 |
+
if not entity.is_none and entity.id == -1:
|
| 34 |
+
entity.id = self._get_id()
|
| 35 |
+
self.entities[entity.id] = entity
|
| 36 |
+
for e in vars(entity).values():
|
| 37 |
+
if isinstance(e, AcisEntity) and e.id == -1:
|
| 38 |
+
self._store_entities(e)
|
| 39 |
+
|
| 40 |
+
def set_entities(self, entity: AcisEntity) -> None:
|
| 41 |
+
self.entities.clear()
|
| 42 |
+
self._root = entity
|
| 43 |
+
self._store_entities(entity)
|
| 44 |
+
|
| 45 |
+
def walk(self, root: AcisEntity = NONE_REF) -> Iterator[AcisEntity]:
|
| 46 |
+
def _walk(entity: AcisEntity):
|
| 47 |
+
if entity.is_none:
|
| 48 |
+
return
|
| 49 |
+
yield entity
|
| 50 |
+
done.add(entity.id)
|
| 51 |
+
for e in vars(entity).values():
|
| 52 |
+
if isinstance(e, AcisEntity) and e.id not in done:
|
| 53 |
+
yield from _walk(e)
|
| 54 |
+
|
| 55 |
+
if root.is_none:
|
| 56 |
+
root = self._root
|
| 57 |
+
done: set[int] = set()
|
| 58 |
+
yield from _walk(root)
|
| 59 |
+
|
| 60 |
+
def filter(
|
| 61 |
+
self, func: Callable[[AcisEntity], bool], entity: AcisEntity = NONE_REF
|
| 62 |
+
) -> Iterator[Any]:
|
| 63 |
+
if entity.is_none:
|
| 64 |
+
entity = self._root
|
| 65 |
+
yield from filter(func, self.walk(entity))
|
| 66 |
+
|
| 67 |
+
def filter_type(
|
| 68 |
+
self, name: str, entity: AcisEntity = NONE_REF
|
| 69 |
+
) -> Iterator[Any]:
|
| 70 |
+
if entity.is_none:
|
| 71 |
+
entity = self._root
|
| 72 |
+
yield from filter(lambda x: x.type == name, self.walk(entity))
|
| 73 |
+
|
| 74 |
+
@staticmethod
|
| 75 |
+
def entity_attributes(entity: AcisEntity, indent: int = 0) -> Iterator[str]:
|
| 76 |
+
indent_str = " " * indent
|
| 77 |
+
for name, data in vars(entity).items():
|
| 78 |
+
if name == "id":
|
| 79 |
+
continue
|
| 80 |
+
yield f"{indent_str}{name}: {data}"
|
| 81 |
+
|
| 82 |
+
def face_link_structure(self, face: Face, indent: int = 0) -> Iterator[str]:
|
| 83 |
+
indent_str = " " * indent
|
| 84 |
+
|
| 85 |
+
while not face.is_none:
|
| 86 |
+
partner_faces = list(self.partner_faces(face))
|
| 87 |
+
error = ""
|
| 88 |
+
linked_partner_faces = []
|
| 89 |
+
unlinked_partner_faces = []
|
| 90 |
+
for pface_id in partner_faces:
|
| 91 |
+
pface = self.entities.get(pface_id)
|
| 92 |
+
if pface is None:
|
| 93 |
+
error += f" face {pface_id} does not exist;"
|
| 94 |
+
if isinstance(pface, Face):
|
| 95 |
+
reverse_faces = self.partner_faces(pface)
|
| 96 |
+
if face.id in reverse_faces:
|
| 97 |
+
linked_partner_faces.append(pface_id)
|
| 98 |
+
else:
|
| 99 |
+
unlinked_partner_faces.append(pface_id)
|
| 100 |
+
else:
|
| 101 |
+
error += f" entity {pface_id} is not a face;"
|
| 102 |
+
if unlinked_partner_faces:
|
| 103 |
+
error = f"unlinked partner faces: {unlinked_partner_faces} {error}"
|
| 104 |
+
yield f"{indent_str}{str(face)} >> {partner_faces} {error}"
|
| 105 |
+
face = face.next_face
|
| 106 |
+
|
| 107 |
+
@staticmethod
|
| 108 |
+
def partner_faces(face: Face) -> Iterator[int]:
|
| 109 |
+
coedges: list[Coedge] = []
|
| 110 |
+
loop = face.loop
|
| 111 |
+
while not loop.is_none:
|
| 112 |
+
coedges.extend(co for co in loop.coedges())
|
| 113 |
+
loop = loop.next_loop
|
| 114 |
+
for coedge in coedges:
|
| 115 |
+
for partner_coedge in coedge.partner_coedges():
|
| 116 |
+
yield partner_coedge.loop.face.id
|
| 117 |
+
|
| 118 |
+
@staticmethod
|
| 119 |
+
def coedge_structure(face: Face, ident: int = 4) -> list[str]:
|
| 120 |
+
lines: list[str] = []
|
| 121 |
+
coedges: list[Coedge] = []
|
| 122 |
+
loop = face.loop
|
| 123 |
+
|
| 124 |
+
while not loop.is_none:
|
| 125 |
+
coedges.extend(co for co in loop.coedges())
|
| 126 |
+
loop = loop.next_loop
|
| 127 |
+
for coedge in coedges:
|
| 128 |
+
edge1 = coedge.edge
|
| 129 |
+
sense1 = coedge.sense
|
| 130 |
+
lines.append(f"Coedge={coedge.id} edge={edge1.id} sense={sense1}")
|
| 131 |
+
for partner_coedge in coedge.partner_coedges():
|
| 132 |
+
edge2 = partner_coedge.edge
|
| 133 |
+
sense2 = partner_coedge.sense
|
| 134 |
+
lines.append(
|
| 135 |
+
f" Partner Coedge={partner_coedge.id} edge={edge2.id} sense={sense2}"
|
| 136 |
+
)
|
| 137 |
+
ident_str = " " * ident
|
| 138 |
+
return [ident_str + line for line in lines]
|
| 139 |
+
|
| 140 |
+
@staticmethod
|
| 141 |
+
def loop_vertices(loop: Loop, indent: int = 0) -> str:
|
| 142 |
+
indent_str = " " * indent
|
| 143 |
+
return f"{indent_str}{loop} >> {list(AcisDebugger.loop_edges(loop))}"
|
| 144 |
+
|
| 145 |
+
@staticmethod
|
| 146 |
+
def loop_edges(loop: Loop) -> Iterator[list[int]]:
|
| 147 |
+
coedge = loop.coedge
|
| 148 |
+
first = coedge
|
| 149 |
+
while not coedge.is_none:
|
| 150 |
+
edge = coedge.edge
|
| 151 |
+
sv = edge.start_vertex
|
| 152 |
+
ev = edge.end_vertex
|
| 153 |
+
if coedge.sense:
|
| 154 |
+
yield [ev.id, sv.id]
|
| 155 |
+
else:
|
| 156 |
+
yield [sv.id, ev.id]
|
| 157 |
+
coedge = coedge.next_coedge
|
| 158 |
+
if coedge is first:
|
| 159 |
+
break
|
| 160 |
+
|
| 161 |
+
def vertex_to_edge_relation(self) -> Iterator[str]:
|
| 162 |
+
for vertex in (
|
| 163 |
+
e for e in self.entities.values() if isinstance(e, Vertex)
|
| 164 |
+
):
|
| 165 |
+
edge = vertex.edge
|
| 166 |
+
sv = edge.start_vertex
|
| 167 |
+
ev = edge.end_vertex
|
| 168 |
+
yield f"{vertex}: parent edge is {edge.id}; {sv.id} => {ev.id}; {edge.curve}"
|
| 169 |
+
|
| 170 |
+
def is_manifold(self) -> bool:
|
| 171 |
+
for coedge in self.filter_type("coedge"):
|
| 172 |
+
if len(coedge.partner_coedges()) > 1:
|
| 173 |
+
return False
|
| 174 |
+
return True
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def dump_sab_as_text(data: bytes) -> Iterator[str]:
|
| 178 |
+
def entity_data(e):
|
| 179 |
+
for tag, value in e:
|
| 180 |
+
name = sab.Tags(tag).name
|
| 181 |
+
yield f"{name} = {value}"
|
| 182 |
+
|
| 183 |
+
decoder = sab.Decoder(data)
|
| 184 |
+
header = decoder.read_header()
|
| 185 |
+
yield from header.dumps()
|
| 186 |
+
index = 0
|
| 187 |
+
try:
|
| 188 |
+
for record in decoder.read_records():
|
| 189 |
+
yield f"--------------------- record: {index}"
|
| 190 |
+
yield from entity_data(record)
|
| 191 |
+
index += 1
|
| 192 |
+
except sab.ParsingError as e:
|
| 193 |
+
yield str(e)
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/dxf.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import cast, Sequence
|
| 5 |
+
from ezdxf.entities import DXFEntity, Body as DXFBody
|
| 6 |
+
from ezdxf.lldxf import const
|
| 7 |
+
from .entities import Body, export_sat, export_sab, load
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def export_dxf(entity: DXFEntity, bodies: Sequence[Body]):
|
| 11 |
+
"""Store the :term:`ACIS` bodies in the given DXF entity. This is the
|
| 12 |
+
recommended way to set ACIS data of DXF entities.
|
| 13 |
+
|
| 14 |
+
The DXF entity has to be an ACIS based entity and inherit from
|
| 15 |
+
:class:`ezdxf.entities.Body`. The entity has to be bound to a valid DXF
|
| 16 |
+
document and the DXF version of the document has to be DXF R2000 or newer.
|
| 17 |
+
|
| 18 |
+
Raises:
|
| 19 |
+
DXFTypeError: invalid DXF entity type
|
| 20 |
+
DXFValueError: invalid DXF document
|
| 21 |
+
DXFVersionError: invalid DXF version
|
| 22 |
+
|
| 23 |
+
"""
|
| 24 |
+
if not isinstance(entity, DXFBody):
|
| 25 |
+
raise const.DXFTypeError(f"invalid DXF entity {entity.dxftype()}")
|
| 26 |
+
body = cast(DXFBody, entity)
|
| 27 |
+
doc = entity.doc
|
| 28 |
+
if doc is None:
|
| 29 |
+
raise const.DXFValueError("a valid DXF document is required")
|
| 30 |
+
dxfversion = doc.dxfversion
|
| 31 |
+
if dxfversion < const.DXF2000:
|
| 32 |
+
raise const.DXFVersionError(f"invalid DXF version {dxfversion}")
|
| 33 |
+
|
| 34 |
+
if dxfversion < const.DXF2013:
|
| 35 |
+
body.sat = export_sat(bodies)
|
| 36 |
+
else:
|
| 37 |
+
body.sab = export_sab(bodies)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_dxf(entity: DXFEntity) -> list[Body]:
|
| 41 |
+
"""Load the :term:`ACIS` bodies from the given DXF entity. This is the
|
| 42 |
+
recommended way to load ACIS data.
|
| 43 |
+
|
| 44 |
+
The DXF entity has to be an ACIS based entity and inherit from
|
| 45 |
+
:class:`ezdxf.entities.Body`. The entity has to be bound to a valid DXF
|
| 46 |
+
document and the DXF version of the document has to be DXF R2000 or newer.
|
| 47 |
+
|
| 48 |
+
Raises:
|
| 49 |
+
DXFTypeError: invalid DXF entity type
|
| 50 |
+
DXFValueError: invalid DXF document
|
| 51 |
+
DXFVersionError: invalid DXF version
|
| 52 |
+
|
| 53 |
+
.. warning::
|
| 54 |
+
|
| 55 |
+
Only a limited count of :term:`ACIS` entities is supported, all
|
| 56 |
+
unsupported entities are loaded as ``NONE_ENTITY`` and their data is
|
| 57 |
+
lost. Exporting such ``NONE_ENTITIES`` will raise an :class:`ExportError`
|
| 58 |
+
exception.
|
| 59 |
+
|
| 60 |
+
To emphasize that again: **It is not possible to load and re-export
|
| 61 |
+
arbitrary ACIS data!**
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
if not isinstance(entity, DXFBody):
|
| 66 |
+
raise const.DXFTypeError(f"invalid DXF entity {entity.dxftype()}")
|
| 67 |
+
body = cast(DXFBody, entity)
|
| 68 |
+
doc = entity.doc
|
| 69 |
+
if doc is None:
|
| 70 |
+
raise const.DXFValueError("a valid DXF document is required")
|
| 71 |
+
dxfversion = doc.dxfversion
|
| 72 |
+
if dxfversion < const.DXF2000:
|
| 73 |
+
raise const.DXFVersionError(f"invalid DXF version {dxfversion}")
|
| 74 |
+
if body.has_binary_data:
|
| 75 |
+
binary_data = body.sab
|
| 76 |
+
if binary_data:
|
| 77 |
+
return load(binary_data)
|
| 78 |
+
else:
|
| 79 |
+
text = body.sat
|
| 80 |
+
if text:
|
| 81 |
+
return load(text)
|
| 82 |
+
return []
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/hdr.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import struct
|
| 7 |
+
from . import const
|
| 8 |
+
|
| 9 |
+
# ACIS versions exported by BricsCAD:
|
| 10 |
+
# R2000/AC1015: 400, "ACIS 4.00 NT", text length has no prefix "@"
|
| 11 |
+
# R2004/AC1018: 20800 @ "ACIS 208.00 NT", text length has "@" prefix ??? weird
|
| 12 |
+
# R2007/AC1021: 700 @ "ACIS 32.0 NT", text length has "@" prefix
|
| 13 |
+
# R2010/AC1024: 700 @ "ACIS 32.0 NT", text length has "@" prefix
|
| 14 |
+
|
| 15 |
+
# A test showed that R2000 files that contains ACIS v700/32.0 or v20800/208.0
|
| 16 |
+
# data can be opened by Autodesk TrueView, BricsCAD and Allplan, so exporting
|
| 17 |
+
# only v700/32.0 for all DXF versions should be OK!
|
| 18 |
+
# test script: exploration/acis/transplant_acis_data.py
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def encode_str(s: str) -> bytes:
|
| 22 |
+
b = s.encode("utf8", errors="ignore")
|
| 23 |
+
return struct.pack("<BB", const.Tags.STR, len(b)) + b
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def encode_double(value: float) -> bytes:
|
| 27 |
+
return struct.pack("<Bd", const.Tags.DOUBLE, value)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass
|
| 31 |
+
class AcisHeader:
|
| 32 |
+
"""Represents an ACIS file header."""
|
| 33 |
+
|
| 34 |
+
version: int = const.MIN_EXPORT_VERSION
|
| 35 |
+
n_records: int = 0 # can be 0
|
| 36 |
+
n_entities: int = 0
|
| 37 |
+
flags: int = 0
|
| 38 |
+
product_id: str = const.EZDXF_BUILDER_ID
|
| 39 |
+
acis_version: str = const.ACIS_VERSION[const.MIN_EXPORT_VERSION]
|
| 40 |
+
creation_date: datetime = field(default_factory=datetime.now)
|
| 41 |
+
units_in_mm: float = 1.0
|
| 42 |
+
asm_version: str = ""
|
| 43 |
+
asm_end_marker: bool = False # depends on DXF version: R2013, RT2018
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def has_asm_header(self) -> bool:
|
| 47 |
+
return self.asm_version != ""
|
| 48 |
+
|
| 49 |
+
def dumps(self) -> list[str]:
|
| 50 |
+
"""Returns the SAT file header as list of strings."""
|
| 51 |
+
return [
|
| 52 |
+
f"{self.version} {self.n_records} {self.n_entities} {self.flags} ",
|
| 53 |
+
self._header_str(),
|
| 54 |
+
f"{self.units_in_mm:g} 9.9999999999999995e-007 1e-010 ",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
def dumpb(self) -> bytes:
|
| 58 |
+
"""Returns the SAB file header as bytes."""
|
| 59 |
+
buffer: list[bytes] = []
|
| 60 |
+
if self.version > 21800:
|
| 61 |
+
buffer.append(const.ASM_SIGNATURE)
|
| 62 |
+
else:
|
| 63 |
+
buffer.append(const.ACIS_SIGNATURE)
|
| 64 |
+
data = struct.pack(
|
| 65 |
+
"<iiii", self.version, self.n_records, self.n_entities, self.flags
|
| 66 |
+
)
|
| 67 |
+
buffer.append(data)
|
| 68 |
+
buffer.append(encode_str(self.product_id))
|
| 69 |
+
buffer.append(encode_str(self.acis_version))
|
| 70 |
+
buffer.append(encode_str(self.creation_date.ctime()))
|
| 71 |
+
buffer.append(encode_double(self.units_in_mm))
|
| 72 |
+
buffer.append(encode_double(const.RES_TOL))
|
| 73 |
+
buffer.append(encode_double(const.NOR_TOL))
|
| 74 |
+
return b"".join(buffer)
|
| 75 |
+
|
| 76 |
+
def _header_str(self) -> str:
|
| 77 |
+
p_len = len(self.product_id)
|
| 78 |
+
a_len = len(self.acis_version)
|
| 79 |
+
date = self.creation_date.ctime()
|
| 80 |
+
if self.version > 400:
|
| 81 |
+
return f"@{p_len} {self.product_id} @{a_len} {self.acis_version} @{len(date)} {date} "
|
| 82 |
+
else:
|
| 83 |
+
return f"{p_len} {self.product_id} {a_len} {self.acis_version} {len(date)} {date} "
|
| 84 |
+
|
| 85 |
+
def set_version(self, version: int) -> None:
|
| 86 |
+
"""Sets the ACIS version as an integer value and updates the version
|
| 87 |
+
string accordingly.
|
| 88 |
+
"""
|
| 89 |
+
try:
|
| 90 |
+
self.acis_version = const.ACIS_VERSION[version]
|
| 91 |
+
self.version = version
|
| 92 |
+
except KeyError:
|
| 93 |
+
raise ValueError(f"invalid ACIS version number {version}")
|
| 94 |
+
self.asm_version = const.ASM_VERSION.get(version, "")
|
| 95 |
+
|
| 96 |
+
def asm_header(self):
|
| 97 |
+
from .entities import AsmHeader
|
| 98 |
+
return AsmHeader(self.asm_version)
|
| 99 |
+
|
| 100 |
+
def sat_end_marker(self) -> str:
|
| 101 |
+
if self.asm_end_marker:
|
| 102 |
+
return const.END_OF_ASM_DATA_SAT + " "
|
| 103 |
+
else:
|
| 104 |
+
return const.END_OF_ACIS_DATA_SAT + " "
|
| 105 |
+
|
| 106 |
+
def sab_end_marker(self) -> bytes:
|
| 107 |
+
if self.asm_end_marker:
|
| 108 |
+
return const.END_OF_ASM_DATA_SAB
|
| 109 |
+
else:
|
| 110 |
+
return const.END_OF_ACIS_DATA_SAB
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/mesh.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import Iterator, Sequence, Optional, Iterable
|
| 5 |
+
from ezdxf.render import MeshVertexMerger, MeshTransformer, MeshBuilder
|
| 6 |
+
from ezdxf.math import Matrix44, Vec3, NULLVEC, BoundingBox
|
| 7 |
+
from . import entities
|
| 8 |
+
from .entities import Body, Lump, NONE_REF, Face, Shell
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def mesh_from_body(body: Body, merge_lumps=True) -> list[MeshTransformer]:
|
| 12 |
+
"""Returns a list of :class:`~ezdxf.render.MeshTransformer` instances from
|
| 13 |
+
the given ACIS :class:`Body` entity.
|
| 14 |
+
The list contains multiple meshes if `merge_lumps` is ``False`` or just a
|
| 15 |
+
single mesh if `merge_lumps` is ``True``.
|
| 16 |
+
|
| 17 |
+
The ACIS format stores the faces in counter-clockwise orientation where the
|
| 18 |
+
face-normal points outwards (away) from the solid body (material).
|
| 19 |
+
|
| 20 |
+
.. note::
|
| 21 |
+
|
| 22 |
+
This function returns meshes build up only from flat polygonal
|
| 23 |
+
:class:`Face` entities, for a tessellation of more complex ACIS
|
| 24 |
+
entities (spline surfaces, tori, cones, ...) is an ACIS kernel
|
| 25 |
+
required which `ezdxf` does not provide.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
body: ACIS entity of type :class:`Body`
|
| 29 |
+
merge_lumps: returns all :class:`Lump` entities
|
| 30 |
+
from a body as a single mesh if ``True`` otherwise each :class:`Lump`
|
| 31 |
+
entity is a separated mesh
|
| 32 |
+
|
| 33 |
+
Raises:
|
| 34 |
+
TypeError: given `body` entity has invalid type
|
| 35 |
+
|
| 36 |
+
"""
|
| 37 |
+
if not isinstance(body, Body):
|
| 38 |
+
raise TypeError(f"expected a body entity, got: {type(body)}")
|
| 39 |
+
|
| 40 |
+
meshes: list[MeshTransformer] = []
|
| 41 |
+
builder = MeshVertexMerger()
|
| 42 |
+
for faces in flat_polygon_faces_from_body(body):
|
| 43 |
+
for face in faces:
|
| 44 |
+
builder.add_face(face)
|
| 45 |
+
if not merge_lumps:
|
| 46 |
+
meshes.append(MeshTransformer.from_builder(builder))
|
| 47 |
+
builder = MeshVertexMerger()
|
| 48 |
+
if merge_lumps:
|
| 49 |
+
meshes.append(MeshTransformer.from_builder(builder))
|
| 50 |
+
return meshes
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def flat_polygon_faces_from_body(
|
| 54 |
+
body: Body,
|
| 55 |
+
) -> Iterator[list[Sequence[Vec3]]]:
|
| 56 |
+
"""Yields all flat polygon faces from all lumps in the given
|
| 57 |
+
:class:`Body` entity.
|
| 58 |
+
Yields a separated list of faces for each linked :class:`Lump` entity.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
body: ACIS entity of type :class:`Body`
|
| 62 |
+
|
| 63 |
+
Raises:
|
| 64 |
+
TypeError: given `body` entity has invalid type
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if not isinstance(body, Body):
|
| 69 |
+
raise TypeError(f"expected a body entity, got: {type(body)}")
|
| 70 |
+
lump = body.lump
|
| 71 |
+
transform = body.transform
|
| 72 |
+
|
| 73 |
+
m: Optional[Matrix44] = None
|
| 74 |
+
if not transform.is_none:
|
| 75 |
+
m = transform.matrix
|
| 76 |
+
while not lump.is_none:
|
| 77 |
+
yield list(flat_polygon_faces_from_lump(lump, m))
|
| 78 |
+
lump = lump.next_lump
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def flat_polygon_faces_from_lump(
|
| 82 |
+
lump: Lump, m: Matrix44 | None = None
|
| 83 |
+
) -> Iterator[Sequence[Vec3]]:
|
| 84 |
+
"""Yields all flat polygon faces from the given :class:`Lump` entity as
|
| 85 |
+
sequence of :class:`~ezdxf.math.Vec3` instances. Applies the transformation
|
| 86 |
+
:class:`~ezdxf.math.Matrix44` `m` to all vertices if not ``None``.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
lump: :class:`Lump` entity
|
| 90 |
+
m: optional transformation matrix
|
| 91 |
+
|
| 92 |
+
Raises:
|
| 93 |
+
TypeError: `lump` has invalid ACIS type
|
| 94 |
+
|
| 95 |
+
"""
|
| 96 |
+
if not isinstance(lump, Lump):
|
| 97 |
+
raise TypeError(f"expected a lump entity, got: {type(lump)}")
|
| 98 |
+
|
| 99 |
+
shell = lump.shell
|
| 100 |
+
if shell.is_none:
|
| 101 |
+
return # not a shell
|
| 102 |
+
vertices: list[Vec3] = []
|
| 103 |
+
face = shell.face
|
| 104 |
+
while not face.is_none:
|
| 105 |
+
first_coedge = NONE_REF
|
| 106 |
+
vertices.clear()
|
| 107 |
+
if face.surface.type == "plane-surface":
|
| 108 |
+
try:
|
| 109 |
+
first_coedge = face.loop.coedge
|
| 110 |
+
except AttributeError: # loop is a none-entity
|
| 111 |
+
pass
|
| 112 |
+
coedge = first_coedge
|
| 113 |
+
while not coedge.is_none: # invalid coedge or face is not closed
|
| 114 |
+
# the edge entity contains the vertices and the curve type
|
| 115 |
+
edge = coedge.edge
|
| 116 |
+
try:
|
| 117 |
+
# only straight lines as face edges supported:
|
| 118 |
+
if edge.curve.type != "straight-curve":
|
| 119 |
+
break
|
| 120 |
+
# add the first edge vertex to the face vertices
|
| 121 |
+
if coedge.sense: # reversed sense of the underlying edge
|
| 122 |
+
vertices.append(edge.end_vertex.point.location)
|
| 123 |
+
else: # same sense as the underlying edge
|
| 124 |
+
vertices.append(edge.start_vertex.point.location)
|
| 125 |
+
except AttributeError:
|
| 126 |
+
# one of the involved entities is a none-entity or an
|
| 127 |
+
# incompatible entity type -> ignore this face!
|
| 128 |
+
break
|
| 129 |
+
coedge = coedge.next_coedge
|
| 130 |
+
if coedge is first_coedge: # a valid closed face
|
| 131 |
+
if m is not None:
|
| 132 |
+
yield tuple(m.transform_vertices(vertices))
|
| 133 |
+
else:
|
| 134 |
+
yield tuple(vertices)
|
| 135 |
+
break
|
| 136 |
+
face = face.next_face
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def body_from_mesh(mesh: MeshBuilder, precision: int = 6) -> Body:
|
| 140 |
+
"""Returns a :term:`ACIS` :class:`~ezdxf.acis.entities.Body` entity from a
|
| 141 |
+
:class:`~ezdxf.render.MeshBuilder` instance.
|
| 142 |
+
|
| 143 |
+
This entity can be assigned to a :class:`~ezdxf.entities.Solid3d` DXF entity
|
| 144 |
+
as :term:`SAT` or :term:`SAB` data according to the version your DXF
|
| 145 |
+
document uses (SAT for DXF R2000 to R2010 and SAB for DXF R2013 and later).
|
| 146 |
+
|
| 147 |
+
If the `mesh` contains multiple separated meshes, each mesh will be a
|
| 148 |
+
separated :class:`~ezdxf.acis.entities.Lump` node.
|
| 149 |
+
If each mesh should get its own :class:`~ezdxf.acis.entities.Body` entity,
|
| 150 |
+
separate the meshes beforehand by the method
|
| 151 |
+
:meth:`~ezdxf.render.MeshBuilder.separate_meshes`.
|
| 152 |
+
|
| 153 |
+
A closed mesh creates a solid body and an open mesh creates an open (hollow)
|
| 154 |
+
shell. The detection if the mesh is open or closed is based on the edges
|
| 155 |
+
of the mesh: if **all** edges of mesh have two adjacent faces the mesh is
|
| 156 |
+
closed.
|
| 157 |
+
|
| 158 |
+
The current implementation applies automatically a vertex optimization,
|
| 159 |
+
which merges coincident vertices into a single vertex.
|
| 160 |
+
|
| 161 |
+
"""
|
| 162 |
+
mesh = mesh.optimize_vertices(precision)
|
| 163 |
+
body = Body()
|
| 164 |
+
bbox = BoundingBox(mesh.vertices)
|
| 165 |
+
if not bbox.center.is_null:
|
| 166 |
+
mesh.translate(-bbox.center)
|
| 167 |
+
transform = entities.Transform()
|
| 168 |
+
transform.matrix = Matrix44.translate(*bbox.center)
|
| 169 |
+
body.transform = transform
|
| 170 |
+
|
| 171 |
+
for mesh in mesh.separate_meshes():
|
| 172 |
+
lump = lump_from_mesh(mesh)
|
| 173 |
+
body.append_lump(lump)
|
| 174 |
+
return body
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def lump_from_mesh(mesh: MeshBuilder) -> Lump:
|
| 178 |
+
"""Returns a :class:`~ezdxf.acis.entities.Lump` entity from a
|
| 179 |
+
:class:`~ezdxf.render.MeshBuilder` instance. The `mesh` has to be a single
|
| 180 |
+
body or shell!
|
| 181 |
+
"""
|
| 182 |
+
lump = Lump()
|
| 183 |
+
shell = Shell()
|
| 184 |
+
lump.append_shell(shell)
|
| 185 |
+
face_builder = PolyhedronFaceBuilder(mesh)
|
| 186 |
+
for face in face_builder.acis_faces():
|
| 187 |
+
shell.append_face(face)
|
| 188 |
+
return lump
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class PolyhedronFaceBuilder:
|
| 192 |
+
def __init__(self, mesh: MeshBuilder):
|
| 193 |
+
mesh_copy = mesh.copy()
|
| 194 |
+
mesh_copy.normalize_faces() # open faces without duplicates!
|
| 195 |
+
self.vertices: list[Vec3] = mesh_copy.vertices
|
| 196 |
+
self.faces: list[Sequence[int]] = mesh_copy.faces
|
| 197 |
+
self.normals = list(mesh_copy.face_normals())
|
| 198 |
+
self.acis_vertices: list[entities.Vertex] = []
|
| 199 |
+
|
| 200 |
+
# double_sided:
|
| 201 |
+
# If every edge belongs to two faces the body is for sure a closed
|
| 202 |
+
# surface. But the "is_edge_balance_broken" property can not detect
|
| 203 |
+
# non-manifold meshes!
|
| 204 |
+
# - True: the body is an open shell, each side of the face is outside
|
| 205 |
+
# (environment side)
|
| 206 |
+
# - False: the body is a closed solid body, one side points outwards of
|
| 207 |
+
# the body (environment side) and one side points inwards (material
|
| 208 |
+
# side)
|
| 209 |
+
self.double_sided = mesh_copy.diagnose().is_edge_balance_broken
|
| 210 |
+
|
| 211 |
+
# coedges and edges ledger, where index1 <= index2
|
| 212 |
+
self.partner_coedges: dict[tuple[int, int], entities.Coedge] = dict()
|
| 213 |
+
self.edges: dict[tuple[int, int], entities.Edge] = dict()
|
| 214 |
+
|
| 215 |
+
def reset(self):
|
| 216 |
+
self.acis_vertices = list(make_vertices(self.vertices))
|
| 217 |
+
self.partner_coedges.clear()
|
| 218 |
+
self.edges.clear()
|
| 219 |
+
|
| 220 |
+
def acis_faces(self) -> list[Face]:
|
| 221 |
+
self.reset()
|
| 222 |
+
faces: list[Face] = []
|
| 223 |
+
for face, face_normal in zip(self.faces, self.normals):
|
| 224 |
+
if face_normal.is_null:
|
| 225 |
+
continue
|
| 226 |
+
acis_face = Face()
|
| 227 |
+
plane = self.make_plane(face)
|
| 228 |
+
if plane is None:
|
| 229 |
+
continue
|
| 230 |
+
plane.normal = face_normal
|
| 231 |
+
loop = self.make_loop(face)
|
| 232 |
+
if loop is None:
|
| 233 |
+
continue
|
| 234 |
+
acis_face.append_loop(loop)
|
| 235 |
+
acis_face.surface = plane
|
| 236 |
+
acis_face.sense = False # face normal is plane normal
|
| 237 |
+
acis_face.double_sided = self.double_sided
|
| 238 |
+
faces.append(acis_face)
|
| 239 |
+
# The link structure of all entities is only completed at the end of
|
| 240 |
+
# the building process. Do not yield faces from the body of the loop!
|
| 241 |
+
return faces
|
| 242 |
+
|
| 243 |
+
def make_plane(self, face: Sequence[int]) -> Optional[entities.Plane]:
|
| 244 |
+
assert len(face) > 1, "face requires least 2 vertices"
|
| 245 |
+
plane = entities.Plane()
|
| 246 |
+
# normal is always calculated by the right-hand rule:
|
| 247 |
+
plane.reverse_v = False
|
| 248 |
+
plane.origin = self.vertices[face[0]]
|
| 249 |
+
try:
|
| 250 |
+
plane.u_dir = (self.vertices[face[1]] - plane.origin).normalize()
|
| 251 |
+
except ZeroDivisionError:
|
| 252 |
+
return None # vertices are too close together
|
| 253 |
+
return plane
|
| 254 |
+
|
| 255 |
+
def make_loop(self, face: Sequence[int]) -> Optional[entities.Loop]:
|
| 256 |
+
coedges: list[entities.Coedge] = []
|
| 257 |
+
face2 = list(face[1:])
|
| 258 |
+
if face[0] != face[-1]:
|
| 259 |
+
face2.append(face[0])
|
| 260 |
+
|
| 261 |
+
for i1, i2 in zip(face, face2):
|
| 262 |
+
coedge = self.make_coedge(i1, i2)
|
| 263 |
+
coedge.edge, coedge.sense = self.make_edge(i1, i2, coedge)
|
| 264 |
+
coedges.append(coedge)
|
| 265 |
+
loop = entities.Loop()
|
| 266 |
+
loop.set_coedges(coedges, close=True)
|
| 267 |
+
return loop
|
| 268 |
+
|
| 269 |
+
def make_coedge(self, index1: int, index2: int) -> entities.Coedge:
|
| 270 |
+
if index1 > index2:
|
| 271 |
+
key = index2, index1
|
| 272 |
+
else:
|
| 273 |
+
key = index1, index2
|
| 274 |
+
coedge = entities.Coedge()
|
| 275 |
+
try:
|
| 276 |
+
partner_coedge = self.partner_coedges[key]
|
| 277 |
+
except KeyError:
|
| 278 |
+
self.partner_coedges[key] = coedge
|
| 279 |
+
else:
|
| 280 |
+
partner_coedge.add_partner_coedge(coedge)
|
| 281 |
+
return coedge
|
| 282 |
+
|
| 283 |
+
def make_edge(
|
| 284 |
+
self, index1: int, index2: int, parent: entities.Coedge
|
| 285 |
+
) -> tuple[entities.Edge, bool]:
|
| 286 |
+
def make_vertex(index: int):
|
| 287 |
+
vertex = self.acis_vertices[index]
|
| 288 |
+
vertex.ref_count += 1
|
| 289 |
+
# assign first edge which references the vertex as parent edge (?):
|
| 290 |
+
if vertex.edge.is_none:
|
| 291 |
+
vertex.edge = edge
|
| 292 |
+
return vertex
|
| 293 |
+
|
| 294 |
+
sense = False
|
| 295 |
+
ex1 = index1 # vertex index of unified edges
|
| 296 |
+
ex2 = index2 # vertex index of unified edges
|
| 297 |
+
if ex1 > ex2:
|
| 298 |
+
sense = True
|
| 299 |
+
ex1, ex2 = ex2, ex1
|
| 300 |
+
try:
|
| 301 |
+
return self.edges[ex1, ex2], sense
|
| 302 |
+
except KeyError:
|
| 303 |
+
pass
|
| 304 |
+
# The edge has always the same direction as the underlying
|
| 305 |
+
# straight curve:
|
| 306 |
+
edge = entities.Edge()
|
| 307 |
+
edge.coedge = parent # first coedge which references this edge
|
| 308 |
+
edge.sense = False
|
| 309 |
+
edge.start_vertex = make_vertex(ex1)
|
| 310 |
+
edge.start_param = 0.0
|
| 311 |
+
edge.end_vertex = make_vertex(ex2)
|
| 312 |
+
edge.end_param = self.vertices[ex1].distance(self.vertices[ex2])
|
| 313 |
+
edge.curve = self.make_ray(ex1, ex2)
|
| 314 |
+
self.edges[ex1, ex2] = edge
|
| 315 |
+
return edge, sense
|
| 316 |
+
|
| 317 |
+
def make_ray(self, index1: int, index2: int) -> entities.StraightCurve:
|
| 318 |
+
v1 = self.vertices[index1]
|
| 319 |
+
v2 = self.vertices[index2]
|
| 320 |
+
ray = entities.StraightCurve()
|
| 321 |
+
ray.origin = v1
|
| 322 |
+
try:
|
| 323 |
+
ray.direction = (v2 - v1).normalize()
|
| 324 |
+
except ZeroDivisionError: # avoided by normalize_faces()
|
| 325 |
+
ray.direction = NULLVEC
|
| 326 |
+
return ray
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def make_vertices(vertices: Iterable[Vec3]) -> Iterator[entities.Vertex]:
|
| 330 |
+
for v in vertices:
|
| 331 |
+
point = entities.Point()
|
| 332 |
+
point.location = v
|
| 333 |
+
vertex = entities.Vertex()
|
| 334 |
+
vertex.point = point
|
| 335 |
+
yield vertex
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def vertices_from_body(body: Body) -> list[Vec3]:
|
| 339 |
+
"""Returns all stored vertices in the given :class:`Body` entity.
|
| 340 |
+
The result is not optimized, meaning the vertices are in no particular order and
|
| 341 |
+
there are duplicates.
|
| 342 |
+
|
| 343 |
+
This function can be useful to determining the approximate bounding box of an
|
| 344 |
+
:term:`ACIS` entity. The result is exact for polyhedra with flat faces with
|
| 345 |
+
straight edges, but not for bodies with curved edges and faces.
|
| 346 |
+
|
| 347 |
+
Args:
|
| 348 |
+
body: ACIS entity of type :class:`Body`
|
| 349 |
+
|
| 350 |
+
Raises:
|
| 351 |
+
TypeError: given `body` entity has invalid type
|
| 352 |
+
|
| 353 |
+
"""
|
| 354 |
+
|
| 355 |
+
if not isinstance(body, Body):
|
| 356 |
+
raise TypeError(f"expected a body entity, got: {type(body)}")
|
| 357 |
+
lump = body.lump
|
| 358 |
+
transform = body.transform
|
| 359 |
+
vertices: list[Vec3] = []
|
| 360 |
+
|
| 361 |
+
m: Optional[Matrix44] = None
|
| 362 |
+
if not transform.is_none:
|
| 363 |
+
m = transform.matrix
|
| 364 |
+
while not lump.is_none:
|
| 365 |
+
vertices.extend(vertices_from_lump(lump, m))
|
| 366 |
+
lump = lump.next_lump
|
| 367 |
+
return vertices
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def vertices_from_lump(lump: Lump, m: Matrix44 | None = None) -> list[Vec3]:
|
| 371 |
+
"""Returns all stored vertices from a given :class:`Lump` entity.
|
| 372 |
+
Applies the transformation :class:`~ezdxf.math.Matrix44` `m` to all vertices if not
|
| 373 |
+
``None``.
|
| 374 |
+
|
| 375 |
+
Args:
|
| 376 |
+
lump: :class:`Lump` entity
|
| 377 |
+
m: optional transformation matrix
|
| 378 |
+
|
| 379 |
+
Raises:
|
| 380 |
+
TypeError: `lump` has invalid ACIS type
|
| 381 |
+
|
| 382 |
+
"""
|
| 383 |
+
if not isinstance(lump, Lump):
|
| 384 |
+
raise TypeError(f"expected a lump entity, got: {type(lump)}")
|
| 385 |
+
|
| 386 |
+
vertices: list[Vec3] = []
|
| 387 |
+
shell = lump.shell
|
| 388 |
+
if shell.is_none:
|
| 389 |
+
return vertices # not a shell
|
| 390 |
+
|
| 391 |
+
face = shell.face
|
| 392 |
+
while not face.is_none:
|
| 393 |
+
first_coedge = NONE_REF
|
| 394 |
+
try:
|
| 395 |
+
first_coedge = face.loop.coedge
|
| 396 |
+
except AttributeError: # loop is a none-entity
|
| 397 |
+
pass
|
| 398 |
+
coedge = first_coedge
|
| 399 |
+
while not coedge.is_none: # invalid coedge or face is not closed
|
| 400 |
+
# the edge entity contains the vertices and the curve type
|
| 401 |
+
edge = coedge.edge
|
| 402 |
+
try:
|
| 403 |
+
vertices.append(edge.start_vertex.point.location)
|
| 404 |
+
vertices.append(edge.end_vertex.point.location)
|
| 405 |
+
except AttributeError:
|
| 406 |
+
# one of the involved entities is a none-entity or an
|
| 407 |
+
# incompatible entity type -> ignore this face!
|
| 408 |
+
break
|
| 409 |
+
coedge = coedge.next_coedge
|
| 410 |
+
if coedge is first_coedge: # a valid closed face
|
| 411 |
+
break
|
| 412 |
+
face = face.next_face
|
| 413 |
+
if m is not None:
|
| 414 |
+
return list(m.transform_vertices(vertices))
|
| 415 |
+
return vertices
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/sab.py
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import (
|
| 5 |
+
NamedTuple,
|
| 6 |
+
Any,
|
| 7 |
+
Sequence,
|
| 8 |
+
Iterator,
|
| 9 |
+
Union,
|
| 10 |
+
Iterable,
|
| 11 |
+
cast,
|
| 12 |
+
TYPE_CHECKING,
|
| 13 |
+
List,
|
| 14 |
+
Tuple,
|
| 15 |
+
Optional,
|
| 16 |
+
)
|
| 17 |
+
from typing_extensions import TypeAlias
|
| 18 |
+
import math
|
| 19 |
+
import struct
|
| 20 |
+
from datetime import datetime
|
| 21 |
+
|
| 22 |
+
from ezdxf.math import Vec3
|
| 23 |
+
from . import const
|
| 24 |
+
from .const import ParsingError, Tags, InvalidLinkStructure
|
| 25 |
+
from .hdr import AcisHeader
|
| 26 |
+
from .abstract import (
|
| 27 |
+
AbstractEntity,
|
| 28 |
+
DataLoader,
|
| 29 |
+
AbstractBuilder,
|
| 30 |
+
DataExporter,
|
| 31 |
+
EntityExporter,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from .entities import AcisEntity
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class Token(NamedTuple):
|
| 39 |
+
"""Named tuple to store tagged value tokens of the SAB format."""
|
| 40 |
+
|
| 41 |
+
tag: int
|
| 42 |
+
value: Any
|
| 43 |
+
|
| 44 |
+
def __str__(self):
|
| 45 |
+
return f"(0x{self.tag:02x}, {str(self.value)})"
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
SabRecord: TypeAlias = List[Token]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Decoder:
|
| 52 |
+
def __init__(self, data: bytes):
|
| 53 |
+
self.data = data
|
| 54 |
+
self.index: int = 0
|
| 55 |
+
|
| 56 |
+
@property
|
| 57 |
+
def has_data(self) -> bool:
|
| 58 |
+
return self.index < len(self.data)
|
| 59 |
+
|
| 60 |
+
def read_header(self) -> AcisHeader:
|
| 61 |
+
header = AcisHeader()
|
| 62 |
+
for signature in const.SIGNATURES:
|
| 63 |
+
if self.data.startswith(signature):
|
| 64 |
+
self.index = len(signature)
|
| 65 |
+
break
|
| 66 |
+
else:
|
| 67 |
+
raise ParsingError("not a SAB file")
|
| 68 |
+
header.version = self.read_int()
|
| 69 |
+
header.n_records = self.read_int()
|
| 70 |
+
header.n_entities = self.read_int()
|
| 71 |
+
header.flags = self.read_int()
|
| 72 |
+
header.product_id = self.read_str_tag()
|
| 73 |
+
header.acis_version = self.read_str_tag()
|
| 74 |
+
date = self.read_str_tag()
|
| 75 |
+
header.creation_date = datetime.strptime(date, const.DATE_FMT)
|
| 76 |
+
header.units_in_mm = self.read_double_tag()
|
| 77 |
+
# tolerances are ignored
|
| 78 |
+
_ = self.read_double_tag() # res_tol
|
| 79 |
+
_ = self.read_double_tag() # nor_tol
|
| 80 |
+
return header
|
| 81 |
+
|
| 82 |
+
def forward(self, count: int):
|
| 83 |
+
pos = self.index
|
| 84 |
+
self.index += count
|
| 85 |
+
return pos
|
| 86 |
+
|
| 87 |
+
def read_byte(self) -> int:
|
| 88 |
+
pos = self.forward(1)
|
| 89 |
+
return self.data[pos]
|
| 90 |
+
|
| 91 |
+
def read_bytes(self, count: int) -> bytes:
|
| 92 |
+
pos = self.forward(count)
|
| 93 |
+
return self.data[pos : pos + count]
|
| 94 |
+
|
| 95 |
+
def read_int(self) -> int:
|
| 96 |
+
pos = self.forward(4)
|
| 97 |
+
values = struct.unpack_from("<i", self.data, pos)[0]
|
| 98 |
+
return values
|
| 99 |
+
|
| 100 |
+
def read_float(self) -> float:
|
| 101 |
+
pos = self.forward(8)
|
| 102 |
+
return struct.unpack_from("<d", self.data, pos)[0]
|
| 103 |
+
|
| 104 |
+
def read_floats(self, count: int) -> Sequence[float]:
|
| 105 |
+
pos = self.forward(8 * count)
|
| 106 |
+
return struct.unpack_from(f"<{count}d", self.data, pos)
|
| 107 |
+
|
| 108 |
+
def read_str(self, length) -> str:
|
| 109 |
+
text = self.read_bytes(length)
|
| 110 |
+
return text.decode()
|
| 111 |
+
|
| 112 |
+
def read_str_tag(self) -> str:
|
| 113 |
+
tag = self.read_byte()
|
| 114 |
+
if tag != Tags.STR:
|
| 115 |
+
raise ParsingError("string tag (7) not found")
|
| 116 |
+
return self.read_str(self.read_byte())
|
| 117 |
+
|
| 118 |
+
def read_double_tag(self) -> float:
|
| 119 |
+
tag = self.read_byte()
|
| 120 |
+
if tag != Tags.DOUBLE:
|
| 121 |
+
raise ParsingError("double tag (6) not found")
|
| 122 |
+
return self.read_float()
|
| 123 |
+
|
| 124 |
+
def read_record(self) -> SabRecord:
|
| 125 |
+
def entity_name():
|
| 126 |
+
return "-".join(entity_type)
|
| 127 |
+
|
| 128 |
+
values: SabRecord = []
|
| 129 |
+
entity_type: list[str] = []
|
| 130 |
+
subtype_level: int = 0
|
| 131 |
+
while True:
|
| 132 |
+
if not self.has_data:
|
| 133 |
+
if values:
|
| 134 |
+
token = values[0]
|
| 135 |
+
if token.value in const.DATA_END_MARKERS:
|
| 136 |
+
return values
|
| 137 |
+
raise ParsingError("pre-mature end of data")
|
| 138 |
+
tag = self.read_byte()
|
| 139 |
+
if tag == Tags.INT:
|
| 140 |
+
values.append(Token(tag, self.read_int()))
|
| 141 |
+
elif tag == Tags.DOUBLE:
|
| 142 |
+
values.append(Token(tag, self.read_float()))
|
| 143 |
+
elif tag == Tags.STR:
|
| 144 |
+
values.append(Token(tag, self.read_str(self.read_byte())))
|
| 145 |
+
elif tag == Tags.POINTER:
|
| 146 |
+
values.append(Token(tag, self.read_int()))
|
| 147 |
+
elif tag == Tags.BOOL_TRUE:
|
| 148 |
+
values.append(Token(tag, True))
|
| 149 |
+
elif tag == Tags.BOOL_FALSE:
|
| 150 |
+
values.append(Token(tag, False))
|
| 151 |
+
elif tag == Tags.LITERAL_STR:
|
| 152 |
+
values.append(Token(tag, self.read_str(self.read_int())))
|
| 153 |
+
elif tag == Tags.ENTITY_TYPE_EX:
|
| 154 |
+
entity_type.append(self.read_str(self.read_byte()))
|
| 155 |
+
elif tag == Tags.ENTITY_TYPE:
|
| 156 |
+
entity_type.append(self.read_str(self.read_byte()))
|
| 157 |
+
values.append(Token(tag, entity_name()))
|
| 158 |
+
entity_type.clear()
|
| 159 |
+
elif tag == Tags.LOCATION_VEC:
|
| 160 |
+
values.append(Token(tag, self.read_floats(3)))
|
| 161 |
+
elif tag == Tags.DIRECTION_VEC:
|
| 162 |
+
values.append(Token(tag, self.read_floats(3)))
|
| 163 |
+
elif tag == Tags.ENUM:
|
| 164 |
+
values.append(Token(tag, self.read_int()))
|
| 165 |
+
elif tag == Tags.UNKNOWN_0x17:
|
| 166 |
+
values.append(Token(tag, self.read_float()))
|
| 167 |
+
elif tag == Tags.SUBTYPE_START:
|
| 168 |
+
subtype_level += 1
|
| 169 |
+
values.append(Token(tag, subtype_level))
|
| 170 |
+
elif tag == Tags.SUBTYPE_END:
|
| 171 |
+
values.append(Token(tag, subtype_level))
|
| 172 |
+
subtype_level -= 1
|
| 173 |
+
elif tag == Tags.RECORD_END:
|
| 174 |
+
return values
|
| 175 |
+
else:
|
| 176 |
+
raise ParsingError(
|
| 177 |
+
f"unknown SAB tag: 0x{tag:x} ({tag}) in entity '{values[0].value}'"
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def read_records(self) -> Iterator[SabRecord]:
|
| 181 |
+
while True:
|
| 182 |
+
try:
|
| 183 |
+
if self.has_data:
|
| 184 |
+
yield self.read_record()
|
| 185 |
+
else:
|
| 186 |
+
return
|
| 187 |
+
except IndexError:
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class SabEntity(AbstractEntity):
|
| 192 |
+
"""Low level representation of an ACIS entity (node)."""
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
name: str,
|
| 197 |
+
attr_ptr: int = -1,
|
| 198 |
+
id: int = -1,
|
| 199 |
+
data: Optional[SabRecord] = None,
|
| 200 |
+
):
|
| 201 |
+
self.name = name
|
| 202 |
+
self.attr_ptr = attr_ptr
|
| 203 |
+
self.id = id
|
| 204 |
+
self.data: SabRecord = data if data is not None else []
|
| 205 |
+
self.attributes: "SabEntity" = None # type: ignore
|
| 206 |
+
|
| 207 |
+
def __str__(self):
|
| 208 |
+
return f"{self.name}({self.id})"
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
NULL_PTR = SabEntity(const.NULL_PTR_NAME, -1, -1, tuple()) # type: ignore
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class SabDataLoader(DataLoader):
|
| 215 |
+
def __init__(self, data: SabRecord, version: int):
|
| 216 |
+
self.version = version
|
| 217 |
+
self.data = data
|
| 218 |
+
self.index = 0
|
| 219 |
+
|
| 220 |
+
def has_data(self) -> bool:
|
| 221 |
+
return self.index <= len(self.data)
|
| 222 |
+
|
| 223 |
+
def read_int(self, skip_sat: Optional[int] = None) -> int:
|
| 224 |
+
token = self.data[self.index]
|
| 225 |
+
if token.tag == Tags.INT:
|
| 226 |
+
self.index += 1
|
| 227 |
+
return cast(int, token.value)
|
| 228 |
+
raise ParsingError(f"expected int token, got {token}")
|
| 229 |
+
|
| 230 |
+
def read_double(self) -> float:
|
| 231 |
+
token = self.data[self.index]
|
| 232 |
+
if token.tag == Tags.DOUBLE:
|
| 233 |
+
self.index += 1
|
| 234 |
+
return cast(float, token.value)
|
| 235 |
+
raise ParsingError(f"expected double token, got {token}")
|
| 236 |
+
|
| 237 |
+
def read_interval(self) -> float:
|
| 238 |
+
finite = self.read_bool("F", "I")
|
| 239 |
+
if finite:
|
| 240 |
+
return self.read_double()
|
| 241 |
+
return math.inf
|
| 242 |
+
|
| 243 |
+
def read_vec3(self) -> tuple[float, float, float]:
|
| 244 |
+
token = self.data[self.index]
|
| 245 |
+
if token.tag in (Tags.LOCATION_VEC, Tags.DIRECTION_VEC):
|
| 246 |
+
self.index += 1
|
| 247 |
+
return cast(Tuple[float, float, float], token.value)
|
| 248 |
+
raise ParsingError(f"expected vector token, got {token}")
|
| 249 |
+
|
| 250 |
+
def read_bool(self, true: str, false: str) -> bool:
|
| 251 |
+
token = self.data[self.index]
|
| 252 |
+
if token.tag == Tags.BOOL_TRUE:
|
| 253 |
+
self.index += 1
|
| 254 |
+
return True
|
| 255 |
+
elif token.tag == Tags.BOOL_FALSE:
|
| 256 |
+
self.index += 1
|
| 257 |
+
return False
|
| 258 |
+
raise ParsingError(f"expected bool token, got {token}")
|
| 259 |
+
|
| 260 |
+
def read_str(self) -> str:
|
| 261 |
+
token = self.data[self.index]
|
| 262 |
+
if token.tag in (Tags.STR, Tags.LITERAL_STR):
|
| 263 |
+
self.index += 1
|
| 264 |
+
return cast(str, token.value)
|
| 265 |
+
raise ParsingError(f"expected str token, got {token}")
|
| 266 |
+
|
| 267 |
+
def read_ptr(self) -> AbstractEntity:
|
| 268 |
+
token = self.data[self.index]
|
| 269 |
+
if token.tag == Tags.POINTER:
|
| 270 |
+
self.index += 1
|
| 271 |
+
return cast(AbstractEntity, token.value)
|
| 272 |
+
raise ParsingError(f"expected pointer token, got {token}")
|
| 273 |
+
|
| 274 |
+
def read_transform(self) -> list[float]:
|
| 275 |
+
# Transform matrix is stored as literal string like in the SAT format!
|
| 276 |
+
# 4th column is not stored
|
| 277 |
+
# Read only the matrix values which contain all information needed,
|
| 278 |
+
# the additional data are only hints for the kernel how to process
|
| 279 |
+
# the data (rotation, reflection, scaling, shearing).
|
| 280 |
+
values = self.read_str().split(" ")
|
| 281 |
+
return [float(v) for v in values[:12]]
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class SabBuilder(AbstractBuilder):
|
| 285 |
+
"""Low level data structure to manage ACIS SAB data files."""
|
| 286 |
+
|
| 287 |
+
def __init__(self) -> None:
|
| 288 |
+
self.header = AcisHeader()
|
| 289 |
+
self.bodies: list[SabEntity] = []
|
| 290 |
+
self.entities: list[SabEntity] = []
|
| 291 |
+
|
| 292 |
+
def dump_sab(self) -> bytes:
|
| 293 |
+
"""Returns the SAB representation of the ACIS file as bytes."""
|
| 294 |
+
self.reorder_records()
|
| 295 |
+
self.header.n_entities = len(self.bodies) + int(
|
| 296 |
+
self.header.has_asm_header
|
| 297 |
+
)
|
| 298 |
+
self.header.n_records = 0 # is always 0
|
| 299 |
+
self.header.flags = 12 # important for 21800 - meaning unknown
|
| 300 |
+
data: list[bytes] = [self.header.dumpb()]
|
| 301 |
+
encoder = Encoder()
|
| 302 |
+
for record in build_sab_records(self.entities):
|
| 303 |
+
encoder.write_record(record)
|
| 304 |
+
data.extend(encoder.buffer)
|
| 305 |
+
data.append(self.header.sab_end_marker())
|
| 306 |
+
return b"".join(data)
|
| 307 |
+
|
| 308 |
+
def set_entities(self, entities: list[SabEntity]) -> None:
|
| 309 |
+
"""Reset entities and bodies list. (internal API)"""
|
| 310 |
+
self.bodies = [e for e in entities if e.name == "body"]
|
| 311 |
+
self.entities = entities
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class SabExporter(EntityExporter[SabEntity]):
|
| 315 |
+
def make_record(self, entity: AcisEntity) -> SabEntity:
|
| 316 |
+
record = SabEntity(entity.type, id=entity.id)
|
| 317 |
+
record.attributes = NULL_PTR
|
| 318 |
+
return record
|
| 319 |
+
|
| 320 |
+
def make_data_exporter(self, record: SabEntity) -> DataExporter:
|
| 321 |
+
return SabDataExporter(self, record.data)
|
| 322 |
+
|
| 323 |
+
def dump_sab(self) -> bytes:
|
| 324 |
+
builder = SabBuilder()
|
| 325 |
+
builder.header = self.header
|
| 326 |
+
builder.set_entities(self.export_records())
|
| 327 |
+
return builder.dump_sab()
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def build_entities(
|
| 331 |
+
records: Iterable[SabRecord], version: int
|
| 332 |
+
) -> Iterator[SabEntity]:
|
| 333 |
+
for record in records:
|
| 334 |
+
assert record[0].tag == Tags.ENTITY_TYPE, "invalid entity-name tag"
|
| 335 |
+
name = record[0].value # 1. entity-name
|
| 336 |
+
if name in const.DATA_END_MARKERS:
|
| 337 |
+
yield SabEntity(name)
|
| 338 |
+
return
|
| 339 |
+
assert record[1].tag == Tags.POINTER, "invalid attribute pointer tag"
|
| 340 |
+
attr = record[1].value # 2. attribute record pointer
|
| 341 |
+
id_ = -1
|
| 342 |
+
if version >= 700:
|
| 343 |
+
assert record[2].tag == Tags.INT, "invalid id tag"
|
| 344 |
+
id_ = record[2].value # 3. int id
|
| 345 |
+
data = record[3:]
|
| 346 |
+
else:
|
| 347 |
+
data = record[2:]
|
| 348 |
+
yield SabEntity(name, attr, id_, data)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def resolve_pointers(entities: list[SabEntity]) -> list[SabEntity]:
|
| 352 |
+
def ptr(num: int) -> SabEntity:
|
| 353 |
+
if num == -1:
|
| 354 |
+
return NULL_PTR
|
| 355 |
+
return entities[num]
|
| 356 |
+
|
| 357 |
+
for entity in entities:
|
| 358 |
+
entity.attributes = ptr(entity.attr_ptr)
|
| 359 |
+
entity.attr_ptr = -1
|
| 360 |
+
for index, token in enumerate(entity.data):
|
| 361 |
+
if token.tag == Tags.POINTER:
|
| 362 |
+
entity.data[index] = Token(token.tag, ptr(token.value))
|
| 363 |
+
return entities
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def parse_sab(data: Union[bytes, bytearray]) -> SabBuilder:
|
| 367 |
+
"""Returns the :class:`SabBuilder` for the ACIS :term:`SAB` file content
|
| 368 |
+
given as string or list of strings.
|
| 369 |
+
|
| 370 |
+
Raises:
|
| 371 |
+
ParsingError: invalid or unsupported ACIS data structure
|
| 372 |
+
|
| 373 |
+
"""
|
| 374 |
+
if not isinstance(data, (bytes, bytearray)):
|
| 375 |
+
raise TypeError("expected bytes, bytearray")
|
| 376 |
+
builder = SabBuilder()
|
| 377 |
+
decoder = Decoder(data)
|
| 378 |
+
builder.header = decoder.read_header()
|
| 379 |
+
entities = list(
|
| 380 |
+
build_entities(decoder.read_records(), builder.header.version)
|
| 381 |
+
)
|
| 382 |
+
builder.set_entities(resolve_pointers(entities))
|
| 383 |
+
return builder
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class SabDataExporter(DataExporter):
|
| 387 |
+
def __init__(self, exporter: SabExporter, data: list[Token]):
|
| 388 |
+
self.version = exporter.version
|
| 389 |
+
self.exporter = exporter
|
| 390 |
+
self.data = data
|
| 391 |
+
|
| 392 |
+
def write_int(self, value: int, skip_sat=False) -> None:
|
| 393 |
+
"""There are sometimes additional int values in SAB files which are
|
| 394 |
+
not present in SAT files, maybe reference counters e.g. vertex, coedge.
|
| 395 |
+
"""
|
| 396 |
+
self.data.append(Token(Tags.INT, value))
|
| 397 |
+
|
| 398 |
+
def write_double(self, value: float) -> None:
|
| 399 |
+
self.data.append(Token(Tags.DOUBLE, value))
|
| 400 |
+
|
| 401 |
+
def write_interval(self, value: float) -> None:
|
| 402 |
+
if math.isinf(value):
|
| 403 |
+
self.data.append(Token(Tags.BOOL_FALSE, False)) # infinite "I"
|
| 404 |
+
else:
|
| 405 |
+
self.data.append(Token(Tags.BOOL_TRUE, True)) # finite "F"
|
| 406 |
+
self.write_double(value)
|
| 407 |
+
|
| 408 |
+
def write_loc_vec3(self, value: Vec3) -> None:
|
| 409 |
+
self.data.append(Token(Tags.LOCATION_VEC, value))
|
| 410 |
+
|
| 411 |
+
def write_dir_vec3(self, value: Vec3) -> None:
|
| 412 |
+
self.data.append(Token(Tags.DIRECTION_VEC, value))
|
| 413 |
+
|
| 414 |
+
def write_bool(self, value: bool, true: str, false: str) -> None:
|
| 415 |
+
if value:
|
| 416 |
+
self.data.append(Token(Tags.BOOL_TRUE, True))
|
| 417 |
+
else:
|
| 418 |
+
self.data.append(Token(Tags.BOOL_FALSE, False))
|
| 419 |
+
|
| 420 |
+
def write_str(self, value: str) -> None:
|
| 421 |
+
self.data.append(Token(Tags.STR, value))
|
| 422 |
+
|
| 423 |
+
def write_literal_str(self, value: str) -> None:
|
| 424 |
+
self.data.append(Token(Tags.LITERAL_STR, value))
|
| 425 |
+
|
| 426 |
+
def write_ptr(self, entity: AcisEntity) -> None:
|
| 427 |
+
record = NULL_PTR
|
| 428 |
+
if not entity.is_none:
|
| 429 |
+
record = self.exporter.get_record(entity)
|
| 430 |
+
self.data.append(Token(Tags.POINTER, record))
|
| 431 |
+
|
| 432 |
+
def write_transform(self, data: list[str]) -> None:
|
| 433 |
+
# The last space is important!
|
| 434 |
+
self.write_literal_str(" ".join(data) + " ")
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def encode_entity_type(name: str) -> list[Token]:
|
| 438 |
+
if name == const.NULL_PTR_NAME:
|
| 439 |
+
raise InvalidLinkStructure(
|
| 440 |
+
f"invalid record type: {const.NULL_PTR_NAME}"
|
| 441 |
+
)
|
| 442 |
+
parts = name.split("-")
|
| 443 |
+
tokens = [Token(Tags.ENTITY_TYPE_EX, part) for part in parts[:-1]]
|
| 444 |
+
tokens.append(Token(Tags.ENTITY_TYPE, parts[-1]))
|
| 445 |
+
return tokens
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
def encode_entity_ptr(entity: SabEntity, entities: list[SabEntity]) -> Token:
|
| 449 |
+
if entity.is_null_ptr:
|
| 450 |
+
return Token(Tags.POINTER, -1)
|
| 451 |
+
try:
|
| 452 |
+
return Token(Tags.POINTER, entities.index(entity))
|
| 453 |
+
except ValueError:
|
| 454 |
+
raise InvalidLinkStructure(
|
| 455 |
+
f"entity {str(entity)} not in record storage"
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def build_sab_records(entities: list[SabEntity]) -> Iterator[SabRecord]:
|
| 460 |
+
for entity in entities:
|
| 461 |
+
record: list[Token] = []
|
| 462 |
+
record.extend(encode_entity_type(entity.name))
|
| 463 |
+
# 1. attribute record pointer
|
| 464 |
+
record.append(encode_entity_ptr(entity.attributes, entities))
|
| 465 |
+
# 2. int id
|
| 466 |
+
record.append(Token(Tags.INT, entity.id))
|
| 467 |
+
for token in entity.data:
|
| 468 |
+
if token.tag == Tags.POINTER:
|
| 469 |
+
record.append(encode_entity_ptr(token.value, entities))
|
| 470 |
+
elif token.tag == Tags.ENTITY_TYPE:
|
| 471 |
+
record.extend(encode_entity_type(token.value))
|
| 472 |
+
else:
|
| 473 |
+
record.append(token)
|
| 474 |
+
yield record
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
END_OF_RECORD = bytes([Tags.RECORD_END.value])
|
| 478 |
+
TRUE_RECORD = bytes([Tags.BOOL_TRUE.value])
|
| 479 |
+
FALSE_RECORD = bytes([Tags.BOOL_FALSE.value])
|
| 480 |
+
SUBTYPE_START_RECORD = bytes([Tags.SUBTYPE_START.value])
|
| 481 |
+
SUBTYPE_END_RECORD = bytes([Tags.SUBTYPE_END.value])
|
| 482 |
+
SAB_ENCODING = "utf8"
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
class Encoder:
|
| 486 |
+
def __init__(self) -> None:
|
| 487 |
+
self.buffer: list[bytes] = []
|
| 488 |
+
|
| 489 |
+
def write_record(self, record: SabRecord) -> None:
|
| 490 |
+
for token in record:
|
| 491 |
+
self.write_token(token)
|
| 492 |
+
self.buffer.append(END_OF_RECORD)
|
| 493 |
+
|
| 494 |
+
def write_token(self, token: Token) -> None:
|
| 495 |
+
tag = token.tag
|
| 496 |
+
if tag in (Tags.INT, Tags.POINTER, Tags.ENUM):
|
| 497 |
+
assert isinstance(token.value, int)
|
| 498 |
+
self.buffer.append(struct.pack("<Bi", tag, token.value))
|
| 499 |
+
elif tag == Tags.DOUBLE:
|
| 500 |
+
assert isinstance(token.value, float)
|
| 501 |
+
self.buffer.append(struct.pack("<Bd", tag, token.value))
|
| 502 |
+
elif tag == Tags.STR:
|
| 503 |
+
assert isinstance(token.value, str)
|
| 504 |
+
data = token.value.encode(encoding=SAB_ENCODING)
|
| 505 |
+
self.buffer.append(struct.pack("<BB", tag, len(data)) + data)
|
| 506 |
+
elif tag == Tags.LITERAL_STR:
|
| 507 |
+
assert isinstance(token.value, str)
|
| 508 |
+
data = token.value.encode(encoding=SAB_ENCODING)
|
| 509 |
+
self.buffer.append(struct.pack("<Bi", tag, len(data)) + data)
|
| 510 |
+
elif tag in (Tags.ENTITY_TYPE, Tags.ENTITY_TYPE_EX):
|
| 511 |
+
assert isinstance(token.value, str)
|
| 512 |
+
data = token.value.encode(encoding=SAB_ENCODING)
|
| 513 |
+
self.buffer.append(struct.pack("<BB", tag, len(data)) + data)
|
| 514 |
+
elif tag in (Tags.LOCATION_VEC, Tags.DIRECTION_VEC):
|
| 515 |
+
v = token.value
|
| 516 |
+
assert isinstance(v, Vec3)
|
| 517 |
+
self.buffer.append(struct.pack("<B3d", tag, v.x, v.y, v.z))
|
| 518 |
+
elif tag == Tags.BOOL_TRUE:
|
| 519 |
+
self.buffer.append(TRUE_RECORD)
|
| 520 |
+
elif tag == Tags.BOOL_FALSE:
|
| 521 |
+
self.buffer.append(FALSE_RECORD)
|
| 522 |
+
elif tag == Tags.SUBTYPE_START:
|
| 523 |
+
self.buffer.append(SUBTYPE_START_RECORD)
|
| 524 |
+
elif tag == Tags.SUBTYPE_END:
|
| 525 |
+
self.buffer.append(SUBTYPE_END_RECORD)
|
| 526 |
+
else:
|
| 527 |
+
raise ValueError(f"invalid tag in token: {token}")
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/acis/sat.py
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import (
|
| 5 |
+
Any,
|
| 6 |
+
Sequence,
|
| 7 |
+
Iterator,
|
| 8 |
+
Union,
|
| 9 |
+
List,
|
| 10 |
+
TYPE_CHECKING,
|
| 11 |
+
Optional,
|
| 12 |
+
)
|
| 13 |
+
from typing_extensions import TypeAlias
|
| 14 |
+
import math
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
|
| 17 |
+
from . import const
|
| 18 |
+
from .const import ParsingError, InvalidLinkStructure
|
| 19 |
+
from .hdr import AcisHeader
|
| 20 |
+
from .abstract import (
|
| 21 |
+
AbstractEntity,
|
| 22 |
+
AbstractBuilder,
|
| 23 |
+
DataLoader,
|
| 24 |
+
DataExporter,
|
| 25 |
+
EntityExporter,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
if TYPE_CHECKING:
|
| 29 |
+
from .entities import AcisEntity
|
| 30 |
+
from ezdxf.math import Vec3
|
| 31 |
+
|
| 32 |
+
SatRecord: TypeAlias = List[str]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SatEntity(AbstractEntity):
|
| 36 |
+
"""Low level representation of an ACIS entity (node)."""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
name: str,
|
| 41 |
+
attr_ptr: str = "$-1",
|
| 42 |
+
id: int = -1,
|
| 43 |
+
data: Optional[list[Any]] = None,
|
| 44 |
+
):
|
| 45 |
+
self.name = name
|
| 46 |
+
self.attr_ptr = attr_ptr
|
| 47 |
+
self.id = id
|
| 48 |
+
self.data: list[Any] = data if data is not None else []
|
| 49 |
+
self.attributes: "SatEntity" = None # type: ignore
|
| 50 |
+
|
| 51 |
+
def __str__(self):
|
| 52 |
+
return f"{self.name}({self.id})"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
NULL_PTR = SatEntity("null-ptr", "$-1", -1, tuple()) # type: ignore
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def new_entity(
|
| 59 |
+
name: str,
|
| 60 |
+
attributes=NULL_PTR,
|
| 61 |
+
id=-1,
|
| 62 |
+
data: Optional[list[Any]] = None,
|
| 63 |
+
) -> SatEntity:
|
| 64 |
+
"""Factory to create new ACIS entities.
|
| 65 |
+
|
| 66 |
+
Args:
|
| 67 |
+
name: entity type
|
| 68 |
+
attributes: reference to the entity attributes or :attr:`NULL_PTR`.
|
| 69 |
+
id: unique entity id as integer or -1
|
| 70 |
+
data: generic data container as list
|
| 71 |
+
|
| 72 |
+
"""
|
| 73 |
+
e = SatEntity(name, "$-1", id, data)
|
| 74 |
+
e.attributes = attributes
|
| 75 |
+
return e
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def is_ptr(s: str) -> bool:
|
| 79 |
+
"""Returns ``True`` if the string `s` represents an entity pointer."""
|
| 80 |
+
return len(s) > 0 and s[0] == "$"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def resolve_str_pointers(entities: list[SatEntity]) -> list[SatEntity]:
|
| 84 |
+
def ptr(s: str) -> SatEntity:
|
| 85 |
+
num = int(s[1:])
|
| 86 |
+
if num == -1:
|
| 87 |
+
return NULL_PTR
|
| 88 |
+
return entities[num]
|
| 89 |
+
|
| 90 |
+
for entity in entities:
|
| 91 |
+
entity.attributes = ptr(entity.attr_ptr)
|
| 92 |
+
entity.attr_ptr = "$-1"
|
| 93 |
+
data = []
|
| 94 |
+
for token in entity.data:
|
| 95 |
+
if is_ptr(token):
|
| 96 |
+
data.append(ptr(token))
|
| 97 |
+
else:
|
| 98 |
+
data.append(token)
|
| 99 |
+
entity.data = data
|
| 100 |
+
return entities
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SatDataLoader(DataLoader):
|
| 104 |
+
def __init__(self, data: list[Any], version: int):
|
| 105 |
+
self.version = version
|
| 106 |
+
self.data = data
|
| 107 |
+
self.index = 0
|
| 108 |
+
|
| 109 |
+
def has_data(self) -> bool:
|
| 110 |
+
return self.index <= len(self.data)
|
| 111 |
+
|
| 112 |
+
def read_int(self, skip_sat: Optional[int] = None) -> int:
|
| 113 |
+
if skip_sat is not None:
|
| 114 |
+
return skip_sat
|
| 115 |
+
|
| 116 |
+
entry = self.data[self.index]
|
| 117 |
+
try:
|
| 118 |
+
value = int(entry)
|
| 119 |
+
except ValueError:
|
| 120 |
+
raise ParsingError(f"expected integer, got {entry}")
|
| 121 |
+
self.index += 1
|
| 122 |
+
return value
|
| 123 |
+
|
| 124 |
+
def read_double(self) -> float:
|
| 125 |
+
entry = self.data[self.index]
|
| 126 |
+
try:
|
| 127 |
+
value = float(entry)
|
| 128 |
+
except ValueError:
|
| 129 |
+
raise ParsingError(f"expected double, got {entry}")
|
| 130 |
+
self.index += 1
|
| 131 |
+
return value
|
| 132 |
+
|
| 133 |
+
def read_interval(self) -> float:
|
| 134 |
+
finite = self.read_bool("F", "I")
|
| 135 |
+
if finite:
|
| 136 |
+
return self.read_double()
|
| 137 |
+
return math.inf
|
| 138 |
+
|
| 139 |
+
def read_vec3(self) -> tuple[float, float, float]:
|
| 140 |
+
x = self.read_double()
|
| 141 |
+
y = self.read_double()
|
| 142 |
+
z = self.read_double()
|
| 143 |
+
return x, y, z
|
| 144 |
+
|
| 145 |
+
def read_bool(self, true: str, false: str) -> bool:
|
| 146 |
+
value = self.data[self.index]
|
| 147 |
+
if value == true:
|
| 148 |
+
self.index += 1
|
| 149 |
+
return True
|
| 150 |
+
elif value == false:
|
| 151 |
+
self.index += 1
|
| 152 |
+
return False
|
| 153 |
+
raise ParsingError(
|
| 154 |
+
f"expected bool string '{true}' or '{false}', got {value}"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
def read_str(self) -> str:
|
| 158 |
+
value = self.data[self.index]
|
| 159 |
+
if self.version < const.Features.AT or value.startswith("@"):
|
| 160 |
+
self.index += 2
|
| 161 |
+
return self.data[self.index - 1]
|
| 162 |
+
raise ParsingError(f"expected string, got {value}")
|
| 163 |
+
|
| 164 |
+
def read_ptr(self) -> AbstractEntity:
|
| 165 |
+
entity = self.data[self.index]
|
| 166 |
+
if isinstance(entity, AbstractEntity):
|
| 167 |
+
self.index += 1
|
| 168 |
+
return entity
|
| 169 |
+
raise ParsingError(f"expected pointer, got {type(entity)}")
|
| 170 |
+
|
| 171 |
+
def read_transform(self) -> list[float]:
|
| 172 |
+
# 4th column is not stored
|
| 173 |
+
# Read only the matrix values which contain all information needed,
|
| 174 |
+
# the additional data are only hints for the kernel how to process
|
| 175 |
+
# the data (rotation, reflection, scaling, shearing).
|
| 176 |
+
return [self.read_double() for _ in range(12)]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class SatBuilder(AbstractBuilder):
|
| 180 |
+
"""Low level data structure to manage ACIS SAT data files."""
|
| 181 |
+
|
| 182 |
+
def __init__(self) -> None:
|
| 183 |
+
self.header = AcisHeader()
|
| 184 |
+
self.bodies: list[SatEntity] = []
|
| 185 |
+
self.entities: list[SatEntity] = []
|
| 186 |
+
self._export_mapping: dict[int, SatEntity] = {}
|
| 187 |
+
|
| 188 |
+
def dump_sat(self) -> list[str]:
|
| 189 |
+
"""Returns the text representation of the ACIS file as list of strings
|
| 190 |
+
without line endings.
|
| 191 |
+
|
| 192 |
+
Raise:
|
| 193 |
+
InvalidLinkStructure: referenced ACIS entity is not stored in
|
| 194 |
+
the :attr:`entities` storage
|
| 195 |
+
|
| 196 |
+
"""
|
| 197 |
+
self.reorder_records()
|
| 198 |
+
self.header.n_entities = len(self.bodies) + int(
|
| 199 |
+
self.header.has_asm_header
|
| 200 |
+
)
|
| 201 |
+
if self.header.version == 700:
|
| 202 |
+
self.header.n_records = 0 # ignored for old versions
|
| 203 |
+
else:
|
| 204 |
+
self.header.n_records = len(self.entities)
|
| 205 |
+
data = self.header.dumps()
|
| 206 |
+
data.extend(build_str_records(self.entities, self.header.version))
|
| 207 |
+
data.append(self.header.sat_end_marker())
|
| 208 |
+
return data
|
| 209 |
+
|
| 210 |
+
def set_entities(self, entities: list[SatEntity]) -> None:
|
| 211 |
+
"""Reset entities and bodies list. (internal API)"""
|
| 212 |
+
self.bodies = [e for e in entities if e.name == "body"]
|
| 213 |
+
self.entities = entities
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
class SatExporter(EntityExporter[SatEntity]):
|
| 217 |
+
def make_record(self, entity: AcisEntity) -> SatEntity:
|
| 218 |
+
record = SatEntity(entity.type, id=entity.id)
|
| 219 |
+
record.attributes = NULL_PTR
|
| 220 |
+
return record
|
| 221 |
+
|
| 222 |
+
def make_data_exporter(self, record: SatEntity) -> DataExporter:
|
| 223 |
+
return SatDataExporter(self, record.data)
|
| 224 |
+
|
| 225 |
+
def dump_sat(self) -> list[str]:
|
| 226 |
+
builder = SatBuilder()
|
| 227 |
+
builder.header = self.header
|
| 228 |
+
builder.set_entities(self.export_records())
|
| 229 |
+
return builder.dump_sat()
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def build_str_records(entities: list[SatEntity], version: int) -> Iterator[str]:
|
| 233 |
+
def ptr_str(e: SatEntity) -> str:
|
| 234 |
+
if e is NULL_PTR:
|
| 235 |
+
return "$-1"
|
| 236 |
+
try:
|
| 237 |
+
return f"${entities.index(e)}"
|
| 238 |
+
except ValueError:
|
| 239 |
+
raise InvalidLinkStructure(f"entity {str(e)} not in record storage")
|
| 240 |
+
|
| 241 |
+
for entity in entities:
|
| 242 |
+
tokens = [entity.name]
|
| 243 |
+
tokens.append(ptr_str(entity.attributes))
|
| 244 |
+
if version >= 700:
|
| 245 |
+
tokens.append(str(entity.id))
|
| 246 |
+
for data in entity.data:
|
| 247 |
+
if isinstance(data, SatEntity):
|
| 248 |
+
tokens.append(ptr_str(data))
|
| 249 |
+
else:
|
| 250 |
+
tokens.append(str(data))
|
| 251 |
+
tokens.append("#")
|
| 252 |
+
yield " ".join(tokens)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def parse_header_str(s: str) -> Iterator[str]:
|
| 256 |
+
num = ""
|
| 257 |
+
collect = 0
|
| 258 |
+
token = ""
|
| 259 |
+
for c in s.rstrip():
|
| 260 |
+
if collect > 0:
|
| 261 |
+
token += c
|
| 262 |
+
collect -= 1
|
| 263 |
+
if collect == 0:
|
| 264 |
+
yield token
|
| 265 |
+
token = ""
|
| 266 |
+
elif c == "@":
|
| 267 |
+
continue
|
| 268 |
+
elif c in "0123456789":
|
| 269 |
+
num += c
|
| 270 |
+
elif c == " " and num:
|
| 271 |
+
collect = int(num)
|
| 272 |
+
num = ""
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def parse_header(data: Sequence[str]) -> tuple[AcisHeader, Sequence[str]]:
|
| 276 |
+
header = AcisHeader()
|
| 277 |
+
tokens = data[0].split()
|
| 278 |
+
header.version = int(tokens[0])
|
| 279 |
+
try:
|
| 280 |
+
header.n_records = int(tokens[1])
|
| 281 |
+
header.n_entities = int(tokens[2])
|
| 282 |
+
header.flags = int(tokens[3])
|
| 283 |
+
except (IndexError, ValueError):
|
| 284 |
+
pass
|
| 285 |
+
tokens = list(parse_header_str(data[1]))
|
| 286 |
+
try:
|
| 287 |
+
header.product_id = tokens[0]
|
| 288 |
+
header.acis_version = tokens[1]
|
| 289 |
+
except IndexError:
|
| 290 |
+
pass
|
| 291 |
+
|
| 292 |
+
if len(tokens) > 2:
|
| 293 |
+
try: # Sat Jan 1 10:00:00 2022
|
| 294 |
+
header.creation_date = datetime.strptime(tokens[2], const.DATE_FMT)
|
| 295 |
+
except ValueError:
|
| 296 |
+
pass
|
| 297 |
+
tokens = data[2].split()
|
| 298 |
+
try:
|
| 299 |
+
header.units_in_mm = float(tokens[0])
|
| 300 |
+
except (IndexError, ValueError):
|
| 301 |
+
pass
|
| 302 |
+
return header, data[3:]
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def _filter_records(data: Sequence[str]) -> Iterator[str]:
|
| 306 |
+
for line in data:
|
| 307 |
+
if line.startswith(const.END_OF_ACIS_DATA_SAT) or line.startswith(
|
| 308 |
+
const.BEGIN_OF_ACIS_HISTORY_DATA
|
| 309 |
+
):
|
| 310 |
+
return
|
| 311 |
+
yield line
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def merge_record_strings(data: Sequence[str]) -> Iterator[str]:
|
| 315 |
+
merged_data = " ".join(_filter_records(data))
|
| 316 |
+
for record in merged_data.split("#"):
|
| 317 |
+
record = record.strip()
|
| 318 |
+
if record:
|
| 319 |
+
yield record
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def parse_records(data: Sequence[str]) -> list[SatRecord]:
|
| 323 |
+
expected_seq_num = 0
|
| 324 |
+
records: list[SatRecord] = []
|
| 325 |
+
for line in merge_record_strings(data):
|
| 326 |
+
tokens: SatRecord = line.split()
|
| 327 |
+
first_token = tokens[0].strip()
|
| 328 |
+
if first_token.startswith("-"):
|
| 329 |
+
num = -int(first_token)
|
| 330 |
+
if num != expected_seq_num:
|
| 331 |
+
raise ParsingError(
|
| 332 |
+
"non-continuous sequence numbers not supported"
|
| 333 |
+
)
|
| 334 |
+
tokens.pop(0)
|
| 335 |
+
records.append(tokens)
|
| 336 |
+
expected_seq_num += 1
|
| 337 |
+
return records
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def build_entities(
|
| 341 |
+
records: Sequence[SatRecord], version: int
|
| 342 |
+
) -> list[SatEntity]:
|
| 343 |
+
entities: list[SatEntity] = []
|
| 344 |
+
for record in records:
|
| 345 |
+
name = record[0]
|
| 346 |
+
attr = record[1]
|
| 347 |
+
id_ = -1
|
| 348 |
+
if version >= 700:
|
| 349 |
+
id_ = int(record[2])
|
| 350 |
+
data = record[3:]
|
| 351 |
+
else:
|
| 352 |
+
data = record[2:]
|
| 353 |
+
entities.append(SatEntity(name, attr, id_, data))
|
| 354 |
+
return entities
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def parse_sat(s: Union[str, Sequence[str]]) -> SatBuilder:
|
| 358 |
+
"""Returns the :class:`SatBuilder` for the ACIS :term:`SAT` file content
|
| 359 |
+
given as string or list of strings.
|
| 360 |
+
|
| 361 |
+
Raises:
|
| 362 |
+
ParsingError: invalid or unsupported ACIS data structure
|
| 363 |
+
|
| 364 |
+
"""
|
| 365 |
+
data: Sequence[str]
|
| 366 |
+
if isinstance(s, str):
|
| 367 |
+
data = s.splitlines()
|
| 368 |
+
else:
|
| 369 |
+
data = s
|
| 370 |
+
if not isinstance(data, Sequence):
|
| 371 |
+
raise TypeError("expected as string or a sequence of strings")
|
| 372 |
+
builder = SatBuilder()
|
| 373 |
+
header, data = parse_header(data)
|
| 374 |
+
builder.header = header
|
| 375 |
+
records = parse_records(data)
|
| 376 |
+
entities = build_entities(records, header.version)
|
| 377 |
+
builder.set_entities(resolve_str_pointers(entities))
|
| 378 |
+
return builder
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
class SatDataExporter(DataExporter):
|
| 382 |
+
def __init__(self, exporter: SatExporter, data: list[Any]):
|
| 383 |
+
self.version = exporter.version
|
| 384 |
+
self.exporter = exporter
|
| 385 |
+
self.data = data
|
| 386 |
+
|
| 387 |
+
def write_int(self, value: int, skip_sat=False) -> None:
|
| 388 |
+
"""There are sometimes additional int values in SAB files which are
|
| 389 |
+
not present in SAT files, maybe reference counters e.g. vertex, coedge.
|
| 390 |
+
"""
|
| 391 |
+
if not skip_sat:
|
| 392 |
+
self.data.append(str(value))
|
| 393 |
+
|
| 394 |
+
def write_double(self, value: float) -> None:
|
| 395 |
+
self.data.append(f"{value:g}")
|
| 396 |
+
|
| 397 |
+
def write_interval(self, value: float) -> None:
|
| 398 |
+
if math.isinf(value):
|
| 399 |
+
self.data.append("I") # infinite
|
| 400 |
+
else:
|
| 401 |
+
self.data.append("F") # finite
|
| 402 |
+
self.write_double(value)
|
| 403 |
+
|
| 404 |
+
def write_loc_vec3(self, value: Vec3) -> None:
|
| 405 |
+
self.write_double(value.x)
|
| 406 |
+
self.write_double(value.y)
|
| 407 |
+
self.write_double(value.z)
|
| 408 |
+
|
| 409 |
+
def write_dir_vec3(self, value: Vec3) -> None:
|
| 410 |
+
self.write_double(value.x)
|
| 411 |
+
self.write_double(value.y)
|
| 412 |
+
self.write_double(value.z)
|
| 413 |
+
|
| 414 |
+
def write_bool(self, value: bool, true: str, false: str) -> None:
|
| 415 |
+
self.data.append(true if value else false)
|
| 416 |
+
|
| 417 |
+
def write_str(self, value: str) -> None:
|
| 418 |
+
self.data.append(f"@{len(value)}")
|
| 419 |
+
self.data.append(str(value))
|
| 420 |
+
|
| 421 |
+
def write_literal_str(self, value: str) -> None:
|
| 422 |
+
self.write_str(value) # just for SAB files important
|
| 423 |
+
|
| 424 |
+
def write_ptr(self, entity: AcisEntity) -> None:
|
| 425 |
+
record = NULL_PTR
|
| 426 |
+
if not entity.is_none:
|
| 427 |
+
record = self.exporter.get_record(entity)
|
| 428 |
+
self.data.append(record)
|
| 429 |
+
|
| 430 |
+
def write_transform(self, data: list[str]) -> None:
|
| 431 |
+
self.data.extend(data)
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/__init__.cpython-311.pyc
ADDED
|
Binary file (202 Bytes). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_face.cpython-311.pyc
ADDED
|
Binary file (3.88 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_manager.cpython-311.pyc
ADDED
|
Binary file (28.3 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_measurements.cpython-311.pyc
ADDED
|
Binary file (2.74 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/font_synonyms.cpython-311.pyc
ADDED
|
Binary file (414 Bytes). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/fonts.cpython-311.pyc
ADDED
|
Binary file (35.2 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/glyphs.cpython-311.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/lff.cpython-311.pyc
ADDED
|
Binary file (18.9 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/shapefile.cpython-311.pyc
ADDED
|
Binary file (52.6 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/__pycache__/ttfonts.cpython-311.pyc
ADDED
|
Binary file (13.3 kB). View file
|
|
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_face.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import NamedTuple
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FontFace(NamedTuple):
|
| 8 |
+
# filename without parent directories e.g. "OpenSans-Regular.ttf"
|
| 9 |
+
filename: str = ""
|
| 10 |
+
family: str = "sans-serif"
|
| 11 |
+
style: str = "Regular"
|
| 12 |
+
weight: int = 400 # Normal - usWeightClass
|
| 13 |
+
width: int = 5 # Medium(Normal) - usWidthClass
|
| 14 |
+
|
| 15 |
+
@property
|
| 16 |
+
def is_italic(self) -> bool:
|
| 17 |
+
"""Returns ``True`` if font face is italic."""
|
| 18 |
+
return self.style.lower().find("italic") > -1
|
| 19 |
+
|
| 20 |
+
@property
|
| 21 |
+
def is_oblique(self) -> bool:
|
| 22 |
+
"""Returns ``True`` if font face is oblique."""
|
| 23 |
+
return self.style.lower().find("oblique") > -1
|
| 24 |
+
|
| 25 |
+
@property
|
| 26 |
+
def is_bold(self) -> bool:
|
| 27 |
+
"""Returns ``True`` if font face weight > 400."""
|
| 28 |
+
return self.weight > 400
|
| 29 |
+
|
| 30 |
+
@property
|
| 31 |
+
def weight_str(self) -> str:
|
| 32 |
+
"""Returns the :attr:`weight` as string e.g. "Thin", "Normal", "Bold", ..."""
|
| 33 |
+
return get_weight_str(self.weight)
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def width_str(self) -> str:
|
| 37 |
+
"""Returns the :attr:`width` as string e.g. "Condensed", "Expanded", ..."""
|
| 38 |
+
return get_width_str(self.width)
|
| 39 |
+
|
| 40 |
+
def distance(self, font_face: FontFace) -> tuple[int, int]:
|
| 41 |
+
return self.weight - font_face.weight, self.width - font_face.width
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
WEIGHT_STR = {
|
| 45 |
+
100: "Thin",
|
| 46 |
+
200: "ExtraLight",
|
| 47 |
+
300: "Light",
|
| 48 |
+
400: "Normal",
|
| 49 |
+
500: "Medium",
|
| 50 |
+
600: "SemiBold",
|
| 51 |
+
700: "Bold",
|
| 52 |
+
800: "ExtraBold",
|
| 53 |
+
900: "Black",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
WIDTH_STR = {
|
| 57 |
+
1: "UltraCondensed",
|
| 58 |
+
2: "ExtraCondensed",
|
| 59 |
+
3: "Condensed",
|
| 60 |
+
4: "SemiCondensed",
|
| 61 |
+
5: "Medium", # Normal
|
| 62 |
+
6: "SemiExpanded",
|
| 63 |
+
7: "Expanded",
|
| 64 |
+
8: "ExtraExpanded",
|
| 65 |
+
9: "UltraExpanded",
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_weight_str(weight: int) -> str:
|
| 70 |
+
"""Returns the :attr:`weight` as string e.g. "Thin", "Normal", "Bold", ..."""
|
| 71 |
+
key = max(min(round((weight + 1) / 100) * 100, 900), 100)
|
| 72 |
+
return WEIGHT_STR[key]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_width_str(width: int) -> str:
|
| 76 |
+
"""Returns the :attr:`width` as string e.g. "Condensed", "Expanded", ..."""
|
| 77 |
+
key = max(min(width, 9), 1)
|
| 78 |
+
return WIDTH_STR[key]
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_manager.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import pathlib
|
| 6 |
+
from typing import Iterable, NamedTuple, Optional, Sequence
|
| 7 |
+
import os
|
| 8 |
+
import platform
|
| 9 |
+
import json
|
| 10 |
+
import logging
|
| 11 |
+
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from fontTools.ttLib import TTFont, TTLibError
|
| 14 |
+
from .font_face import FontFace
|
| 15 |
+
from . import shapefile, lff
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("ezdxf")
|
| 18 |
+
WINDOWS = "Windows"
|
| 19 |
+
LINUX = "Linux"
|
| 20 |
+
MACOS = "Darwin"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
WIN_SYSTEM_ROOT = os.environ.get("SystemRoot", "C:/Windows")
|
| 24 |
+
WIN_FONT_DIRS = [
|
| 25 |
+
# AutoCAD and BricsCAD do not support fonts installed in the user directory:
|
| 26 |
+
"~/AppData/Local/Microsoft/Windows/Fonts",
|
| 27 |
+
f"{WIN_SYSTEM_ROOT}/Fonts",
|
| 28 |
+
]
|
| 29 |
+
LINUX_FONT_DIRS = [
|
| 30 |
+
"/usr/share/fonts",
|
| 31 |
+
"/usr/local/share/fonts",
|
| 32 |
+
"~/.fonts",
|
| 33 |
+
"~/.local/share/fonts",
|
| 34 |
+
"~/.local/share/texmf/fonts",
|
| 35 |
+
]
|
| 36 |
+
MACOS_FONT_DIRS = ["/Library/Fonts/", "/System/Library/Fonts/"]
|
| 37 |
+
FONT_DIRECTORIES = {
|
| 38 |
+
WINDOWS: WIN_FONT_DIRS,
|
| 39 |
+
LINUX: LINUX_FONT_DIRS,
|
| 40 |
+
MACOS: MACOS_FONT_DIRS,
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
DEFAULT_FONTS = [
|
| 44 |
+
"ArialUni.ttf", # for Windows
|
| 45 |
+
"Arial Unicode.ttf", # for macOS
|
| 46 |
+
"Arial.ttf", # for the case "Arial Unicode" does not exist
|
| 47 |
+
"DejaVuSansCondensed.ttf", # widths of glyphs is similar to Arial
|
| 48 |
+
"DejaVuSans.ttf",
|
| 49 |
+
"LiberationSans-Regular.ttf",
|
| 50 |
+
"OpenSans-Regular.ttf",
|
| 51 |
+
]
|
| 52 |
+
CURRENT_CACHE_VERSION = 2
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class CacheEntry(NamedTuple):
|
| 56 |
+
file_path: Path # full file path e.g. "C:\Windows\Fonts\DejaVuSans.ttf"
|
| 57 |
+
font_face: FontFace
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
GENERIC_FONT_FAMILY = {
|
| 61 |
+
"serif": "DejaVu Serif",
|
| 62 |
+
"sans-serif": "DejaVu Sans",
|
| 63 |
+
"monospace": "DejaVu Sans Mono",
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class FontCache:
|
| 68 |
+
def __init__(self) -> None:
|
| 69 |
+
# cache key is the lowercase ttf font name without parent directories
|
| 70 |
+
# e.g. "arial.ttf" for "C:\Windows\Fonts\Arial.ttf"
|
| 71 |
+
self._cache: dict[str, CacheEntry] = dict()
|
| 72 |
+
|
| 73 |
+
def __contains__(self, font_name: str) -> bool:
|
| 74 |
+
return self.key(font_name) in self._cache
|
| 75 |
+
|
| 76 |
+
def __getitem__(self, item: str) -> CacheEntry:
|
| 77 |
+
return self._cache[self.key(item)]
|
| 78 |
+
|
| 79 |
+
def __setitem__(self, item: str, entry: CacheEntry) -> None:
|
| 80 |
+
self._cache[self.key(item)] = entry
|
| 81 |
+
|
| 82 |
+
def __len__(self):
|
| 83 |
+
return len(self._cache)
|
| 84 |
+
|
| 85 |
+
def clear(self) -> None:
|
| 86 |
+
self._cache.clear()
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def key(font_name: str) -> str:
|
| 90 |
+
return str(font_name).lower()
|
| 91 |
+
|
| 92 |
+
def add_entry(self, font_path: Path, font_face: FontFace) -> None:
|
| 93 |
+
self._cache[self.key(font_path.name)] = CacheEntry(font_path, font_face)
|
| 94 |
+
|
| 95 |
+
def get(self, font_name: str, fallback: str) -> CacheEntry:
|
| 96 |
+
try:
|
| 97 |
+
return self._cache[self.key(font_name)]
|
| 98 |
+
except KeyError:
|
| 99 |
+
entry = self._cache.get(self.key(fallback))
|
| 100 |
+
if entry is not None:
|
| 101 |
+
return entry
|
| 102 |
+
else: # no fallback font available
|
| 103 |
+
raise FontNotFoundError("no fonts available, not even fallback fonts")
|
| 104 |
+
|
| 105 |
+
def find_best_match(self, font_face: FontFace) -> Optional[FontFace]:
|
| 106 |
+
entry = self._cache.get(self.key(font_face.filename), None)
|
| 107 |
+
if entry:
|
| 108 |
+
return entry.font_face
|
| 109 |
+
return self.find_best_match_ex(
|
| 110 |
+
family=font_face.family,
|
| 111 |
+
style=font_face.style,
|
| 112 |
+
weight=font_face.weight,
|
| 113 |
+
width=font_face.width,
|
| 114 |
+
italic=font_face.is_italic,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
def find_best_match_ex(
|
| 118 |
+
self,
|
| 119 |
+
family: str = "sans-serif",
|
| 120 |
+
style: str = "Regular",
|
| 121 |
+
weight: int = 400,
|
| 122 |
+
width: int = 5,
|
| 123 |
+
italic: Optional[bool] = False,
|
| 124 |
+
) -> Optional[FontFace]:
|
| 125 |
+
# italic == None ... ignore italic flag
|
| 126 |
+
family = GENERIC_FONT_FAMILY.get(family, family)
|
| 127 |
+
entries = filter_family(family, self._cache.values())
|
| 128 |
+
if len(entries) == 0:
|
| 129 |
+
return None
|
| 130 |
+
elif len(entries) == 1:
|
| 131 |
+
return entries[0].font_face
|
| 132 |
+
entries_ = filter_style(style, entries)
|
| 133 |
+
if len(entries_) == 1:
|
| 134 |
+
return entries_[0].font_face
|
| 135 |
+
elif len(entries_):
|
| 136 |
+
entries = entries_
|
| 137 |
+
# best match by weight, italic, width
|
| 138 |
+
# Note: the width property is used to prioritize shapefile types:
|
| 139 |
+
# 1st .shx; 2nd: .shp; 3rd: .lff
|
| 140 |
+
result = sorted(
|
| 141 |
+
entries,
|
| 142 |
+
key=lambda e: (
|
| 143 |
+
abs(e.font_face.weight - weight),
|
| 144 |
+
e.font_face.is_italic is not italic,
|
| 145 |
+
abs(e.font_face.width - width),
|
| 146 |
+
),
|
| 147 |
+
)
|
| 148 |
+
return result[0].font_face
|
| 149 |
+
|
| 150 |
+
def loads(self, s: str) -> None:
|
| 151 |
+
cache: dict[str, CacheEntry] = dict()
|
| 152 |
+
try:
|
| 153 |
+
content = json.loads(s)
|
| 154 |
+
except json.JSONDecodeError:
|
| 155 |
+
raise IOError("invalid JSON file format")
|
| 156 |
+
try:
|
| 157 |
+
version = content["version"]
|
| 158 |
+
content = content["font-faces"]
|
| 159 |
+
except KeyError:
|
| 160 |
+
raise IOError("invalid cache file format")
|
| 161 |
+
if version == CURRENT_CACHE_VERSION:
|
| 162 |
+
for entry in content:
|
| 163 |
+
try:
|
| 164 |
+
file_path, family, style, weight, width = entry
|
| 165 |
+
except ValueError:
|
| 166 |
+
raise IOError("invalid cache file format")
|
| 167 |
+
path = Path(file_path) # full path, e.g. "C:\Windows\Fonts\Arial.ttf"
|
| 168 |
+
font_face = FontFace(
|
| 169 |
+
filename=path.name, # file name without parent dirs, e.g. "Arial.ttf"
|
| 170 |
+
family=family, # Arial
|
| 171 |
+
style=style, # Regular
|
| 172 |
+
weight=weight, # 400 (Normal)
|
| 173 |
+
width=width, # 5 (Normal)
|
| 174 |
+
)
|
| 175 |
+
cache[self.key(path.name)] = CacheEntry(path, font_face)
|
| 176 |
+
else:
|
| 177 |
+
raise IOError("invalid cache file version")
|
| 178 |
+
self._cache = cache
|
| 179 |
+
|
| 180 |
+
def dumps(self) -> str:
|
| 181 |
+
faces = [
|
| 182 |
+
(
|
| 183 |
+
str(entry.file_path),
|
| 184 |
+
entry.font_face.family,
|
| 185 |
+
entry.font_face.style,
|
| 186 |
+
entry.font_face.weight,
|
| 187 |
+
entry.font_face.width,
|
| 188 |
+
)
|
| 189 |
+
for entry in self._cache.values()
|
| 190 |
+
]
|
| 191 |
+
data = {"version": CURRENT_CACHE_VERSION, "font-faces": faces}
|
| 192 |
+
return json.dumps(data, indent=2)
|
| 193 |
+
|
| 194 |
+
def print_available_fonts(self, verbose=False) -> None:
|
| 195 |
+
for entry in self._cache.values():
|
| 196 |
+
print(f"{entry.file_path}")
|
| 197 |
+
if not verbose:
|
| 198 |
+
continue
|
| 199 |
+
font_type = entry.file_path.suffix.lower()
|
| 200 |
+
ff = entry.font_face
|
| 201 |
+
if font_type in (".shx", ".shp"):
|
| 202 |
+
print(f" Shape font file: '{ff.filename}'")
|
| 203 |
+
elif font_type == ".lff":
|
| 204 |
+
print(f" LibreCAD font file: '{ff.filename}'")
|
| 205 |
+
else:
|
| 206 |
+
print(f" TrueType/OpenType font file: '{ff.filename}'")
|
| 207 |
+
print(f" family: {ff.family}")
|
| 208 |
+
print(f" style: {ff.style}")
|
| 209 |
+
print(f" weight: {ff.weight}, {ff.weight_str}")
|
| 210 |
+
print(f" width: {ff.width}, {ff.width_str}")
|
| 211 |
+
print(f"\nfound {len(self._cache)} fonts")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def filter_family(family: str, entries: Iterable[CacheEntry]) -> list[CacheEntry]:
|
| 215 |
+
key = str(family).lower()
|
| 216 |
+
return [e for e in entries if e.font_face.family.lower().startswith(key)]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def filter_style(style: str, entries: Iterable[CacheEntry]) -> list[CacheEntry]:
|
| 220 |
+
key = str(style).lower()
|
| 221 |
+
return [e for e in entries if key in e.font_face.style.lower()]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# TrueType and OpenType fonts:
|
| 225 |
+
# Note: CAD applications like AutoCAD/BricsCAD do not support OpenType fonts!
|
| 226 |
+
SUPPORTED_TTF_TYPES = {".ttf", ".ttc", ".otf"}
|
| 227 |
+
# Basic stroke-fonts included in CAD applications:
|
| 228 |
+
SUPPORTED_SHAPE_FILES = {".shx", ".shp", ".lff"}
|
| 229 |
+
NO_FONT_FACE = FontFace()
|
| 230 |
+
FALLBACK_SHAPE_FILES = ["txt.shx", "txt.shp", "iso.shx", "iso.shp"]
|
| 231 |
+
FALLBACK_LFF = ["standard.lff", "iso.lff", "simplex.lff"]
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class FontNotFoundError(Exception):
|
| 235 |
+
pass
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class UnsupportedFont(Exception):
|
| 239 |
+
pass
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class FontManager:
|
| 243 |
+
def __init__(self) -> None:
|
| 244 |
+
self.platform = platform.system()
|
| 245 |
+
self._font_cache: FontCache = FontCache()
|
| 246 |
+
self._match_cache: dict[int, Optional[FontFace]] = dict()
|
| 247 |
+
self._loaded_ttf_fonts: dict[str, TTFont] = dict()
|
| 248 |
+
self._loaded_shape_file_glyph_caches: dict[str, shapefile.GlyphCache] = dict()
|
| 249 |
+
self._loaded_lff_glyph_caches: dict[str, lff.GlyphCache] = dict()
|
| 250 |
+
self._fallback_font_name = ""
|
| 251 |
+
self._fallback_shape_file = ""
|
| 252 |
+
self._fallback_lff = ""
|
| 253 |
+
|
| 254 |
+
def print_available_fonts(self, verbose=False) -> None:
|
| 255 |
+
self._font_cache.print_available_fonts(verbose=verbose)
|
| 256 |
+
|
| 257 |
+
def has_font(self, font_name: str) -> bool:
|
| 258 |
+
return font_name in self._font_cache
|
| 259 |
+
|
| 260 |
+
def clear(self) -> None:
|
| 261 |
+
self._font_cache = FontCache()
|
| 262 |
+
self._loaded_ttf_fonts.clear()
|
| 263 |
+
self._fallback_font_name = ""
|
| 264 |
+
|
| 265 |
+
def fallback_font_name(self) -> str:
|
| 266 |
+
fallback_name = self._fallback_font_name
|
| 267 |
+
if fallback_name:
|
| 268 |
+
return fallback_name
|
| 269 |
+
fallback_name = DEFAULT_FONTS[0]
|
| 270 |
+
for name in DEFAULT_FONTS:
|
| 271 |
+
try:
|
| 272 |
+
cache_entry = self._font_cache.get(name, fallback_name)
|
| 273 |
+
fallback_name = cache_entry.file_path.name
|
| 274 |
+
break
|
| 275 |
+
except FontNotFoundError:
|
| 276 |
+
pass
|
| 277 |
+
self._fallback_font_name = fallback_name
|
| 278 |
+
return fallback_name
|
| 279 |
+
|
| 280 |
+
def fallback_shapefile(self) -> str:
|
| 281 |
+
fallback_shape_file = self._fallback_shape_file
|
| 282 |
+
if fallback_shape_file:
|
| 283 |
+
return fallback_shape_file
|
| 284 |
+
|
| 285 |
+
for name in FALLBACK_SHAPE_FILES:
|
| 286 |
+
if name in self._font_cache:
|
| 287 |
+
self._fallback_shape_file = name
|
| 288 |
+
return name
|
| 289 |
+
return ""
|
| 290 |
+
|
| 291 |
+
def fallback_lff(self) -> str:
|
| 292 |
+
fallback_lff = self._fallback_lff
|
| 293 |
+
if fallback_lff:
|
| 294 |
+
return fallback_lff
|
| 295 |
+
|
| 296 |
+
for name in FALLBACK_SHAPE_FILES:
|
| 297 |
+
if name in self._font_cache:
|
| 298 |
+
self._fallback_shape_file = name
|
| 299 |
+
return name
|
| 300 |
+
return ""
|
| 301 |
+
|
| 302 |
+
def get_ttf_font(self, font_name: str, font_number: int = 0) -> TTFont:
|
| 303 |
+
try:
|
| 304 |
+
return self._loaded_ttf_fonts[font_name]
|
| 305 |
+
except KeyError:
|
| 306 |
+
pass
|
| 307 |
+
fallback_name = self.fallback_font_name()
|
| 308 |
+
try:
|
| 309 |
+
font = TTFont(
|
| 310 |
+
self._font_cache.get(font_name, fallback_name).file_path,
|
| 311 |
+
fontNumber=font_number,
|
| 312 |
+
)
|
| 313 |
+
except IOError as e:
|
| 314 |
+
raise FontNotFoundError(str(e))
|
| 315 |
+
except TTLibError as e:
|
| 316 |
+
raise FontNotFoundError(str(e))
|
| 317 |
+
self._loaded_ttf_fonts[font_name] = font
|
| 318 |
+
return font
|
| 319 |
+
|
| 320 |
+
def ttf_font_from_font_face(self, font_face: FontFace) -> TTFont:
|
| 321 |
+
return self.get_ttf_font(Path(font_face.filename).name)
|
| 322 |
+
|
| 323 |
+
def get_shapefile_glyph_cache(self, font_name: str) -> shapefile.GlyphCache:
|
| 324 |
+
try:
|
| 325 |
+
return self._loaded_shape_file_glyph_caches[font_name]
|
| 326 |
+
except KeyError:
|
| 327 |
+
pass
|
| 328 |
+
fallback_name = self.fallback_shapefile()
|
| 329 |
+
try:
|
| 330 |
+
file_path = self._font_cache.get(font_name, fallback_name).file_path
|
| 331 |
+
except KeyError:
|
| 332 |
+
raise FontNotFoundError(f"shape font '{font_name}' not found")
|
| 333 |
+
try:
|
| 334 |
+
file = shapefile.readfile(str(file_path))
|
| 335 |
+
except IOError:
|
| 336 |
+
raise FontNotFoundError(f"shape file '{file_path}' not found")
|
| 337 |
+
except shapefile.UnsupportedShapeFile as e:
|
| 338 |
+
raise UnsupportedFont(f"unsupported font '{file_path}': {str(e)}")
|
| 339 |
+
try:
|
| 340 |
+
glyph_cache = shapefile.GlyphCache(file)
|
| 341 |
+
except Exception:
|
| 342 |
+
raise UnsupportedFont(f"can't create glyph-cache for font '{file_path}'.")
|
| 343 |
+
self._loaded_shape_file_glyph_caches[font_name] = glyph_cache
|
| 344 |
+
return glyph_cache
|
| 345 |
+
|
| 346 |
+
def get_lff_glyph_cache(self, font_name: str) -> lff.GlyphCache:
|
| 347 |
+
try:
|
| 348 |
+
return self._loaded_lff_glyph_caches[font_name]
|
| 349 |
+
except KeyError:
|
| 350 |
+
pass
|
| 351 |
+
fallback_name = self.fallback_lff()
|
| 352 |
+
try:
|
| 353 |
+
file_path = self._font_cache.get(font_name, fallback_name).file_path
|
| 354 |
+
except KeyError:
|
| 355 |
+
raise FontNotFoundError(f"LibreCAD font '{font_name}' not found")
|
| 356 |
+
try:
|
| 357 |
+
s = pathlib.Path(file_path).read_text(encoding="utf8")
|
| 358 |
+
font = lff.loads(s)
|
| 359 |
+
except IOError:
|
| 360 |
+
raise FontNotFoundError(f"LibreCAD font file '{file_path}' not found")
|
| 361 |
+
try:
|
| 362 |
+
glyph_cache = lff.GlyphCache(font)
|
| 363 |
+
except Exception:
|
| 364 |
+
raise UnsupportedFont(f"can't create glyph-cache for font '{file_path}'.")
|
| 365 |
+
|
| 366 |
+
self._loaded_lff_glyph_caches[font_name] = glyph_cache
|
| 367 |
+
return glyph_cache
|
| 368 |
+
|
| 369 |
+
def get_font_face(self, font_name: str) -> FontFace:
|
| 370 |
+
cache_entry = self._font_cache.get(font_name, self.fallback_font_name())
|
| 371 |
+
return cache_entry.font_face
|
| 372 |
+
|
| 373 |
+
def find_best_match(
|
| 374 |
+
self,
|
| 375 |
+
family: str = "sans-serif",
|
| 376 |
+
style: str = "Regular",
|
| 377 |
+
weight=400,
|
| 378 |
+
width=5,
|
| 379 |
+
italic: Optional[bool] = False,
|
| 380 |
+
) -> Optional[FontFace]:
|
| 381 |
+
key = hash((family, style, weight, width, italic))
|
| 382 |
+
try:
|
| 383 |
+
return self._match_cache[key]
|
| 384 |
+
except KeyError:
|
| 385 |
+
pass
|
| 386 |
+
font_face = self._font_cache.find_best_match_ex(
|
| 387 |
+
family, style, weight, width, italic
|
| 388 |
+
)
|
| 389 |
+
self._match_cache[key] = font_face
|
| 390 |
+
return font_face
|
| 391 |
+
|
| 392 |
+
def find_font_name(self, font_face: FontFace) -> str:
|
| 393 |
+
"""Returns the font file name of the font without parent directories
|
| 394 |
+
e.g. "LiberationSans-Regular.ttf".
|
| 395 |
+
"""
|
| 396 |
+
font_face = self._font_cache.find_best_match(font_face) # type: ignore
|
| 397 |
+
if font_face is None:
|
| 398 |
+
font_face = self.get_font_face(self.fallback_font_name())
|
| 399 |
+
return font_face.filename
|
| 400 |
+
else:
|
| 401 |
+
return font_face.filename
|
| 402 |
+
|
| 403 |
+
def build(self, folders: Optional[Sequence[str]] = None, support_dirs=True) -> None:
|
| 404 |
+
"""Adds all supported font types located in the given `folders` to the font
|
| 405 |
+
manager. If no directories are specified, the known font folders for Windows,
|
| 406 |
+
Linux and macOS are searched by default, except `support_dirs` is ``False``.
|
| 407 |
+
Searches recursively all subdirectories.
|
| 408 |
+
|
| 409 |
+
The folders stored in the config SUPPORT_DIRS option are scanned recursively for
|
| 410 |
+
.shx, .shp and .lff fonts, the basic stroke fonts included in CAD applications.
|
| 411 |
+
|
| 412 |
+
"""
|
| 413 |
+
from ezdxf._options import options
|
| 414 |
+
|
| 415 |
+
if folders:
|
| 416 |
+
dirs = list(folders)
|
| 417 |
+
else:
|
| 418 |
+
dirs = FONT_DIRECTORIES.get(self.platform, LINUX_FONT_DIRS)
|
| 419 |
+
if support_dirs:
|
| 420 |
+
dirs = dirs + list(options.support_dirs)
|
| 421 |
+
self.scan_all(dirs)
|
| 422 |
+
|
| 423 |
+
def add_synonyms(self, synonyms: dict[str, str], reverse=True) -> None:
|
| 424 |
+
font_cache = self._font_cache
|
| 425 |
+
for font_name, synonym in synonyms.items():
|
| 426 |
+
if not font_name in font_cache:
|
| 427 |
+
continue
|
| 428 |
+
if synonym in font_cache:
|
| 429 |
+
continue
|
| 430 |
+
cache_entry = font_cache[font_name]
|
| 431 |
+
font_cache[synonym] = cache_entry
|
| 432 |
+
if reverse:
|
| 433 |
+
self.add_synonyms({v: k for k, v in synonyms.items()}, reverse=False)
|
| 434 |
+
|
| 435 |
+
def scan_all(self, folders: Iterable[str]) -> None:
|
| 436 |
+
for folder in folders:
|
| 437 |
+
folder = folder.strip("'\"") # strip quotes
|
| 438 |
+
if not folder:
|
| 439 |
+
continue
|
| 440 |
+
try:
|
| 441 |
+
self.scan_folder(Path(folder).expanduser())
|
| 442 |
+
except PermissionError as e:
|
| 443 |
+
print(str(e))
|
| 444 |
+
continue
|
| 445 |
+
|
| 446 |
+
def scan_folder(self, folder: Path):
|
| 447 |
+
if not folder.exists():
|
| 448 |
+
return
|
| 449 |
+
for file in folder.iterdir():
|
| 450 |
+
if file.is_dir():
|
| 451 |
+
self.scan_folder(file)
|
| 452 |
+
continue
|
| 453 |
+
ext = file.suffix.lower()
|
| 454 |
+
if ext in SUPPORTED_TTF_TYPES:
|
| 455 |
+
try:
|
| 456 |
+
font_face = get_ttf_font_face(file)
|
| 457 |
+
except Exception as e:
|
| 458 |
+
logger.warning(f"cannot open font '{file}': {str(e)}")
|
| 459 |
+
else:
|
| 460 |
+
self._font_cache.add_entry(file, font_face)
|
| 461 |
+
elif ext in SUPPORTED_SHAPE_FILES:
|
| 462 |
+
font_face = get_shape_file_font_face(file)
|
| 463 |
+
self._font_cache.add_entry(file, font_face)
|
| 464 |
+
|
| 465 |
+
def dumps(self) -> str:
|
| 466 |
+
return self._font_cache.dumps()
|
| 467 |
+
|
| 468 |
+
def loads(self, s: str) -> None:
|
| 469 |
+
self._font_cache.loads(s)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def normalize_style(style: str) -> str:
|
| 473 |
+
if style in {"Book"}:
|
| 474 |
+
style = "Regular"
|
| 475 |
+
return style
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def get_ttf_font_face(font_path: Path) -> FontFace:
|
| 479 |
+
"""The caller should catch ALL exception (see scan_folder function above) - strange
|
| 480 |
+
things can happen when reading TTF files.
|
| 481 |
+
"""
|
| 482 |
+
ttf = TTFont(font_path, fontNumber=0)
|
| 483 |
+
names = ttf["name"].names
|
| 484 |
+
family = ""
|
| 485 |
+
style = ""
|
| 486 |
+
for record in names:
|
| 487 |
+
if record.nameID == 1:
|
| 488 |
+
family = record.string.decode(record.getEncoding())
|
| 489 |
+
elif record.nameID == 2:
|
| 490 |
+
style = record.string.decode(record.getEncoding())
|
| 491 |
+
if family and style:
|
| 492 |
+
break
|
| 493 |
+
|
| 494 |
+
try:
|
| 495 |
+
os2_table = ttf["OS/2"]
|
| 496 |
+
except Exception: # e.g. ComickBook_Simple.ttf has an invalid "OS/2" table
|
| 497 |
+
logger.info(f"cannot load OS/2 table of font '{font_path.name}'")
|
| 498 |
+
weight = 400
|
| 499 |
+
width = 5
|
| 500 |
+
else:
|
| 501 |
+
weight = os2_table.usWeightClass
|
| 502 |
+
width = os2_table.usWidthClass
|
| 503 |
+
return FontFace(
|
| 504 |
+
filename=font_path.name,
|
| 505 |
+
family=family,
|
| 506 |
+
style=normalize_style(style),
|
| 507 |
+
width=width,
|
| 508 |
+
weight=weight,
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def get_shape_file_font_face(font_path: Path) -> FontFace:
|
| 513 |
+
ext = font_path.suffix.lower()
|
| 514 |
+
# Note: the width property is not defined in shapefiles and is used to
|
| 515 |
+
# prioritize the shapefile types for find_best_match():
|
| 516 |
+
# 1st .shx; 2nd: .shp; 3rd: .lff
|
| 517 |
+
|
| 518 |
+
width = 5
|
| 519 |
+
if ext == ".shp":
|
| 520 |
+
width = 6
|
| 521 |
+
if ext == ".lff":
|
| 522 |
+
width = 7
|
| 523 |
+
|
| 524 |
+
return FontFace(
|
| 525 |
+
filename=font_path.name, # "txt.shx", "simplex.shx", ...
|
| 526 |
+
family=font_path.stem.lower(), # "txt", "simplex", ...
|
| 527 |
+
style=font_path.suffix.lower(), # ".shx", ".shp" or ".lff"
|
| 528 |
+
width=width,
|
| 529 |
+
weight=400,
|
| 530 |
+
)
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_measurements.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import NamedTuple
|
| 5 |
+
# A Visual Guide to the Anatomy of Typography: https://visme.co/blog/type-anatomy/
|
| 6 |
+
# Anatomy of a Character: https://www.fonts.com/content/learning/fontology/level-1/type-anatomy/anatomy
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class FontMeasurements(NamedTuple):
|
| 10 |
+
baseline: float
|
| 11 |
+
cap_height: float
|
| 12 |
+
x_height: float
|
| 13 |
+
descender_height: float
|
| 14 |
+
|
| 15 |
+
def scale(self, factor: float = 1.0) -> FontMeasurements:
|
| 16 |
+
return FontMeasurements(
|
| 17 |
+
self.baseline * factor,
|
| 18 |
+
self.cap_height * factor,
|
| 19 |
+
self.x_height * factor,
|
| 20 |
+
self.descender_height * factor,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
def shift(self, distance: float = 0.0) -> FontMeasurements:
|
| 24 |
+
return FontMeasurements(
|
| 25 |
+
self.baseline + distance,
|
| 26 |
+
self.cap_height,
|
| 27 |
+
self.x_height,
|
| 28 |
+
self.descender_height,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
def scale_from_baseline(self, desired_cap_height: float) -> FontMeasurements:
|
| 32 |
+
factor = desired_cap_height / self.cap_height
|
| 33 |
+
return FontMeasurements(
|
| 34 |
+
self.baseline,
|
| 35 |
+
desired_cap_height,
|
| 36 |
+
self.x_height * factor,
|
| 37 |
+
self.descender_height * factor,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def cap_top(self) -> float:
|
| 42 |
+
return self.baseline + self.cap_height
|
| 43 |
+
|
| 44 |
+
@property
|
| 45 |
+
def x_top(self) -> float:
|
| 46 |
+
return self.baseline + self.x_height
|
| 47 |
+
|
| 48 |
+
@property
|
| 49 |
+
def bottom(self) -> float:
|
| 50 |
+
return self.baseline - self.descender_height
|
| 51 |
+
|
| 52 |
+
@property
|
| 53 |
+
def total_height(self) -> float:
|
| 54 |
+
return self.cap_height + self.descender_height
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/font_synonyms.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2024, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
|
| 4 |
+
FONT_SYNONYMS = {
|
| 5 |
+
"ariblk.ttf": "Arial Black.ttf",
|
| 6 |
+
"comic.ttf": "Comic Sans MS.ttf",
|
| 7 |
+
"arialuni.ttf": "Arial Unicode.ttf",
|
| 8 |
+
"times.ttf": "Times New Roman.ttf",
|
| 9 |
+
"trebuc.ttf": "Trebuchet MS.ttf",
|
| 10 |
+
}
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/fonts.py
ADDED
|
@@ -0,0 +1,745 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2021-2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing import Optional, TYPE_CHECKING, cast
|
| 5 |
+
import abc
|
| 6 |
+
import enum
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
import pathlib
|
| 10 |
+
|
| 11 |
+
from ezdxf import options
|
| 12 |
+
from .font_face import FontFace
|
| 13 |
+
from .font_manager import (
|
| 14 |
+
FontManager,
|
| 15 |
+
SUPPORTED_TTF_TYPES,
|
| 16 |
+
FontNotFoundError,
|
| 17 |
+
UnsupportedFont,
|
| 18 |
+
)
|
| 19 |
+
from .font_synonyms import FONT_SYNONYMS
|
| 20 |
+
from .font_measurements import FontMeasurements
|
| 21 |
+
from .glyphs import GlyphPath, Glyphs
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from ezdxf.document import Drawing
|
| 25 |
+
from ezdxf.entities import DXFEntity, Textstyle
|
| 26 |
+
|
| 27 |
+
logger = logging.getLogger("ezdxf")
|
| 28 |
+
FONT_MANAGER_CACHE_FILE = "font_manager_cache.json"
|
| 29 |
+
# SUT = System Under Test, see build_sut_font_manager_cache() function
|
| 30 |
+
SUT_FONT_MANAGER_CACHE = False
|
| 31 |
+
CACHE_DIRECTORY = ".cache"
|
| 32 |
+
font_manager = FontManager()
|
| 33 |
+
|
| 34 |
+
SHX_FONTS = {
|
| 35 |
+
# See examples in: CADKitSamples/Shapefont.dxf
|
| 36 |
+
# Shape file structure is not documented, therefore, replace these fonts by
|
| 37 |
+
# true type fonts.
|
| 38 |
+
# `None` is for: use the default font.
|
| 39 |
+
#
|
| 40 |
+
# All these replacement TTF fonts have a copyright remark:
|
| 41 |
+
# "(c) Copyright 1996 by Autodesk Inc., All rights reserved"
|
| 42 |
+
# and therefore can not be included in ezdxf or the associated repository!
|
| 43 |
+
# You got them if you install any Autodesk product, like the free available
|
| 44 |
+
# DWG/DXF viewer "TrueView" : https://www.autodesk.com/viewers
|
| 45 |
+
"AMGDT": "amgdt___.ttf", # Tolerance symbols
|
| 46 |
+
"AMGDT.SHX": "amgdt___.ttf",
|
| 47 |
+
"COMPLEX": "complex_.ttf",
|
| 48 |
+
"COMPLEX.SHX": "complex_.ttf",
|
| 49 |
+
"ISOCP": "isocp.ttf",
|
| 50 |
+
"ISOCP.SHX": "isocp.ttf",
|
| 51 |
+
"ITALIC": "italicc_.ttf",
|
| 52 |
+
"ITALIC.SHX": "italicc_.ttf",
|
| 53 |
+
"GOTHICG": "gothicg_.ttf",
|
| 54 |
+
"GOTHICG.SHX": "gothicg_.ttf",
|
| 55 |
+
"GREEKC": "greekc.ttf",
|
| 56 |
+
"GREEKC.SHX": "greekc.ttf",
|
| 57 |
+
"ROMANS": "romans__.ttf",
|
| 58 |
+
"ROMANS.SHX": "romans__.ttf",
|
| 59 |
+
"SCRIPTS": "scripts_.ttf",
|
| 60 |
+
"SCRIPTS.SHX": "scripts_.ttf",
|
| 61 |
+
"SCRIPTC": "scriptc_.ttf",
|
| 62 |
+
"SCRIPTC.SHX": "scriptc_.ttf",
|
| 63 |
+
"SIMPLEX": "simplex_.ttf",
|
| 64 |
+
"SIMPLEX.SHX": "simplex_.ttf",
|
| 65 |
+
"SYMATH": "symath__.ttf",
|
| 66 |
+
"SYMATH.SHX": "symath__.ttf",
|
| 67 |
+
"SYMAP": "symap___.ttf",
|
| 68 |
+
"SYMAP.SHX": "symap___.ttf",
|
| 69 |
+
"SYMETEO": "symeteo_.ttf",
|
| 70 |
+
"SYMETEO.SHX": "symeteo_.ttf",
|
| 71 |
+
"TXT": "txt_____.ttf", # Default AutoCAD font
|
| 72 |
+
"TXT.SHX": "txt_____.ttf",
|
| 73 |
+
}
|
| 74 |
+
LFF_FONTS = {
|
| 75 |
+
"TXT": "standard.lff",
|
| 76 |
+
"TXT.SHX": "standard.lff",
|
| 77 |
+
}
|
| 78 |
+
TTF_TO_SHX = {v: k for k, v in SHX_FONTS.items() if k.endswith("SHX")}
|
| 79 |
+
DESCENDER_FACTOR = 0.333 # from TXT SHX font - just guessing
|
| 80 |
+
X_HEIGHT_FACTOR = 0.666 # from TXT SHX font - just guessing
|
| 81 |
+
MONOSPACE = "*monospace" # last resort fallback font only for measurement
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def map_shx_to_ttf(font_name: str) -> str:
|
| 85 |
+
"""Map .shx font names to .ttf file names. e.g. "TXT" -> "txt_____.ttf" """
|
| 86 |
+
# Map SHX fonts to True Type Fonts:
|
| 87 |
+
font_upper = font_name.upper()
|
| 88 |
+
if font_upper in SHX_FONTS:
|
| 89 |
+
font_name = SHX_FONTS[font_upper]
|
| 90 |
+
return font_name
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def map_shx_to_lff(font_name: str) -> str:
|
| 94 |
+
"""Map .shx font names to .lff file names. e.g. "TXT" -> "standard.lff" """
|
| 95 |
+
font_upper = font_name.upper()
|
| 96 |
+
name = LFF_FONTS.get(font_upper, "")
|
| 97 |
+
if font_manager.has_font(name):
|
| 98 |
+
return name
|
| 99 |
+
if not font_upper.endswith(".SHX"):
|
| 100 |
+
lff_name = font_name + ".lff"
|
| 101 |
+
else:
|
| 102 |
+
lff_name = font_name[:-4] + ".lff"
|
| 103 |
+
if font_manager.has_font(lff_name):
|
| 104 |
+
return lff_name
|
| 105 |
+
return font_name
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def is_shx_font_name(font_name: str) -> bool:
|
| 109 |
+
name = font_name.lower()
|
| 110 |
+
if name.endswith(".shx"):
|
| 111 |
+
return True
|
| 112 |
+
if "." not in name:
|
| 113 |
+
return True
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def map_ttf_to_shx(ttf: str) -> Optional[str]:
|
| 118 |
+
"""Maps .ttf filenames to .shx font names. e.g. "txt_____.ttf" -> "TXT" """
|
| 119 |
+
return TTF_TO_SHX.get(ttf.lower())
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def build_system_font_cache() -> None:
|
| 123 |
+
"""Builds or rebuilds the font manager cache. The font manager cache has a fixed
|
| 124 |
+
location in the cache directory of the users home directory "~/.cache/ezdxf" or the
|
| 125 |
+
directory specified by the environment variable "XDG_CACHE_HOME".
|
| 126 |
+
"""
|
| 127 |
+
build_font_manager_cache(_get_font_manager_path())
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def find_font_face(font_name: str) -> FontFace:
|
| 131 |
+
"""Returns the :class:`FontFace` definition for the given font filename
|
| 132 |
+
e.g. "LiberationSans-Regular.ttf".
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
return font_manager.get_font_face(font_name)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def get_font_face(font_name: str, map_shx=True) -> FontFace:
|
| 139 |
+
"""Returns the :class:`FontFace` definition for the given font filename
|
| 140 |
+
e.g. "LiberationSans-Regular.ttf".
|
| 141 |
+
|
| 142 |
+
This function translates a DXF font definition by the TTF font file name into a
|
| 143 |
+
:class:`FontFace` object. Returns the :class:`FontFace` of the default font when a
|
| 144 |
+
font is not available on the current system.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
font_name: raw font file name as stored in the
|
| 148 |
+
:class:`~ezdxf.entities.Textstyle` entity
|
| 149 |
+
map_shx: maps SHX font names to TTF replacement fonts,
|
| 150 |
+
e.g. "TXT" -> "txt_____.ttf"
|
| 151 |
+
|
| 152 |
+
"""
|
| 153 |
+
if not isinstance(font_name, str):
|
| 154 |
+
raise TypeError("font_name has invalid type")
|
| 155 |
+
if map_shx:
|
| 156 |
+
font_name = map_shx_to_ttf(font_name)
|
| 157 |
+
return find_font_face(font_name)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def resolve_shx_font_name(font_name: str, order: str) -> str:
|
| 161 |
+
"""Resolves a .shx font name, the argument `order` defines the resolve order:
|
| 162 |
+
|
| 163 |
+
- "t" = map .shx fonts to TrueType fonts (.ttf, .ttc, .otf)
|
| 164 |
+
- "s" = use shapefile fonts (.shx, .shp)
|
| 165 |
+
- "l" = map .shx fonts to LibreCAD fonts (.lff)
|
| 166 |
+
|
| 167 |
+
"""
|
| 168 |
+
if len(order) == 0:
|
| 169 |
+
return font_name
|
| 170 |
+
order = order.lower()
|
| 171 |
+
for type_str in order:
|
| 172 |
+
if type_str == "t":
|
| 173 |
+
name = map_shx_to_ttf(font_name)
|
| 174 |
+
if font_manager.has_font(name):
|
| 175 |
+
return name
|
| 176 |
+
elif type_str == "s":
|
| 177 |
+
if not font_name.lower().endswith(".shx"):
|
| 178 |
+
font_name += ".shx"
|
| 179 |
+
if font_manager.has_font(font_name):
|
| 180 |
+
return font_name
|
| 181 |
+
elif type_str == "l":
|
| 182 |
+
name = map_shx_to_lff(font_name)
|
| 183 |
+
if font_manager.has_font(name):
|
| 184 |
+
return name
|
| 185 |
+
return font_name
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def resolve_font_face(font_name: str, order="tsl") -> FontFace:
|
| 189 |
+
"""Returns the :class:`FontFace` definition for the given font filename
|
| 190 |
+
e.g. "LiberationSans-Regular.ttf".
|
| 191 |
+
|
| 192 |
+
This function translates a DXF font definition by the TTF font file name into a
|
| 193 |
+
:class:`FontFace` object. Returns the :class:`FontFace` of the default font when a
|
| 194 |
+
font is not available on the current system.
|
| 195 |
+
|
| 196 |
+
The order argument defines the resolve order for .shx fonts:
|
| 197 |
+
|
| 198 |
+
- "t" = map .shx fonts to TrueType fonts (.ttf, .ttc, .otf)
|
| 199 |
+
- "s" = use shapefile fonts (.shx, .shp)
|
| 200 |
+
- "l" = map .shx fonts to LibreCAD fonts (.lff)
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
font_name: raw font file name as stored in the
|
| 204 |
+
:class:`~ezdxf.entities.Textstyle` entity
|
| 205 |
+
order: resolving order
|
| 206 |
+
|
| 207 |
+
"""
|
| 208 |
+
if not isinstance(font_name, str):
|
| 209 |
+
raise TypeError("font_name has invalid type")
|
| 210 |
+
if is_shx_font_name(font_name):
|
| 211 |
+
font_name = resolve_shx_font_name(font_name, order)
|
| 212 |
+
return find_font_face(font_name)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def get_font_measurements(font_name: str, map_shx=True) -> FontMeasurements:
|
| 216 |
+
"""Get :class:`FontMeasurements` for the given font filename
|
| 217 |
+
e.g. "LiberationSans-Regular.ttf".
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
font_name: raw font file name as stored in the
|
| 221 |
+
:class:`~ezdxf.entities.Textstyle` entity
|
| 222 |
+
map_shx: maps SHX font names to TTF replacement fonts,
|
| 223 |
+
e.g. "TXT" -> "txt_____.ttf"
|
| 224 |
+
|
| 225 |
+
"""
|
| 226 |
+
if map_shx:
|
| 227 |
+
font_name = map_shx_to_ttf(font_name)
|
| 228 |
+
elif is_shx_font_name(font_name):
|
| 229 |
+
return FontMeasurements(
|
| 230 |
+
baseline=0,
|
| 231 |
+
cap_height=1,
|
| 232 |
+
x_height=X_HEIGHT_FACTOR,
|
| 233 |
+
descender_height=DESCENDER_FACTOR,
|
| 234 |
+
)
|
| 235 |
+
font = TrueTypeFont(font_name, cap_height=1)
|
| 236 |
+
return font.measurements
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def find_best_match(
|
| 240 |
+
*,
|
| 241 |
+
family: str = "sans-serif",
|
| 242 |
+
style: str = "Regular",
|
| 243 |
+
weight: int = 400,
|
| 244 |
+
width: int = 5,
|
| 245 |
+
italic: Optional[bool] = False,
|
| 246 |
+
) -> Optional[FontFace]:
|
| 247 |
+
"""Returns a :class:`FontFace` that matches the given properties best. The search
|
| 248 |
+
is based the descriptive properties and not on comparing glyph shapes. Returns
|
| 249 |
+
``None`` if no font was found.
|
| 250 |
+
|
| 251 |
+
Args:
|
| 252 |
+
family: font family name e.g. "sans-serif", "Liberation Sans"
|
| 253 |
+
style: font style e.g. "Regular", "Italic", "Bold"
|
| 254 |
+
weight: weight in the range from 1-1000 (usWeightClass)
|
| 255 |
+
width: width in the range from 1-9 (usWidthClass)
|
| 256 |
+
italic: ``True``, ``False`` or ``None`` to ignore this flag
|
| 257 |
+
|
| 258 |
+
"""
|
| 259 |
+
return font_manager.find_best_match(family, style, weight, width, italic)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def find_font_file_name(font_face: FontFace) -> str:
|
| 263 |
+
"""Returns the true type font file name without parent directories e.g. "Arial.ttf"."""
|
| 264 |
+
return font_manager.find_font_name(font_face)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def load():
|
| 268 |
+
"""Reload all cache files. The cache files are loaded automatically at the import
|
| 269 |
+
of `ezdxf`.
|
| 270 |
+
"""
|
| 271 |
+
_load_font_manager()
|
| 272 |
+
# Add font name synonyms, see discussion #1002
|
| 273 |
+
# Find macOS fonts on Windows/Linux and vice versa.
|
| 274 |
+
font_manager.add_synonyms(FONT_SYNONYMS, reverse=True)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def _get_font_manager_path():
|
| 278 |
+
cache_path = options.xdg_path("XDG_CACHE_HOME", CACHE_DIRECTORY)
|
| 279 |
+
return cache_path / FONT_MANAGER_CACHE_FILE
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _load_font_manager() -> None:
|
| 283 |
+
fm_path = _get_font_manager_path()
|
| 284 |
+
if fm_path.exists():
|
| 285 |
+
try:
|
| 286 |
+
font_manager.loads(fm_path.read_text())
|
| 287 |
+
return
|
| 288 |
+
except IOError as e:
|
| 289 |
+
logger.info(f"Error loading cache file: {str(e)}")
|
| 290 |
+
build_font_manager_cache(fm_path)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def build_sut_font_manager_cache(repo_font_path: pathlib.Path) -> None:
|
| 294 |
+
"""Load font manger cache for system under test (sut).
|
| 295 |
+
|
| 296 |
+
Load the fonts included in the repository folder "./fonts" to guarantee the tests
|
| 297 |
+
have the same fonts available on all systems.
|
| 298 |
+
|
| 299 |
+
This function should be called from "conftest.py".
|
| 300 |
+
|
| 301 |
+
"""
|
| 302 |
+
global SUT_FONT_MANAGER_CACHE
|
| 303 |
+
SUT_FONT_MANAGER_CACHE = True
|
| 304 |
+
font_manager.clear()
|
| 305 |
+
cache_file = repo_font_path / "font_manager_cache.json"
|
| 306 |
+
if cache_file.exists():
|
| 307 |
+
try:
|
| 308 |
+
font_manager.loads(cache_file.read_text())
|
| 309 |
+
return
|
| 310 |
+
except IOError as e:
|
| 311 |
+
print(f"Error loading cache file: {str(e)}")
|
| 312 |
+
font_manager.build([str(repo_font_path)], support_dirs=False)
|
| 313 |
+
s = font_manager.dumps()
|
| 314 |
+
try:
|
| 315 |
+
cache_file.write_text(s)
|
| 316 |
+
except IOError as e:
|
| 317 |
+
print(f"Error writing cache file: {str(e)}")
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def make_cache_directory(path: pathlib.Path) -> None:
|
| 321 |
+
if not path.exists():
|
| 322 |
+
try:
|
| 323 |
+
path.mkdir(parents=True)
|
| 324 |
+
except IOError:
|
| 325 |
+
pass
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def build_font_manager_cache(path: pathlib.Path) -> None:
|
| 329 |
+
font_manager.clear()
|
| 330 |
+
font_manager.build()
|
| 331 |
+
s = font_manager.dumps()
|
| 332 |
+
cache_dir = path.parent
|
| 333 |
+
make_cache_directory(cache_dir)
|
| 334 |
+
if not cache_dir.exists():
|
| 335 |
+
logger.warning(
|
| 336 |
+
f"Cannot create cache home directory: '{str(cache_dir)}', cache files will "
|
| 337 |
+
f"not be saved.\nSee also issue https://github.com/mozman/ezdxf/issues/923."
|
| 338 |
+
)
|
| 339 |
+
return
|
| 340 |
+
try:
|
| 341 |
+
path.write_text(s)
|
| 342 |
+
except IOError as e:
|
| 343 |
+
logger.warning(f"Error writing cache file: '{str(e)}'")
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
class FontRenderType(enum.Enum):
|
| 347 |
+
# render glyphs as filled paths: TTF, OTF
|
| 348 |
+
OUTLINE = enum.auto()
|
| 349 |
+
|
| 350 |
+
# render glyphs as line strokes: SHX, SHP
|
| 351 |
+
STROKE = enum.auto
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
class AbstractFont:
|
| 355 |
+
"""The `ezdxf` font abstraction for text measurement and text path rendering."""
|
| 356 |
+
|
| 357 |
+
font_render_type = FontRenderType.STROKE
|
| 358 |
+
name: str = "undefined"
|
| 359 |
+
|
| 360 |
+
def __init__(self, measurements: FontMeasurements):
|
| 361 |
+
self.measurements = measurements
|
| 362 |
+
|
| 363 |
+
@abc.abstractmethod
|
| 364 |
+
def text_width(self, text: str) -> float:
|
| 365 |
+
"""Returns the text width in drawing units for the given `text` string."""
|
| 366 |
+
pass
|
| 367 |
+
|
| 368 |
+
@abc.abstractmethod
|
| 369 |
+
def text_width_ex(
|
| 370 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 371 |
+
) -> float:
|
| 372 |
+
"""Returns the text width in drawing units, bypasses the stored `cap_height` and
|
| 373 |
+
`width_factor`.
|
| 374 |
+
"""
|
| 375 |
+
pass
|
| 376 |
+
|
| 377 |
+
@abc.abstractmethod
|
| 378 |
+
def space_width(self) -> float:
|
| 379 |
+
"""Returns the width of a "space" character a.k.a. word spacing."""
|
| 380 |
+
pass
|
| 381 |
+
|
| 382 |
+
@abc.abstractmethod
|
| 383 |
+
def text_path(self, text: str) -> GlyphPath:
|
| 384 |
+
"""Returns the 2D text path for the given text."""
|
| 385 |
+
...
|
| 386 |
+
|
| 387 |
+
@abc.abstractmethod
|
| 388 |
+
def text_path_ex(
|
| 389 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 390 |
+
) -> GlyphPath:
|
| 391 |
+
"""Returns the 2D text path for the given text, bypasses the stored `cap_height`
|
| 392 |
+
and `width_factor`."""
|
| 393 |
+
...
|
| 394 |
+
|
| 395 |
+
@abc.abstractmethod
|
| 396 |
+
def text_glyph_paths(
|
| 397 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 398 |
+
) -> list[GlyphPath]:
|
| 399 |
+
"""Returns a list of 2D glyph paths for the given text, bypasses the stored
|
| 400 |
+
`cap_height` and `width_factor`."""
|
| 401 |
+
...
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class MonospaceFont(AbstractFont):
|
| 405 |
+
"""Represents a monospaced font where each letter has the same cap- and descender
|
| 406 |
+
height and the same width. The given cap height and width factor are the default
|
| 407 |
+
values for measurements and rendering. The extended methods can override these
|
| 408 |
+
default values.
|
| 409 |
+
|
| 410 |
+
This font exists only for generic text measurement in tests and does not render any
|
| 411 |
+
glyphs!
|
| 412 |
+
|
| 413 |
+
"""
|
| 414 |
+
|
| 415 |
+
font_render_type = FontRenderType.STROKE
|
| 416 |
+
name = MONOSPACE
|
| 417 |
+
|
| 418 |
+
def __init__(
|
| 419 |
+
self,
|
| 420 |
+
cap_height: float,
|
| 421 |
+
width_factor: float = 1.0,
|
| 422 |
+
baseline: float = 0,
|
| 423 |
+
descender_factor: float = DESCENDER_FACTOR,
|
| 424 |
+
x_height_factor: float = X_HEIGHT_FACTOR,
|
| 425 |
+
):
|
| 426 |
+
super().__init__(
|
| 427 |
+
FontMeasurements(
|
| 428 |
+
baseline=baseline,
|
| 429 |
+
cap_height=cap_height,
|
| 430 |
+
x_height=cap_height * x_height_factor,
|
| 431 |
+
descender_height=cap_height * descender_factor,
|
| 432 |
+
)
|
| 433 |
+
)
|
| 434 |
+
self._width_factor: float = abs(width_factor)
|
| 435 |
+
self._space_width = self.measurements.cap_height * self._width_factor
|
| 436 |
+
|
| 437 |
+
def text_width(self, text: str) -> float:
|
| 438 |
+
"""Returns the text width in drawing units for the given `text`."""
|
| 439 |
+
return self.text_width_ex(
|
| 440 |
+
text, self.measurements.cap_height, self._width_factor
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
def text_width_ex(
|
| 444 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 445 |
+
) -> float:
|
| 446 |
+
"""Returns the text width in drawing units, bypasses the stored `cap_height` and
|
| 447 |
+
`width_factor`.
|
| 448 |
+
"""
|
| 449 |
+
return len(text) * cap_height * width_factor
|
| 450 |
+
|
| 451 |
+
def text_path(self, text: str) -> GlyphPath:
|
| 452 |
+
"""Returns the rectangle text width x cap height as :class:`NumpyPath2d` instance."""
|
| 453 |
+
return self.text_path_ex(text, self.measurements.cap_height, self._width_factor)
|
| 454 |
+
|
| 455 |
+
def text_path_ex(
|
| 456 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 457 |
+
) -> GlyphPath:
|
| 458 |
+
"""Returns the rectangle text width x cap height as :class:`NumpyPath2d`
|
| 459 |
+
instance, bypasses the stored `cap_height` and `width_factor`.
|
| 460 |
+
"""
|
| 461 |
+
from ezdxf.path import Path
|
| 462 |
+
|
| 463 |
+
text_width = self.text_width_ex(text, cap_height, width_factor)
|
| 464 |
+
p = Path((0, 0))
|
| 465 |
+
p.line_to((text_width, 0))
|
| 466 |
+
p.line_to((text_width, cap_height))
|
| 467 |
+
p.line_to((0, cap_height))
|
| 468 |
+
p.close()
|
| 469 |
+
return GlyphPath(p)
|
| 470 |
+
|
| 471 |
+
def text_glyph_paths(
|
| 472 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 473 |
+
) -> list[GlyphPath]:
|
| 474 |
+
"""Returns the same rectangle as the method :meth:`text_path_ex` in a list."""
|
| 475 |
+
return [self.text_path_ex(text, cap_height, width_factor)]
|
| 476 |
+
|
| 477 |
+
def space_width(self) -> float:
|
| 478 |
+
"""Returns the width of a "space" char."""
|
| 479 |
+
return self._space_width
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
class _CachedFont(AbstractFont, abc.ABC):
|
| 483 |
+
"""Abstract font with caching support."""
|
| 484 |
+
|
| 485 |
+
_glyph_caches: dict[str, Glyphs] = dict()
|
| 486 |
+
|
| 487 |
+
def __init__(self, font_name: str, cap_height: float, width_factor: float = 1.0):
|
| 488 |
+
self.name = font_name
|
| 489 |
+
cache = self.create_cache(font_name)
|
| 490 |
+
self.glyph_cache = cache
|
| 491 |
+
self.cap_height = float(cap_height)
|
| 492 |
+
self.width_factor = float(width_factor)
|
| 493 |
+
scale_factor: float = cache.get_scaling_factor(self.cap_height)
|
| 494 |
+
super().__init__(cache.font_measurements.scale(scale_factor))
|
| 495 |
+
self._space_width: float = (
|
| 496 |
+
self.glyph_cache.space_width * scale_factor * width_factor
|
| 497 |
+
)
|
| 498 |
+
|
| 499 |
+
@abc.abstractmethod
|
| 500 |
+
def create_cache(self, font_name: str) -> Glyphs:
|
| 501 |
+
...
|
| 502 |
+
|
| 503 |
+
def text_width(self, text: str) -> float:
|
| 504 |
+
"""Returns the text width in drawing units for the given `text` string."""
|
| 505 |
+
return self.text_width_ex(text, self.cap_height, self.width_factor)
|
| 506 |
+
|
| 507 |
+
def text_width_ex(
|
| 508 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 509 |
+
) -> float:
|
| 510 |
+
"""Returns the text width in drawing units, bypasses the stored `cap_height` and
|
| 511 |
+
`width_factor`.
|
| 512 |
+
"""
|
| 513 |
+
if not text.strip():
|
| 514 |
+
return 0
|
| 515 |
+
return self.glyph_cache.get_text_length(text, cap_height, width_factor)
|
| 516 |
+
|
| 517 |
+
def text_path(self, text: str) -> GlyphPath:
|
| 518 |
+
"""Returns the 2D text path for the given text."""
|
| 519 |
+
|
| 520 |
+
return self.text_path_ex(text, self.cap_height, self.width_factor)
|
| 521 |
+
|
| 522 |
+
def text_path_ex(
|
| 523 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 524 |
+
) -> GlyphPath:
|
| 525 |
+
"""Returns the 2D text path for the given text, bypasses the stored `cap_height`
|
| 526 |
+
and `width_factor`."""
|
| 527 |
+
return self.glyph_cache.get_text_path(text, cap_height, width_factor)
|
| 528 |
+
|
| 529 |
+
def text_glyph_paths(
|
| 530 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 531 |
+
) -> list[GlyphPath]:
|
| 532 |
+
"""Returns a list of 2D glyph paths for the given text, bypasses the stored
|
| 533 |
+
`cap_height` and `width_factor`."""
|
| 534 |
+
return self.glyph_cache.get_text_glyph_paths(text, cap_height, width_factor)
|
| 535 |
+
|
| 536 |
+
def space_width(self) -> float:
|
| 537 |
+
"""Returns the width of a "space" char."""
|
| 538 |
+
return self._space_width
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
class TrueTypeFont(_CachedFont):
|
| 542 |
+
"""Represents a TrueType font. Font measurement and glyph rendering is done by the
|
| 543 |
+
`fontTools` package. The given cap height and width factor are the default values
|
| 544 |
+
for measurements and glyph rendering. The extended methods can override these
|
| 545 |
+
default values.
|
| 546 |
+
"""
|
| 547 |
+
|
| 548 |
+
font_render_type = FontRenderType.OUTLINE
|
| 549 |
+
|
| 550 |
+
def create_cache(self, ttf: str) -> Glyphs:
|
| 551 |
+
from .ttfonts import TTFontRenderer
|
| 552 |
+
|
| 553 |
+
key = pathlib.Path(ttf).name.lower()
|
| 554 |
+
try:
|
| 555 |
+
return self._glyph_caches[key]
|
| 556 |
+
except KeyError:
|
| 557 |
+
pass
|
| 558 |
+
try:
|
| 559 |
+
tt_font = font_manager.get_ttf_font(ttf)
|
| 560 |
+
try: # see issue #990
|
| 561 |
+
cache = TTFontRenderer(tt_font)
|
| 562 |
+
except Exception:
|
| 563 |
+
raise UnsupportedFont
|
| 564 |
+
except UnsupportedFont:
|
| 565 |
+
fallback_font_name = font_manager.fallback_font_name()
|
| 566 |
+
logger.info(f"replacing unsupported font '{ttf}' by '{fallback_font_name}'")
|
| 567 |
+
cache = TTFontRenderer(font_manager.get_ttf_font(fallback_font_name))
|
| 568 |
+
self._glyph_caches[key] = cache
|
| 569 |
+
return cache
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
class _UnmanagedTrueTypeFont(_CachedFont):
|
| 573 |
+
font_render_type = FontRenderType.OUTLINE
|
| 574 |
+
|
| 575 |
+
def create_cache(self, ttf: str) -> Glyphs:
|
| 576 |
+
from .ttfonts import TTFontRenderer
|
| 577 |
+
from fontTools.ttLib import TTFont
|
| 578 |
+
|
| 579 |
+
key = ttf.lower()
|
| 580 |
+
try:
|
| 581 |
+
return self._glyph_caches[key]
|
| 582 |
+
except KeyError:
|
| 583 |
+
pass
|
| 584 |
+
cache = TTFontRenderer(TTFont(ttf, fontNumber=0))
|
| 585 |
+
self._glyph_caches[key] = cache
|
| 586 |
+
return cache
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def sideload_ttf(font_path: str | os.PathLike, cap_height) -> AbstractFont:
|
| 590 |
+
"""This function bypasses the FontManager and loads the TrueType font straight from
|
| 591 |
+
the file system, requires the absolute font file path e.g. "C:/Windows/Fonts/Arial.ttf".
|
| 592 |
+
|
| 593 |
+
.. warning::
|
| 594 |
+
|
| 595 |
+
Expert feature, use with care: no fallback font and no error handling.
|
| 596 |
+
|
| 597 |
+
"""
|
| 598 |
+
|
| 599 |
+
return _UnmanagedTrueTypeFont(str(font_path), cap_height)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class ShapeFileFont(_CachedFont):
|
| 603 |
+
"""Represents a shapefile font (.shx, .shp). Font measurement and glyph rendering is
|
| 604 |
+
done by the ezdxf.fonts.shapefile module. The given cap height and width factor are
|
| 605 |
+
the default values for measurements and glyph rendering. The extended methods can
|
| 606 |
+
override these default values.
|
| 607 |
+
|
| 608 |
+
"""
|
| 609 |
+
|
| 610 |
+
font_render_type = FontRenderType.STROKE
|
| 611 |
+
|
| 612 |
+
def create_cache(self, font_name: str) -> Glyphs:
|
| 613 |
+
key = font_name.lower()
|
| 614 |
+
try:
|
| 615 |
+
return self._glyph_caches[key]
|
| 616 |
+
except KeyError:
|
| 617 |
+
pass
|
| 618 |
+
glyph_cache = font_manager.get_shapefile_glyph_cache(font_name)
|
| 619 |
+
self._glyph_caches[key] = glyph_cache
|
| 620 |
+
return glyph_cache
|
| 621 |
+
|
| 622 |
+
|
| 623 |
+
class LibreCadFont(_CachedFont):
|
| 624 |
+
"""Represents a LibreCAD font (.shx, .shp). Font measurement and glyph rendering is
|
| 625 |
+
done by the ezdxf.fonts.lff module. The given cap height and width factor are the
|
| 626 |
+
default values for measurements and glyph rendering. The extended methods can
|
| 627 |
+
override these default values.
|
| 628 |
+
|
| 629 |
+
"""
|
| 630 |
+
|
| 631 |
+
font_render_type = FontRenderType.STROKE
|
| 632 |
+
|
| 633 |
+
def create_cache(self, font_name: str) -> Glyphs:
|
| 634 |
+
key = font_name.lower()
|
| 635 |
+
try:
|
| 636 |
+
return self._glyph_caches[key]
|
| 637 |
+
except KeyError:
|
| 638 |
+
pass
|
| 639 |
+
glyph_cache = font_manager.get_lff_glyph_cache(font_name)
|
| 640 |
+
self._glyph_caches[key] = glyph_cache
|
| 641 |
+
return glyph_cache
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def make_font(
|
| 645 |
+
font_name: str, cap_height: float, width_factor: float = 1.0
|
| 646 |
+
) -> AbstractFont:
|
| 647 |
+
r"""Returns a font abstraction based on class :class:`AbstractFont`.
|
| 648 |
+
|
| 649 |
+
Supported font types:
|
| 650 |
+
|
| 651 |
+
- .ttf, .ttc and .otf - TrueType fonts
|
| 652 |
+
- .shx, .shp - Autodesk® shapefile fonts
|
| 653 |
+
- .lff - LibreCAD font format
|
| 654 |
+
|
| 655 |
+
The special name "\*monospace" returns the fallback font :class:`MonospaceFont` for
|
| 656 |
+
testing and basic measurements.
|
| 657 |
+
|
| 658 |
+
.. note:: The font definition files are not included in `ezdxf`.
|
| 659 |
+
|
| 660 |
+
Args:
|
| 661 |
+
font_name: font file name as stored in the :class:`~ezdxf.entities.Textstyle`
|
| 662 |
+
entity e.g. "OpenSans-Regular.ttf"
|
| 663 |
+
cap_height: desired cap height in drawing units.
|
| 664 |
+
width_factor: horizontal text stretch factor
|
| 665 |
+
|
| 666 |
+
"""
|
| 667 |
+
if font_name == MONOSPACE:
|
| 668 |
+
return MonospaceFont(cap_height, width_factor)
|
| 669 |
+
ext = pathlib.Path(font_name).suffix.lower()
|
| 670 |
+
last_resort = MonospaceFont(cap_height, width_factor)
|
| 671 |
+
if ext in SUPPORTED_TTF_TYPES:
|
| 672 |
+
try:
|
| 673 |
+
return TrueTypeFont(font_name, cap_height, width_factor)
|
| 674 |
+
except FontNotFoundError as e:
|
| 675 |
+
logger.warning(f"no default font found: {str(e)}")
|
| 676 |
+
return last_resort
|
| 677 |
+
elif ext == ".shx" or ext == ".shp":
|
| 678 |
+
try:
|
| 679 |
+
return ShapeFileFont(font_name, cap_height, width_factor)
|
| 680 |
+
except FontNotFoundError:
|
| 681 |
+
pass
|
| 682 |
+
except UnsupportedFont:
|
| 683 |
+
# change name - the font exists but is not supported
|
| 684 |
+
font_name = font_manager.fallback_font_name()
|
| 685 |
+
elif ext == ".lff":
|
| 686 |
+
try:
|
| 687 |
+
return LibreCadFont(font_name, cap_height, width_factor)
|
| 688 |
+
except FontNotFoundError:
|
| 689 |
+
pass
|
| 690 |
+
elif ext == "": # e.g. "TXT"
|
| 691 |
+
font_face = font_manager.find_best_match(
|
| 692 |
+
family=font_name, style=".shx", italic=None
|
| 693 |
+
)
|
| 694 |
+
if font_face is not None:
|
| 695 |
+
return make_font(font_face.filename, cap_height, width_factor)
|
| 696 |
+
else:
|
| 697 |
+
logger.warning(f"unsupported font-name suffix: {font_name}")
|
| 698 |
+
font_name = font_manager.fallback_font_name()
|
| 699 |
+
|
| 700 |
+
# return default TrueType font
|
| 701 |
+
try:
|
| 702 |
+
return TrueTypeFont(font_name, cap_height, width_factor)
|
| 703 |
+
except FontNotFoundError as e:
|
| 704 |
+
logger.warning(f"no default font found: {str(e)}")
|
| 705 |
+
return last_resort
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
def get_entity_font_face(entity: DXFEntity, doc: Optional[Drawing] = None) -> FontFace:
|
| 709 |
+
"""Returns the :class:`FontFace` defined by the associated text style.
|
| 710 |
+
Returns the default font face if the `entity` does not have or support
|
| 711 |
+
the DXF attribute "style". Supports the extended font information stored in
|
| 712 |
+
:class:`~ezdxf.entities.Textstyle` table entries.
|
| 713 |
+
|
| 714 |
+
Pass a DXF document as argument `doc` to resolve text styles for virtual
|
| 715 |
+
entities which are not assigned to a DXF document. The argument `doc`
|
| 716 |
+
always overrides the DXF document to which the `entity` is assigned to.
|
| 717 |
+
|
| 718 |
+
"""
|
| 719 |
+
if entity.doc and doc is None:
|
| 720 |
+
doc = entity.doc
|
| 721 |
+
if doc is None:
|
| 722 |
+
return FontFace()
|
| 723 |
+
|
| 724 |
+
style_name = ""
|
| 725 |
+
# This works also for entities which do not support "style",
|
| 726 |
+
# where style_name = entity.dxf.get("style") would fail.
|
| 727 |
+
if entity.dxf.is_supported("style"):
|
| 728 |
+
style_name = entity.dxf.style
|
| 729 |
+
|
| 730 |
+
font_face = FontFace()
|
| 731 |
+
if style_name:
|
| 732 |
+
style = cast("Textstyle", doc.styles.get(style_name))
|
| 733 |
+
family, italic, bold = style.get_extended_font_data()
|
| 734 |
+
if family:
|
| 735 |
+
text_style = "Italic" if italic else "Regular"
|
| 736 |
+
text_weight = 700 if bold else 400
|
| 737 |
+
font_face = FontFace(family=family, style=text_style, weight=text_weight)
|
| 738 |
+
else:
|
| 739 |
+
ttf = style.dxf.font
|
| 740 |
+
if ttf:
|
| 741 |
+
font_face = get_font_face(ttf)
|
| 742 |
+
return font_face
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
load()
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/glyphs.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
from typing_extensions import TypeAlias
|
| 5 |
+
import abc
|
| 6 |
+
|
| 7 |
+
from ezdxf.npshapes import NumpyPath2d
|
| 8 |
+
from .font_measurements import FontMeasurements
|
| 9 |
+
|
| 10 |
+
GlyphPath: TypeAlias = NumpyPath2d
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class Glyphs(abc.ABC):
|
| 14 |
+
font_measurements: FontMeasurements # of the raw font
|
| 15 |
+
space_width: float # word spacing of the raw font
|
| 16 |
+
|
| 17 |
+
@abc.abstractmethod
|
| 18 |
+
def get_scaling_factor(self, cap_height: float) -> float:
|
| 19 |
+
...
|
| 20 |
+
|
| 21 |
+
@abc.abstractmethod
|
| 22 |
+
def get_text_length(
|
| 23 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 24 |
+
) -> float:
|
| 25 |
+
...
|
| 26 |
+
|
| 27 |
+
def get_text_path(
|
| 28 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 29 |
+
) -> GlyphPath:
|
| 30 |
+
glyph_paths = self.get_text_glyph_paths(text, cap_height, width_factor)
|
| 31 |
+
if len(glyph_paths) == 0:
|
| 32 |
+
return GlyphPath(None)
|
| 33 |
+
return NumpyPath2d.concatenate(glyph_paths)
|
| 34 |
+
|
| 35 |
+
@abc.abstractmethod
|
| 36 |
+
def get_text_glyph_paths(
|
| 37 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 38 |
+
) -> list[GlyphPath]:
|
| 39 |
+
...
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/lff.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
#
|
| 4 |
+
# Basic tools for the LibreCAD Font Format:
|
| 5 |
+
# https://github.com/Rallaz/LibreCAD/wiki/lff-definition
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
from typing import Sequence, Iterator, Iterable, Optional, no_type_check
|
| 8 |
+
from typing_extensions import TypeAlias
|
| 9 |
+
from ezdxf.math import Vec2, BoundingBox2d, Matrix44
|
| 10 |
+
from ezdxf import path
|
| 11 |
+
from .font_measurements import FontMeasurements
|
| 12 |
+
from .glyphs import GlyphPath, Glyphs
|
| 13 |
+
|
| 14 |
+
__all__ = ["loads", "LCFont", "Glyph", "GlyphCache"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def loads(s: str) -> LCFont:
|
| 18 |
+
lines = s.split("\n")
|
| 19 |
+
name, letter_spacing, word_spacing = parse_properties(lines)
|
| 20 |
+
lcf = LCFont(name, letter_spacing, word_spacing)
|
| 21 |
+
for glyph, parent_code in parse_glyphs(lines):
|
| 22 |
+
lcf.add(glyph, parent_code)
|
| 23 |
+
return lcf
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class LCFont:
|
| 27 |
+
"""Low level representation of LibreCAD fonts."""
|
| 28 |
+
def __init__(
|
| 29 |
+
self, name: str = "", letter_spacing: float = 0.0, word_spacing: float = 0.0
|
| 30 |
+
) -> None:
|
| 31 |
+
self.name: str = name
|
| 32 |
+
self.letter_spacing: float = letter_spacing
|
| 33 |
+
self.word_spacing: float = word_spacing
|
| 34 |
+
self._glyphs: dict[int, Glyph] = dict()
|
| 35 |
+
|
| 36 |
+
def __len__(self) -> int:
|
| 37 |
+
return len(self._glyphs)
|
| 38 |
+
|
| 39 |
+
def __getitem__(self, item: int) -> Glyph:
|
| 40 |
+
return self._glyphs[item]
|
| 41 |
+
|
| 42 |
+
def add(self, glyph: Glyph, parent_code: int = 0) -> None:
|
| 43 |
+
if parent_code:
|
| 44 |
+
try:
|
| 45 |
+
parent_glyph = self._glyphs[parent_code]
|
| 46 |
+
except KeyError:
|
| 47 |
+
return
|
| 48 |
+
glyph = parent_glyph.extend(glyph)
|
| 49 |
+
self._glyphs[glyph.code] = glyph
|
| 50 |
+
|
| 51 |
+
def get(self, code: int) -> Optional[Glyph]:
|
| 52 |
+
return self._glyphs.get(code, None)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
Polyline: TypeAlias = Sequence[Sequence[float]]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Glyph:
|
| 59 |
+
"""Low level representation of a LibreCAD glyph."""
|
| 60 |
+
__slots__ = ("code", "polylines")
|
| 61 |
+
|
| 62 |
+
def __init__(self, code: int, polylines: Sequence[Polyline]):
|
| 63 |
+
self.code: int = code
|
| 64 |
+
self.polylines: Sequence[Polyline] = tuple(polylines)
|
| 65 |
+
|
| 66 |
+
def extend(self, glyph: Glyph) -> Glyph:
|
| 67 |
+
polylines = list(self.polylines)
|
| 68 |
+
polylines.extend(glyph.polylines)
|
| 69 |
+
return Glyph(glyph.code, polylines)
|
| 70 |
+
|
| 71 |
+
def to_path(self) -> GlyphPath:
|
| 72 |
+
from ezdxf.math import OCS
|
| 73 |
+
|
| 74 |
+
final_path = path.Path()
|
| 75 |
+
ocs = OCS()
|
| 76 |
+
for polyline in self.polylines:
|
| 77 |
+
p = path.Path() # empty path is required
|
| 78 |
+
path.add_2d_polyline(
|
| 79 |
+
p, convert_bulge_values(polyline), close=False, elevation=0, ocs=ocs
|
| 80 |
+
)
|
| 81 |
+
final_path.extend_multi_path(p)
|
| 82 |
+
return GlyphPath(final_path)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def convert_bulge_values(polyline: Polyline) -> Iterator[Sequence[float]]:
|
| 86 |
+
# In DXF the bulge value is always stored at the start vertex of the arc.
|
| 87 |
+
last_index = len(polyline) - 1
|
| 88 |
+
for index, vertex in enumerate(polyline):
|
| 89 |
+
bulge = 0.0
|
| 90 |
+
if index < last_index:
|
| 91 |
+
next_vertex = polyline[index + 1]
|
| 92 |
+
try:
|
| 93 |
+
bulge = next_vertex[2]
|
| 94 |
+
except IndexError:
|
| 95 |
+
pass
|
| 96 |
+
yield vertex[0], vertex[1], bulge
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def parse_properties(lines: list[str]) -> tuple[str, float, float]:
|
| 100 |
+
font_name = ""
|
| 101 |
+
letter_spacing = 0.0
|
| 102 |
+
word_spacing = 0.0
|
| 103 |
+
for line in lines:
|
| 104 |
+
line = line.strip()
|
| 105 |
+
if not line.startswith("#"):
|
| 106 |
+
continue
|
| 107 |
+
try:
|
| 108 |
+
name, value = line.split(":")
|
| 109 |
+
except ValueError:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
name = name[1:].strip()
|
| 113 |
+
if name == "Name":
|
| 114 |
+
font_name = value.strip()
|
| 115 |
+
elif name == "LetterSpacing":
|
| 116 |
+
try:
|
| 117 |
+
letter_spacing = float(value)
|
| 118 |
+
except ValueError:
|
| 119 |
+
continue
|
| 120 |
+
elif name == "WordSpacing":
|
| 121 |
+
try:
|
| 122 |
+
word_spacing = float(value)
|
| 123 |
+
except ValueError:
|
| 124 |
+
continue
|
| 125 |
+
return font_name, letter_spacing, word_spacing
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def scan_glyphs(lines: Iterable[str]) -> Iterator[list[str]]:
|
| 129 |
+
glyph: list[str] = []
|
| 130 |
+
for line in lines:
|
| 131 |
+
if line.startswith("["):
|
| 132 |
+
if glyph:
|
| 133 |
+
yield glyph
|
| 134 |
+
glyph.clear()
|
| 135 |
+
if line:
|
| 136 |
+
glyph.append(line)
|
| 137 |
+
if glyph:
|
| 138 |
+
yield glyph
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def strip_clutter(lines: list[str]) -> Iterator[str]:
|
| 142 |
+
for line in lines:
|
| 143 |
+
line = line.strip()
|
| 144 |
+
if not line.startswith("#"):
|
| 145 |
+
yield line
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def scan_int_ex(s: str) -> int:
|
| 149 |
+
from string import hexdigits
|
| 150 |
+
|
| 151 |
+
if len(s) == 0:
|
| 152 |
+
return 0
|
| 153 |
+
try:
|
| 154 |
+
end = s.index("]")
|
| 155 |
+
except ValueError:
|
| 156 |
+
end = len(s)
|
| 157 |
+
s = s[1:end].lower()
|
| 158 |
+
s = "".join(c for c in s if c in hexdigits)
|
| 159 |
+
try:
|
| 160 |
+
return int(s, 16)
|
| 161 |
+
except ValueError:
|
| 162 |
+
return 0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def parse_glyphs(lines: list[str]) -> Iterator[tuple[Glyph, int]]:
|
| 166 |
+
code: int
|
| 167 |
+
polylines: list[Polyline] = []
|
| 168 |
+
for glyph in scan_glyphs(strip_clutter(lines)):
|
| 169 |
+
parent_code: int = 0
|
| 170 |
+
polylines.clear()
|
| 171 |
+
line = glyph.pop(0)
|
| 172 |
+
if line[0] != "[":
|
| 173 |
+
continue
|
| 174 |
+
try:
|
| 175 |
+
code = int(line[1 : line.index("]")], 16)
|
| 176 |
+
except ValueError:
|
| 177 |
+
code = scan_int_ex(line)
|
| 178 |
+
if code == 0:
|
| 179 |
+
continue
|
| 180 |
+
line = glyph[0]
|
| 181 |
+
if line.startswith("C"):
|
| 182 |
+
glyph.pop(0)
|
| 183 |
+
try:
|
| 184 |
+
parent_code = int(line[1:], 16)
|
| 185 |
+
except ValueError:
|
| 186 |
+
continue
|
| 187 |
+
polylines = list(parse_polylines(glyph))
|
| 188 |
+
yield Glyph(code, polylines), parent_code
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def parse_polylines(lines: Iterable[str]) -> Iterator[Polyline]:
|
| 192 |
+
polyline: list[Sequence[float]] = []
|
| 193 |
+
for line in lines:
|
| 194 |
+
polyline.clear()
|
| 195 |
+
for vertex in line.split(";"):
|
| 196 |
+
values = to_floats(vertex.split(","))
|
| 197 |
+
if len(values) > 1:
|
| 198 |
+
polyline.append(values[:3])
|
| 199 |
+
yield tuple(polyline)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def to_floats(values: Iterable[str]) -> Sequence[float]:
|
| 203 |
+
def strip(value: str) -> float:
|
| 204 |
+
if value.startswith("A"):
|
| 205 |
+
value = value[1:]
|
| 206 |
+
try:
|
| 207 |
+
return float(value)
|
| 208 |
+
except ValueError:
|
| 209 |
+
return 0.0
|
| 210 |
+
|
| 211 |
+
return tuple(strip(value) for value in values)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
class GlyphCache(Glyphs):
|
| 215 |
+
"""Text render engine for LibreCAD fonts with integrated glyph caching."""
|
| 216 |
+
|
| 217 |
+
def __init__(self, font: LCFont) -> None:
|
| 218 |
+
self.font: LCFont = font
|
| 219 |
+
self._glyph_cache: dict[int, GlyphPath] = dict()
|
| 220 |
+
self._advance_width_cache: dict[int, float] = dict()
|
| 221 |
+
self.space_width: float = self.font.word_spacing
|
| 222 |
+
self.empty_box: GlyphPath = self.get_empty_box()
|
| 223 |
+
self.font_measurements: FontMeasurements = self._get_font_measurements()
|
| 224 |
+
|
| 225 |
+
def get_scaling_factor(self, cap_height: float) -> float:
|
| 226 |
+
try:
|
| 227 |
+
return cap_height / self.font_measurements.cap_height
|
| 228 |
+
except ZeroDivisionError:
|
| 229 |
+
return 1.0
|
| 230 |
+
|
| 231 |
+
def get_empty_box(self) -> GlyphPath:
|
| 232 |
+
glyph_A = self.get_shape(65)
|
| 233 |
+
box = BoundingBox2d(glyph_A.control_vertices())
|
| 234 |
+
height = box.size.y
|
| 235 |
+
width = box.size.x
|
| 236 |
+
start = glyph_A.start
|
| 237 |
+
p = path.Path(start)
|
| 238 |
+
p.line_to(start + Vec2(width, 0))
|
| 239 |
+
p.line_to(start + Vec2(width, height))
|
| 240 |
+
p.line_to(start + Vec2(0, height))
|
| 241 |
+
p.close()
|
| 242 |
+
p.move_to(glyph_A.end)
|
| 243 |
+
return GlyphPath(p)
|
| 244 |
+
|
| 245 |
+
def _render_shape(self, shape_number) -> GlyphPath:
|
| 246 |
+
try:
|
| 247 |
+
glyph = self.font[shape_number]
|
| 248 |
+
except KeyError:
|
| 249 |
+
if shape_number > 32:
|
| 250 |
+
return self.empty_box
|
| 251 |
+
raise ValueError("space and non-printable characters are not glyphs")
|
| 252 |
+
return glyph.to_path()
|
| 253 |
+
|
| 254 |
+
def get_shape(self, shape_number: int) -> GlyphPath:
|
| 255 |
+
if shape_number <= 32:
|
| 256 |
+
raise ValueError("space and non-printable characters are not glyphs")
|
| 257 |
+
try:
|
| 258 |
+
return self._glyph_cache[shape_number].clone()
|
| 259 |
+
except KeyError:
|
| 260 |
+
pass
|
| 261 |
+
glyph = self._render_shape(shape_number)
|
| 262 |
+
self._glyph_cache[shape_number] = glyph
|
| 263 |
+
advance_width = 0.0
|
| 264 |
+
if len(glyph):
|
| 265 |
+
box = glyph.bbox()
|
| 266 |
+
assert box.extmax is not None
|
| 267 |
+
advance_width = box.extmax.x + self.font.letter_spacing
|
| 268 |
+
self._advance_width_cache[shape_number] = advance_width
|
| 269 |
+
return glyph.clone()
|
| 270 |
+
|
| 271 |
+
def get_advance_width(self, shape_number: int) -> float:
|
| 272 |
+
if shape_number < 32:
|
| 273 |
+
return 0.0
|
| 274 |
+
if shape_number == 32:
|
| 275 |
+
return self.space_width
|
| 276 |
+
try:
|
| 277 |
+
return self._advance_width_cache[shape_number]
|
| 278 |
+
except KeyError:
|
| 279 |
+
pass
|
| 280 |
+
_ = self.get_shape(shape_number)
|
| 281 |
+
return self._advance_width_cache[shape_number]
|
| 282 |
+
|
| 283 |
+
@no_type_check
|
| 284 |
+
def _get_font_measurements(self) -> FontMeasurements:
|
| 285 |
+
# ignore last move_to command, which places the pen at the start of the
|
| 286 |
+
# following glyph
|
| 287 |
+
bbox = BoundingBox2d(self.get_shape(ord("x")).control_vertices())
|
| 288 |
+
baseline = bbox.extmin.y
|
| 289 |
+
x_height = bbox.extmax.y - baseline
|
| 290 |
+
|
| 291 |
+
bbox = BoundingBox2d(self.get_shape(ord("A")).control_vertices())
|
| 292 |
+
cap_height = bbox.extmax.y - baseline
|
| 293 |
+
bbox = BoundingBox2d(self.get_shape(ord("p")).control_vertices())
|
| 294 |
+
descender_height = baseline - bbox.extmin.y
|
| 295 |
+
return FontMeasurements(
|
| 296 |
+
baseline=baseline,
|
| 297 |
+
cap_height=cap_height,
|
| 298 |
+
x_height=x_height,
|
| 299 |
+
descender_height=descender_height,
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
def get_text_length(
|
| 303 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 304 |
+
) -> float:
|
| 305 |
+
scaling_factor = self.get_scaling_factor(cap_height) * width_factor
|
| 306 |
+
return sum(self.get_advance_width(ord(c)) for c in text) * scaling_factor
|
| 307 |
+
|
| 308 |
+
def get_text_glyph_paths(
|
| 309 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 310 |
+
) -> list[GlyphPath]:
|
| 311 |
+
glyph_paths: list[GlyphPath] = []
|
| 312 |
+
sy = self.get_scaling_factor(cap_height)
|
| 313 |
+
sx = sy * width_factor
|
| 314 |
+
m = Matrix44.scale(sx, sy, 1)
|
| 315 |
+
current_location = 0.0
|
| 316 |
+
for c in text:
|
| 317 |
+
shape_number = ord(c)
|
| 318 |
+
if shape_number > 32:
|
| 319 |
+
glyph = self.get_shape(shape_number)
|
| 320 |
+
m[3, 0] = current_location
|
| 321 |
+
glyph.transform_inplace(m)
|
| 322 |
+
glyph_paths.append(glyph)
|
| 323 |
+
current_location += self.get_advance_width(shape_number) * sx
|
| 324 |
+
return glyph_paths
|
data/miniconda3/envs/catiagent/lib/python3.11/site-packages/ezdxf/fonts/shapefile.py
ADDED
|
@@ -0,0 +1,1064 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2022-2023, Manfred Moitzi
|
| 2 |
+
# License: MIT License
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
This module provides support for fonts stored as SHX and SHP files.
|
| 6 |
+
(SHP is not the GIS file format!)
|
| 7 |
+
|
| 8 |
+
The documentation about the SHP file format can be found at Autodesk:
|
| 9 |
+
https://help.autodesk.com/view/OARX/2018/ENU/?guid=GUID-DE941DB5-7044-433C-AA68-2A9AE98A5713
|
| 10 |
+
|
| 11 |
+
Using bytes for strings because no encoding is defined in shape-files.
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
from typing import (
|
| 16 |
+
Sequence,
|
| 17 |
+
Iterable,
|
| 18 |
+
Iterator,
|
| 19 |
+
Callable,
|
| 20 |
+
Optional,
|
| 21 |
+
Any,
|
| 22 |
+
Set,
|
| 23 |
+
no_type_check,
|
| 24 |
+
)
|
| 25 |
+
import dataclasses
|
| 26 |
+
import enum
|
| 27 |
+
import math
|
| 28 |
+
import pathlib
|
| 29 |
+
|
| 30 |
+
from ezdxf.math import (
|
| 31 |
+
UVec,
|
| 32 |
+
Vec2,
|
| 33 |
+
ConstructionEllipse,
|
| 34 |
+
bulge_to_arc,
|
| 35 |
+
BoundingBox2d,
|
| 36 |
+
Matrix44,
|
| 37 |
+
)
|
| 38 |
+
from ezdxf import path
|
| 39 |
+
from .font_measurements import FontMeasurements
|
| 40 |
+
from .glyphs import GlyphPath, Glyphs
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ShapeFileException(Exception):
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class UnsupportedShapeFile(ShapeFileException):
|
| 48 |
+
pass
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class UnsupportedShapeNumber(ShapeFileException):
|
| 52 |
+
pass
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class InvalidFontDefinition(ShapeFileException):
|
| 56 |
+
pass
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class InvalidFontParameters(ShapeFileException):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class InvalidShapeRecord(ShapeFileException):
|
| 64 |
+
pass
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class FileStructureError(ShapeFileException):
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class StackUnderflow(ShapeFileException):
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class FontEmbedding(enum.IntEnum):
|
| 76 |
+
ALLOWED = 0
|
| 77 |
+
DISALLOWED = 1
|
| 78 |
+
READONLY = 2
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class FontEncoding(enum.IntEnum):
|
| 82 |
+
UNICODE = 0
|
| 83 |
+
PACKED_MULTIBYTE_1 = 1
|
| 84 |
+
SHAPE_FILE = 2
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class FontMode(enum.IntEnum):
|
| 88 |
+
HORIZONTAL = 0
|
| 89 |
+
BIDIRECT = 2
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
NO_DATA: Sequence[int] = tuple()
|
| 93 |
+
DEBUG = False
|
| 94 |
+
DEBUG_CODES: Set[int] = set()
|
| 95 |
+
DEBUG_SHAPE_NUMBERS = set()
|
| 96 |
+
ORD_NULL = ord("0")
|
| 97 |
+
ORD_MINUS = ord("-")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# slots=True - Python 3.10+
|
| 101 |
+
@dataclasses.dataclass
|
| 102 |
+
class Symbol:
|
| 103 |
+
number: int
|
| 104 |
+
byte_count: int
|
| 105 |
+
name: bytes
|
| 106 |
+
data: Sequence[int] = NO_DATA
|
| 107 |
+
|
| 108 |
+
def export_str(self, as_num: int = 0) -> list[bytes]:
|
| 109 |
+
num = as_num if as_num else self.number
|
| 110 |
+
export = [f"*{num:05X},{self.byte_count},".encode() + self.name]
|
| 111 |
+
export.extend(format_shape_data_string(self.data))
|
| 112 |
+
return export
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def format_shape_data_string(data: Sequence[int]) -> list[bytes]:
|
| 116 |
+
export = []
|
| 117 |
+
s = b""
|
| 118 |
+
for num in data:
|
| 119 |
+
s2 = s + f"{num},".encode()
|
| 120 |
+
if len(s2) < 80:
|
| 121 |
+
s = s2
|
| 122 |
+
else:
|
| 123 |
+
export.append(s[:-1])
|
| 124 |
+
s = f",{num},".encode()
|
| 125 |
+
if s:
|
| 126 |
+
export.append(s[:-1])
|
| 127 |
+
return export
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class ShapeFile:
|
| 131 |
+
"""Low level representation of a SHX/SHP file."""
|
| 132 |
+
def __init__(
|
| 133 |
+
self,
|
| 134 |
+
name: bytes,
|
| 135 |
+
above: int,
|
| 136 |
+
below: int,
|
| 137 |
+
mode=FontMode.HORIZONTAL,
|
| 138 |
+
encoding=FontEncoding.UNICODE,
|
| 139 |
+
embed=FontEmbedding.ALLOWED,
|
| 140 |
+
):
|
| 141 |
+
self.shapes: dict[int, Symbol] = dict()
|
| 142 |
+
self.name = name
|
| 143 |
+
self.above = above
|
| 144 |
+
self.below = below
|
| 145 |
+
self.mode = mode
|
| 146 |
+
self.encoding = encoding
|
| 147 |
+
self.embed = embed
|
| 148 |
+
|
| 149 |
+
@property
|
| 150 |
+
def cap_height(self) -> float:
|
| 151 |
+
return float(self.above)
|
| 152 |
+
|
| 153 |
+
@property
|
| 154 |
+
def descender(self) -> float:
|
| 155 |
+
return float(self.below)
|
| 156 |
+
|
| 157 |
+
@property
|
| 158 |
+
def is_font(self) -> bool:
|
| 159 |
+
return self.encoding != FontEncoding.SHAPE_FILE
|
| 160 |
+
|
| 161 |
+
@property
|
| 162 |
+
def is_shape_file(self) -> bool:
|
| 163 |
+
return self.encoding == FontEncoding.SHAPE_FILE
|
| 164 |
+
|
| 165 |
+
def find(self, name: bytes) -> Optional[Symbol]:
|
| 166 |
+
for symbol in self.shapes.values():
|
| 167 |
+
if name == symbol.name:
|
| 168 |
+
return symbol
|
| 169 |
+
return None
|
| 170 |
+
|
| 171 |
+
def __len__(self):
|
| 172 |
+
return len(self.shapes)
|
| 173 |
+
|
| 174 |
+
def __getitem__(self, item):
|
| 175 |
+
return self.shapes[item]
|
| 176 |
+
|
| 177 |
+
@staticmethod
|
| 178 |
+
def from_ascii_records(records: Sequence[bytes]):
|
| 179 |
+
if len(records) == 2:
|
| 180 |
+
encoding = FontEncoding.UNICODE
|
| 181 |
+
above = 0
|
| 182 |
+
below = 0
|
| 183 |
+
embed = FontEmbedding.ALLOWED
|
| 184 |
+
mode = FontMode.HORIZONTAL
|
| 185 |
+
end = 0
|
| 186 |
+
header, params = records
|
| 187 |
+
try:
|
| 188 |
+
# ignore second value: defbytes
|
| 189 |
+
spec, _, name = header.split(b",", maxsplit=2)
|
| 190 |
+
except ValueError:
|
| 191 |
+
raise InvalidFontDefinition()
|
| 192 |
+
if spec == b"*UNIFONT":
|
| 193 |
+
try:
|
| 194 |
+
above, below, mode, encoding, embed, end = params.split(b",") # type: ignore
|
| 195 |
+
except ValueError:
|
| 196 |
+
raise InvalidFontParameters(params)
|
| 197 |
+
elif spec == b"*0":
|
| 198 |
+
try:
|
| 199 |
+
above, below, mode, *rest = params.split(b",") # type: ignore
|
| 200 |
+
end = rest[-1] # type: ignore
|
| 201 |
+
except ValueError:
|
| 202 |
+
raise InvalidFontParameters(params)
|
| 203 |
+
else: # it's a simple shape file
|
| 204 |
+
encoding = FontEncoding.SHAPE_FILE
|
| 205 |
+
assert int(end) == 0
|
| 206 |
+
|
| 207 |
+
return ShapeFile(
|
| 208 |
+
name.strip(),
|
| 209 |
+
int(above),
|
| 210 |
+
int(below),
|
| 211 |
+
FontMode(int(mode)),
|
| 212 |
+
FontEncoding(int(encoding)),
|
| 213 |
+
FontEmbedding(int(embed)),
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
def parse_ascii_records(self, records: Iterable[Sequence[bytes]]) -> None:
|
| 217 |
+
for record in records:
|
| 218 |
+
if len(record) < 2:
|
| 219 |
+
raise InvalidShapeRecord(record)
|
| 220 |
+
try:
|
| 221 |
+
number, byte_count, name = split_def_record(record[0])
|
| 222 |
+
except ValueError:
|
| 223 |
+
raise FileStructureError(record[0])
|
| 224 |
+
|
| 225 |
+
assert len(number) > 1
|
| 226 |
+
if number[1] == ORD_NULL: # hex if first char is "0" like "*0000A"
|
| 227 |
+
int_num = int(number[1:], 16)
|
| 228 |
+
else: # like "*130"
|
| 229 |
+
int_num = int(number[1:], 10)
|
| 230 |
+
|
| 231 |
+
symbol = Symbol(int_num, int(byte_count), name)
|
| 232 |
+
data = b"".join(record[1:])
|
| 233 |
+
symbol.data = tuple(parse_codes(split_record(data)))
|
| 234 |
+
if symbol.data[-1] == 0:
|
| 235 |
+
self.shapes[int_num] = symbol
|
| 236 |
+
else:
|
| 237 |
+
s = record[0].decode(errors="ignore")
|
| 238 |
+
raise FileStructureError(f"file structure error at symbol <{s}>")
|
| 239 |
+
|
| 240 |
+
def get_codes(self, number: int) -> Sequence[int]:
|
| 241 |
+
symbol = self.shapes.get(number)
|
| 242 |
+
if symbol is None:
|
| 243 |
+
raise UnsupportedShapeNumber(number)
|
| 244 |
+
return symbol.data
|
| 245 |
+
|
| 246 |
+
def render_shape(self, number: int, stacked=False) -> GlyphPath:
|
| 247 |
+
return render_shapes([number], self.get_codes, stacked=stacked)
|
| 248 |
+
|
| 249 |
+
def render_shapes(self, numbers: Sequence[int], stacked=False) -> GlyphPath:
|
| 250 |
+
return render_shapes(numbers, self.get_codes, stacked=stacked)
|
| 251 |
+
|
| 252 |
+
def render_text(self, text: str, stacked=False) -> GlyphPath:
|
| 253 |
+
numbers = [ord(char) for char in text]
|
| 254 |
+
return render_shapes(
|
| 255 |
+
numbers, self.get_codes, stacked=stacked, reset_to_baseline=True
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
def shape_string(self, shape_number: int, as_num: int = 0) -> list[bytes]:
|
| 259 |
+
return self.shapes[shape_number].export_str(as_num)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def readfile(filename: str) -> ShapeFile:
|
| 263 |
+
"""Load shape-file `filename`, the file type is detected by the file
|
| 264 |
+
name extension and should be ".shp" or ".shx" otherwise rises an
|
| 265 |
+
exception :class:`UnsupportedShapeFile`.
|
| 266 |
+
"""
|
| 267 |
+
data = pathlib.Path(filename).read_bytes()
|
| 268 |
+
filename = filename.lower()
|
| 269 |
+
if filename.endswith(".shp"):
|
| 270 |
+
return shp_load(data)
|
| 271 |
+
elif filename.endswith(".shx"):
|
| 272 |
+
return shx_load(data)
|
| 273 |
+
else:
|
| 274 |
+
raise UnsupportedShapeFile("unknown filetype")
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def split_def_record(record: bytes) -> Sequence[bytes]:
|
| 278 |
+
return tuple(s.strip() for s in record.split(b",", maxsplit=2))
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def split_record(record: bytes) -> Sequence[bytes]:
|
| 282 |
+
return tuple(s.strip() for s in record.split(b","))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def parse_codes(codes: Iterable[bytes]) -> Iterator[int]:
|
| 286 |
+
for code in codes:
|
| 287 |
+
code = code.strip(b"()")
|
| 288 |
+
if code == b"":
|
| 289 |
+
continue
|
| 290 |
+
if code[0] == ORD_NULL:
|
| 291 |
+
yield int(code, 16)
|
| 292 |
+
elif code[0] == ORD_MINUS and code[1] == ORD_NULL:
|
| 293 |
+
yield int(code, 16)
|
| 294 |
+
else:
|
| 295 |
+
yield int(code, 10)
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def shp_load(data: bytes) -> ShapeFile:
|
| 299 |
+
records = parse_string_records(merge_lines(filter_noise(data.split(b"\n"))))
|
| 300 |
+
if b"*UNIFONT" in records:
|
| 301 |
+
font_definition = records.pop(b"*UNIFONT")
|
| 302 |
+
elif b"*0" in records:
|
| 303 |
+
font_definition = records.pop(b"*0")
|
| 304 |
+
else:
|
| 305 |
+
# a common shape file without a name
|
| 306 |
+
# symbol numbers are decimal!!!
|
| 307 |
+
font_definition = (b"_,_,_", b"")
|
| 308 |
+
shp = ShapeFile.from_ascii_records(font_definition)
|
| 309 |
+
shp.parse_ascii_records(records.values())
|
| 310 |
+
return shp
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def shx_load(data: bytes) -> ShapeFile:
|
| 314 |
+
if data.startswith(b"AutoCAD-86 shapes 1.0"):
|
| 315 |
+
return load_shx_shape_file_1_0(data)
|
| 316 |
+
elif data.startswith(b"AutoCAD-86 shapes 1.1"):
|
| 317 |
+
return load_shx_shape_file_1_1(data)
|
| 318 |
+
elif data.startswith(b"AutoCAD-86 unifont 1.0"):
|
| 319 |
+
return load_shx_unifont_file_1_0(data)
|
| 320 |
+
elif data.startswith(b"AutoCAD-86 bigfont 1.0"):
|
| 321 |
+
raise UnsupportedShapeFile("BIGFONT shapes are not supported yet")
|
| 322 |
+
raise UnsupportedShapeFile("unknown shape file format")
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def load_shx_shape_file_1_0(data: bytes) -> ShapeFile:
|
| 326 |
+
above = 0
|
| 327 |
+
below = 0
|
| 328 |
+
mode = FontMode.HORIZONTAL
|
| 329 |
+
name = b""
|
| 330 |
+
shapes = parse_shx_shapes(data)
|
| 331 |
+
font_definition = shapes.get(0)
|
| 332 |
+
if font_definition:
|
| 333 |
+
shapes.pop(0)
|
| 334 |
+
shape_data = font_definition.data
|
| 335 |
+
above = shape_data[0]
|
| 336 |
+
below = shape_data[1]
|
| 337 |
+
mode = FontMode(shape_data[2])
|
| 338 |
+
|
| 339 |
+
shape_file = ShapeFile(name, above=above, below=below, mode=mode)
|
| 340 |
+
shape_file.shapes = shapes
|
| 341 |
+
return shape_file
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def load_shx_shape_file_1_1(data: bytes) -> ShapeFile:
|
| 345 |
+
# seems to be the same as v1.0:
|
| 346 |
+
return load_shx_shape_file_1_0(data)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class DataReader:
|
| 350 |
+
def __init__(self, data: bytes, index=0):
|
| 351 |
+
self.data = data
|
| 352 |
+
self.index = index
|
| 353 |
+
|
| 354 |
+
@property
|
| 355 |
+
def has_data(self) -> bool:
|
| 356 |
+
return self.index < len(self.data)
|
| 357 |
+
|
| 358 |
+
def skip(self, n: int) -> None:
|
| 359 |
+
self.index += n
|
| 360 |
+
|
| 361 |
+
def u8(self) -> int:
|
| 362 |
+
index = self.index
|
| 363 |
+
self.index += 1
|
| 364 |
+
return self.data[index]
|
| 365 |
+
|
| 366 |
+
def i8(self) -> int:
|
| 367 |
+
value = self.data[self.index]
|
| 368 |
+
self.index += 1
|
| 369 |
+
if value > 127:
|
| 370 |
+
return (value & 127) - 128 # ???
|
| 371 |
+
return value
|
| 372 |
+
|
| 373 |
+
def octant(self) -> int:
|
| 374 |
+
value = self.data[self.index]
|
| 375 |
+
self.index += 1
|
| 376 |
+
if value & 128:
|
| 377 |
+
return -(value & 127)
|
| 378 |
+
else:
|
| 379 |
+
return value
|
| 380 |
+
|
| 381 |
+
def read_str(self) -> bytes:
|
| 382 |
+
data = bytearray()
|
| 383 |
+
while True:
|
| 384 |
+
char = self.u8()
|
| 385 |
+
if char:
|
| 386 |
+
data.append(char)
|
| 387 |
+
else:
|
| 388 |
+
return data
|
| 389 |
+
|
| 390 |
+
def read_bytes(self, n: int) -> bytes:
|
| 391 |
+
index = self.index
|
| 392 |
+
self.index += n
|
| 393 |
+
return self.data[index : index + n]
|
| 394 |
+
|
| 395 |
+
def u16(self) -> int:
|
| 396 |
+
# little ending
|
| 397 |
+
index = self.index
|
| 398 |
+
self.index += 2
|
| 399 |
+
return self.data[index] + (self.data[index + 1] << 8)
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
# the old 'AutoCAD-86 shapes 1.0' format
|
| 403 |
+
SHX_SHAPES_START_INDEX = 0x17
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def parse_shx_shapes(data: bytes) -> dict[int, Symbol]:
|
| 407 |
+
"""SHX/SHP shape parser."""
|
| 408 |
+
shapes: dict[int, Symbol] = dict()
|
| 409 |
+
reader = DataReader(data, SHX_SHAPES_START_INDEX)
|
| 410 |
+
if reader.u8() != 0x1A:
|
| 411 |
+
raise FileStructureError("signature byte 0x1A not found")
|
| 412 |
+
first_number = reader.u16()
|
| 413 |
+
last_number = reader.u16()
|
| 414 |
+
shape_count = reader.u16()
|
| 415 |
+
index_table: list[tuple[int, int]] = []
|
| 416 |
+
for _ in range(shape_count):
|
| 417 |
+
shape_number = reader.u16()
|
| 418 |
+
data_size = reader.u16()
|
| 419 |
+
index_table.append((shape_number, data_size))
|
| 420 |
+
if index_table[0][0] != first_number:
|
| 421 |
+
raise FileStructureError("invalid first entry in index table")
|
| 422 |
+
if index_table[-1][0] != last_number:
|
| 423 |
+
raise FileStructureError("invalid last entry in index table")
|
| 424 |
+
for shape_number, length in index_table:
|
| 425 |
+
record = reader.read_bytes(length)
|
| 426 |
+
try:
|
| 427 |
+
name, shape_data = parse_shx_data_record(record)
|
| 428 |
+
except IndexError:
|
| 429 |
+
raise FileStructureError(
|
| 430 |
+
f"SHX parsing error shape *{shape_number:05X}: {str(record)}"
|
| 431 |
+
)
|
| 432 |
+
byte_count = length - len(name) - 1
|
| 433 |
+
shapes[shape_number] = Symbol(shape_number, byte_count, name, shape_data)
|
| 434 |
+
if reader.read_bytes(3) != b"EOF":
|
| 435 |
+
raise FileStructureError("EOF marker not found")
|
| 436 |
+
return shapes
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def parse_shx_data_record(data: bytes) -> tuple[bytes, Sequence[int]]:
|
| 440 |
+
"""Low level SHX/SHP shape record parser."""
|
| 441 |
+
reader = DataReader(data)
|
| 442 |
+
name = reader.read_str()
|
| 443 |
+
codes = parse_shape_codes(reader)
|
| 444 |
+
return name, codes
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
# the new 'AutoCAD-86 unifont 1.0' format
|
| 448 |
+
SHX_UNIFONT_START_INDEX = 0x18
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def load_shx_unifont_file_1_0(data: bytes) -> ShapeFile:
|
| 452 |
+
reader = DataReader(data, SHX_UNIFONT_START_INDEX)
|
| 453 |
+
name, above, below, mode, encoding, embed = parse_shx_unifont_definition(reader)
|
| 454 |
+
shape_file = ShapeFile(
|
| 455 |
+
name,
|
| 456 |
+
above=above,
|
| 457 |
+
below=below,
|
| 458 |
+
mode=mode,
|
| 459 |
+
encoding=encoding,
|
| 460 |
+
embed=embed,
|
| 461 |
+
)
|
| 462 |
+
try:
|
| 463 |
+
shape_file.shapes = parse_shx_unifont_shapes(reader)
|
| 464 |
+
except IndexError:
|
| 465 |
+
raise FileStructureError("pre-mature end of file")
|
| 466 |
+
return shape_file
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def parse_shx_unifont_definition(reader: DataReader) -> Sequence[Any]:
|
| 470 |
+
if reader.u8() != 0x1A:
|
| 471 |
+
raise FileStructureError("signature byte 0x1A not found")
|
| 472 |
+
reader.skip(6)
|
| 473 |
+
# u16 record count: in isocp.shx = 238 (0xEE 0x00)
|
| 474 |
+
# = 1 definition record + 237 character records
|
| 475 |
+
# u16 isocp.shx: 0 (0x00 0x00), always 0???
|
| 476 |
+
# u16 font definition record size; isocp.shx: 52 (0x34 0x00)
|
| 477 |
+
|
| 478 |
+
name = reader.read_str()
|
| 479 |
+
above = reader.u8()
|
| 480 |
+
below = reader.u8()
|
| 481 |
+
mode = FontMode(reader.u8())
|
| 482 |
+
encoding = FontEncoding(reader.u8())
|
| 483 |
+
embed = FontEmbedding(reader.u8())
|
| 484 |
+
reader.skip(1) # <00> byte - end of font definition
|
| 485 |
+
return name, above, below, mode, encoding, embed
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def parse_shx_unifont_shapes(reader: DataReader) -> dict[int, Symbol]:
|
| 489 |
+
shapes: dict[int, Symbol] = dict()
|
| 490 |
+
while reader.has_data:
|
| 491 |
+
shape_number = reader.u16()
|
| 492 |
+
byte_count = reader.u16()
|
| 493 |
+
name = reader.read_str()
|
| 494 |
+
byte_count = byte_count - len(name) - 1
|
| 495 |
+
data_record = reader.read_bytes(byte_count)
|
| 496 |
+
codes = parse_shape_codes(DataReader(data_record), unifont=True)
|
| 497 |
+
shapes[shape_number] = Symbol(shape_number, byte_count, name, codes)
|
| 498 |
+
return shapes
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
SINGLE_CODES = {1, 2, 5, 6, 14}
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def parse_shape_codes(reader: DataReader, unifont=False) -> Sequence[int]:
|
| 505 |
+
codes: list[int] = []
|
| 506 |
+
while True:
|
| 507 |
+
code = reader.u8()
|
| 508 |
+
codes.append(code)
|
| 509 |
+
if code == 0:
|
| 510 |
+
return tuple(codes)
|
| 511 |
+
elif code in SINGLE_CODES or code > 14:
|
| 512 |
+
continue
|
| 513 |
+
elif code == 3 or code == 4: # size control
|
| 514 |
+
codes.append(reader.u8())
|
| 515 |
+
elif code == 7: # sub shape
|
| 516 |
+
if unifont:
|
| 517 |
+
codes.append(reader.u16())
|
| 518 |
+
else:
|
| 519 |
+
codes.append(reader.u8())
|
| 520 |
+
elif code == 8: # displacement
|
| 521 |
+
codes.append(reader.i8())
|
| 522 |
+
codes.append(reader.i8())
|
| 523 |
+
elif code == 9: # multiple displacement
|
| 524 |
+
x, y = 1, 1
|
| 525 |
+
while x or y:
|
| 526 |
+
x = reader.i8()
|
| 527 |
+
y = reader.i8()
|
| 528 |
+
codes.append(x)
|
| 529 |
+
codes.append(y)
|
| 530 |
+
elif code == 10: # octant arc
|
| 531 |
+
codes.append(reader.u8()) # radius
|
| 532 |
+
codes.append(reader.octant()) # octant specs
|
| 533 |
+
elif code == 11: # fractional arc
|
| 534 |
+
codes.append(reader.u8()) # start offset
|
| 535 |
+
codes.append(reader.u8()) # end offset
|
| 536 |
+
codes.append(reader.u8()) # radius hi
|
| 537 |
+
codes.append(reader.u8()) # radius lo
|
| 538 |
+
codes.append(reader.octant()) # octant specs
|
| 539 |
+
elif code == 12: # bulge arcs
|
| 540 |
+
codes.append(reader.i8()) # x
|
| 541 |
+
codes.append(reader.i8()) # y
|
| 542 |
+
codes.append(reader.i8()) # bulge
|
| 543 |
+
elif code == 13: # multiple bulge arcs
|
| 544 |
+
x, y = 1, 1
|
| 545 |
+
while x or y:
|
| 546 |
+
x = reader.i8()
|
| 547 |
+
y = reader.i8()
|
| 548 |
+
codes.append(x)
|
| 549 |
+
codes.append(y)
|
| 550 |
+
if x or y:
|
| 551 |
+
codes.append(reader.i8())
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def filter_noise(lines: Iterable[bytes]) -> Iterator[bytes]:
|
| 555 |
+
for line in lines:
|
| 556 |
+
line.rstrip(b"\r\n")
|
| 557 |
+
line = line.strip()
|
| 558 |
+
if line:
|
| 559 |
+
line = line.split(b";")[0]
|
| 560 |
+
line = line.strip()
|
| 561 |
+
if line:
|
| 562 |
+
yield line
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
def merge_lines(lines: Iterable[bytes]) -> Iterator[bytes]:
|
| 566 |
+
current = b""
|
| 567 |
+
for next_line in lines:
|
| 568 |
+
if not current:
|
| 569 |
+
current = next_line
|
| 570 |
+
elif current.startswith(b"*"):
|
| 571 |
+
if next_line.startswith(b","): # wrapped specification line?
|
| 572 |
+
current += next_line
|
| 573 |
+
else:
|
| 574 |
+
yield current
|
| 575 |
+
current = next_line
|
| 576 |
+
elif current.endswith(b","):
|
| 577 |
+
current += next_line
|
| 578 |
+
elif next_line.startswith(b","):
|
| 579 |
+
current += next_line
|
| 580 |
+
else:
|
| 581 |
+
yield current
|
| 582 |
+
current = next_line
|
| 583 |
+
if current:
|
| 584 |
+
yield current
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
def parse_string_records(
|
| 588 |
+
lines: Iterable[bytes],
|
| 589 |
+
) -> dict[bytes, Sequence[bytes]]:
|
| 590 |
+
records: dict[bytes, Sequence[bytes]] = dict()
|
| 591 |
+
name = None
|
| 592 |
+
record = []
|
| 593 |
+
for line in lines:
|
| 594 |
+
if line.startswith(b"*BIGFONT"):
|
| 595 |
+
raise UnsupportedShapeFile("BIGFONT shape files are not supported yet")
|
| 596 |
+
if line.startswith(b"*"):
|
| 597 |
+
if name is not None:
|
| 598 |
+
records[name] = tuple(record)
|
| 599 |
+
name = line.split(b",")[0].strip()
|
| 600 |
+
record = [line]
|
| 601 |
+
else:
|
| 602 |
+
record.append(line)
|
| 603 |
+
|
| 604 |
+
if name is not None:
|
| 605 |
+
records[name] = tuple(record)
|
| 606 |
+
return records
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def render_shapes(
|
| 610 |
+
shape_numbers: Sequence[int],
|
| 611 |
+
get_codes: Callable[[int], Sequence[int]],
|
| 612 |
+
stacked: bool,
|
| 613 |
+
start: UVec = (0, 0),
|
| 614 |
+
reset_to_baseline=False,
|
| 615 |
+
) -> GlyphPath:
|
| 616 |
+
"""Renders multiple shapes into a single glyph path."""
|
| 617 |
+
ctx = ShapeRenderer(
|
| 618 |
+
path.Path(start),
|
| 619 |
+
pen_down=True,
|
| 620 |
+
stacked=stacked,
|
| 621 |
+
get_codes=get_codes,
|
| 622 |
+
)
|
| 623 |
+
for shape_number in shape_numbers:
|
| 624 |
+
try:
|
| 625 |
+
ctx.render(shape_number, reset_to_baseline=reset_to_baseline)
|
| 626 |
+
except UnsupportedShapeNumber:
|
| 627 |
+
pass
|
| 628 |
+
except StackUnderflow:
|
| 629 |
+
raise StackUnderflow(
|
| 630 |
+
f"stack underflow while rendering shape number {shape_number}"
|
| 631 |
+
)
|
| 632 |
+
# move cursor to the start of the next char???
|
| 633 |
+
return GlyphPath(ctx.p)
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
|
| 637 |
+
VEC_X = [1, 1, 1, 0.5, 0, -0.5, -1, -1, -1, -1, -1, -0.5, 0, 0.5, 1, 1]
|
| 638 |
+
# 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
|
| 639 |
+
VEC_Y = [0, 0.5, 1, 1, 1, 1, 1, 0.5, 0, -0.5, -1, -1, -1, -1, -1, -0.5]
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
class ShapeRenderer:
|
| 643 |
+
"""Low level glyph renderer for SHX/SHP fonts."""
|
| 644 |
+
def __init__(
|
| 645 |
+
self,
|
| 646 |
+
p: path.Path,
|
| 647 |
+
get_codes: Callable[[int], Sequence[int]],
|
| 648 |
+
*,
|
| 649 |
+
vector_length: float = 1.0,
|
| 650 |
+
pen_down: bool = True,
|
| 651 |
+
stacked: bool = False,
|
| 652 |
+
):
|
| 653 |
+
self.p = p
|
| 654 |
+
self.vector_length = float(vector_length) # initial vector length
|
| 655 |
+
self.pen_down = pen_down
|
| 656 |
+
self.stacked = stacked # vertical stacked text
|
| 657 |
+
self._location_stack: list[Vec2] = []
|
| 658 |
+
self._get_codes = get_codes
|
| 659 |
+
self._baseline_y = self.p.start.y
|
| 660 |
+
|
| 661 |
+
@property
|
| 662 |
+
def current_location(self) -> Vec2:
|
| 663 |
+
return Vec2(self.p.end)
|
| 664 |
+
|
| 665 |
+
def push(self) -> None:
|
| 666 |
+
self._location_stack.append(self.current_location)
|
| 667 |
+
|
| 668 |
+
def pop(self) -> None:
|
| 669 |
+
self.p.move_to(self._location_stack.pop())
|
| 670 |
+
|
| 671 |
+
def render(
|
| 672 |
+
self,
|
| 673 |
+
shape_number: int,
|
| 674 |
+
reset_to_baseline=False,
|
| 675 |
+
) -> None:
|
| 676 |
+
self.pen_down = True
|
| 677 |
+
codes = self._get_codes(shape_number)
|
| 678 |
+
index = 0
|
| 679 |
+
skip_next = False
|
| 680 |
+
while index < len(codes):
|
| 681 |
+
code = codes[index]
|
| 682 |
+
if DEBUG and (code in DEBUG_CODES) and shape_number:
|
| 683 |
+
DEBUG_SHAPE_NUMBERS.add(shape_number)
|
| 684 |
+
index += 1
|
| 685 |
+
if code > 15 and not skip_next:
|
| 686 |
+
self.draw_vector(code)
|
| 687 |
+
elif code == 0:
|
| 688 |
+
break
|
| 689 |
+
elif code == 1 and not skip_next: # pen down
|
| 690 |
+
self.pen_down = True
|
| 691 |
+
elif code == 2 and not skip_next: # pen up
|
| 692 |
+
self.pen_down = False
|
| 693 |
+
elif code == 3 or code == 4: # scale size
|
| 694 |
+
factor = codes[index]
|
| 695 |
+
index += 1
|
| 696 |
+
if not skip_next:
|
| 697 |
+
if code == 3:
|
| 698 |
+
self.vector_length /= factor
|
| 699 |
+
elif code == 4:
|
| 700 |
+
self.vector_length *= factor
|
| 701 |
+
continue
|
| 702 |
+
elif code == 5 and not skip_next: # push location state
|
| 703 |
+
self.push()
|
| 704 |
+
elif code == 6 and not skip_next: # pop location state
|
| 705 |
+
try:
|
| 706 |
+
self.pop()
|
| 707 |
+
except IndexError:
|
| 708 |
+
raise StackUnderflow()
|
| 709 |
+
elif code == 7: # sub-shape:
|
| 710 |
+
sub_shape_number = codes[index]
|
| 711 |
+
index += 1
|
| 712 |
+
if not skip_next:
|
| 713 |
+
# Use current state of pen and location!
|
| 714 |
+
self.render(sub_shape_number)
|
| 715 |
+
# resume with current state of pen and location!
|
| 716 |
+
elif code == 8: # displacement vector
|
| 717 |
+
x = codes[index]
|
| 718 |
+
y = codes[index + 1]
|
| 719 |
+
index += 2
|
| 720 |
+
if not skip_next:
|
| 721 |
+
self.draw_displacement(x, y)
|
| 722 |
+
elif code == 9: # multiple displacements vectors
|
| 723 |
+
while True:
|
| 724 |
+
x = codes[index]
|
| 725 |
+
y = codes[index + 1]
|
| 726 |
+
index += 2
|
| 727 |
+
if x == 0 and y == 0:
|
| 728 |
+
break
|
| 729 |
+
if not skip_next:
|
| 730 |
+
self.draw_displacement(x, y)
|
| 731 |
+
elif code == 10: # 10 octant arc
|
| 732 |
+
radius = codes[index]
|
| 733 |
+
start_octant, octant_span, ccw = decode_octant_specs(codes[index + 1])
|
| 734 |
+
if octant_span == 0: # full circle
|
| 735 |
+
octant_span = 8
|
| 736 |
+
index += 2
|
| 737 |
+
if not skip_next:
|
| 738 |
+
self.draw_arc_span(
|
| 739 |
+
radius * self.vector_length,
|
| 740 |
+
math.radians(start_octant * 45),
|
| 741 |
+
math.radians(octant_span * 45),
|
| 742 |
+
ccw,
|
| 743 |
+
)
|
| 744 |
+
elif code == 11: # fractional arc
|
| 745 |
+
# TODO: this still seems not 100% correct, see vertical placing
|
| 746 |
+
# of characters "9" and "&" for font isocp.shx.
|
| 747 |
+
# This is solved by placing the end point on the baseline after
|
| 748 |
+
# each character rendering, but only for text rendering.
|
| 749 |
+
# The remaining problems can possibly be due to a loss of
|
| 750 |
+
# precision when converting floats to ints.
|
| 751 |
+
start_offset = codes[index]
|
| 752 |
+
end_offset = codes[index + 1]
|
| 753 |
+
radius = (codes[index + 2] << 8) + codes[index + 3]
|
| 754 |
+
start_octant, octant_span, ccw = decode_octant_specs(codes[index + 4])
|
| 755 |
+
index += 5
|
| 756 |
+
if end_offset == 0:
|
| 757 |
+
end_offset = 256
|
| 758 |
+
binary_deg = 45.0 / 256.0
|
| 759 |
+
start_offset_angle = start_offset * binary_deg
|
| 760 |
+
end_offset_angle = end_offset * binary_deg
|
| 761 |
+
if ccw:
|
| 762 |
+
end_octant = start_octant + octant_span - 1
|
| 763 |
+
start_angle = start_octant * 45.0 + start_offset_angle
|
| 764 |
+
end_angle = end_octant * 45.0 + end_offset_angle
|
| 765 |
+
else:
|
| 766 |
+
end_octant = start_octant - octant_span + 1
|
| 767 |
+
start_angle = start_octant * 45.0 - start_offset_angle
|
| 768 |
+
end_angle = end_octant * 45.0 - end_offset_angle
|
| 769 |
+
|
| 770 |
+
if not skip_next:
|
| 771 |
+
self.draw_arc_start_to_end(
|
| 772 |
+
radius * self.vector_length,
|
| 773 |
+
math.radians(start_angle),
|
| 774 |
+
math.radians(end_angle),
|
| 775 |
+
ccw,
|
| 776 |
+
)
|
| 777 |
+
elif code == 12: # bulge arc
|
| 778 |
+
x = codes[index]
|
| 779 |
+
y = codes[index + 1]
|
| 780 |
+
bulge = codes[index + 2]
|
| 781 |
+
index += 3
|
| 782 |
+
if not skip_next:
|
| 783 |
+
self.draw_bulge(x, y, bulge)
|
| 784 |
+
elif code == 13: # multiple bulge arcs
|
| 785 |
+
while True:
|
| 786 |
+
x = codes[index]
|
| 787 |
+
y = codes[index + 1]
|
| 788 |
+
if x == 0 and y == 0:
|
| 789 |
+
index += 2
|
| 790 |
+
break
|
| 791 |
+
bulge = codes[index + 2]
|
| 792 |
+
index += 3
|
| 793 |
+
if not skip_next:
|
| 794 |
+
self.draw_bulge(x, y, bulge)
|
| 795 |
+
elif code == 14: # flag vertical text
|
| 796 |
+
if not self.stacked:
|
| 797 |
+
skip_next = True
|
| 798 |
+
continue
|
| 799 |
+
skip_next = False
|
| 800 |
+
|
| 801 |
+
if reset_to_baseline:
|
| 802 |
+
# HACK: because of invalid fractional arc rendering!
|
| 803 |
+
if not math.isclose(self.p.end.y, self._baseline_y):
|
| 804 |
+
self.p.move_to((self.p.end.x, self._baseline_y))
|
| 805 |
+
|
| 806 |
+
def draw_vector(self, code: int) -> None:
|
| 807 |
+
angle: int = code & 0xF
|
| 808 |
+
length: int = (code >> 4) & 0xF
|
| 809 |
+
self.draw_displacement(VEC_X[angle] * length, VEC_Y[angle] * length)
|
| 810 |
+
|
| 811 |
+
def draw_displacement(self, x: float, y: float):
|
| 812 |
+
scale = self.vector_length
|
| 813 |
+
target = self.current_location + Vec2(x * scale, y * scale)
|
| 814 |
+
if self.pen_down:
|
| 815 |
+
self.p.line_to(target)
|
| 816 |
+
else:
|
| 817 |
+
self.p.move_to(target)
|
| 818 |
+
|
| 819 |
+
def draw_arc_span(
|
| 820 |
+
self, radius: float, start_angle: float, span_angle: float, ccw: bool
|
| 821 |
+
):
|
| 822 |
+
# IMPORTANT: radius has to be scaled by self.vector_length!
|
| 823 |
+
end_angle = start_angle + (span_angle if ccw else -span_angle)
|
| 824 |
+
self.draw_arc_start_to_end(radius, start_angle, end_angle, ccw)
|
| 825 |
+
|
| 826 |
+
def draw_arc_start_to_end(
|
| 827 |
+
self, radius: float, start_angle: float, end_angle: float, ccw: bool
|
| 828 |
+
):
|
| 829 |
+
# IMPORTANT: radius has to be scaled by self.vector_length!
|
| 830 |
+
assert radius > 0.0
|
| 831 |
+
arc = ConstructionEllipse(
|
| 832 |
+
major_axis=(radius, 0),
|
| 833 |
+
start_param=start_angle,
|
| 834 |
+
end_param=end_angle,
|
| 835 |
+
ccw=ccw,
|
| 836 |
+
)
|
| 837 |
+
# arc goes start -> end if ccw otherwise end -> start
|
| 838 |
+
# move arc start-point to the end-point of current path
|
| 839 |
+
arc.center += self.current_location - Vec2(
|
| 840 |
+
arc.start_point if ccw else arc.end_point
|
| 841 |
+
)
|
| 842 |
+
if self.pen_down:
|
| 843 |
+
path.add_ellipse(self.p, arc, reset=False)
|
| 844 |
+
else:
|
| 845 |
+
self.p.move_to(arc.end_point if ccw else arc.start_point)
|
| 846 |
+
|
| 847 |
+
def draw_arc(
|
| 848 |
+
self,
|
| 849 |
+
center: Vec2,
|
| 850 |
+
radius: float,
|
| 851 |
+
start_param: float,
|
| 852 |
+
end_param: float,
|
| 853 |
+
ccw: bool,
|
| 854 |
+
):
|
| 855 |
+
# IMPORTANT: radius has to be scaled by self.vector_length!
|
| 856 |
+
arc = ConstructionEllipse(
|
| 857 |
+
center=center,
|
| 858 |
+
major_axis=(radius, 0),
|
| 859 |
+
start_param=start_param,
|
| 860 |
+
end_param=end_param,
|
| 861 |
+
ccw=ccw,
|
| 862 |
+
)
|
| 863 |
+
if self.pen_down:
|
| 864 |
+
path.add_ellipse(self.p, arc, reset=False)
|
| 865 |
+
else:
|
| 866 |
+
self.p.move_to(arc.end_point if ccw else arc.start_point)
|
| 867 |
+
|
| 868 |
+
def draw_bulge(self, x: float, y: float, bulge: float):
|
| 869 |
+
if self.pen_down and bulge:
|
| 870 |
+
start_point = self.current_location
|
| 871 |
+
scale = self.vector_length
|
| 872 |
+
ccw = bulge > 0
|
| 873 |
+
end_point = start_point + Vec2(x * scale, y * scale)
|
| 874 |
+
bulge = abs(bulge) / 127.0
|
| 875 |
+
if ccw: # counter-clockwise
|
| 876 |
+
center, start_angle, end_angle, radius = bulge_to_arc(
|
| 877 |
+
start_point, end_point, bulge
|
| 878 |
+
)
|
| 879 |
+
else: # clockwise
|
| 880 |
+
center, start_angle, end_angle, radius = bulge_to_arc(
|
| 881 |
+
end_point, start_point, bulge
|
| 882 |
+
)
|
| 883 |
+
self.draw_arc(center, radius, start_angle, end_angle, ccw=True)
|
| 884 |
+
else:
|
| 885 |
+
self.draw_displacement(x, y)
|
| 886 |
+
|
| 887 |
+
|
| 888 |
+
def decode_octant_specs(specs: int) -> tuple[int, int, bool]:
|
| 889 |
+
ccw = True
|
| 890 |
+
if specs < 0:
|
| 891 |
+
ccw = False
|
| 892 |
+
specs = -specs
|
| 893 |
+
start_octant = (specs >> 4) & 0xF
|
| 894 |
+
octant_span = specs & 0xF
|
| 895 |
+
return start_octant, octant_span, ccw
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
def find_shape_number(filename: str, name: bytes) -> int:
|
| 899 |
+
"""Returns the shape number for shape `name` from the shape-file, returns -1 if not
|
| 900 |
+
found.
|
| 901 |
+
|
| 902 |
+
The filename can be an absolute path or the shape-file will be searched in the
|
| 903 |
+
current directory and all directories stored in :attr:`ezdxf.options.support_dirs`.
|
| 904 |
+
Supports shape files of type ".shx" and ".shp".
|
| 905 |
+
"""
|
| 906 |
+
from ezdxf.filemanagement import find_support_file
|
| 907 |
+
from ezdxf import options
|
| 908 |
+
|
| 909 |
+
shape_file_name = find_support_file(filename, options.support_dirs)
|
| 910 |
+
index = -1
|
| 911 |
+
try:
|
| 912 |
+
shapes = readfile(shape_file_name)
|
| 913 |
+
except (IOError, ShapeFileException):
|
| 914 |
+
return index
|
| 915 |
+
shx_symbol = shapes.find(name)
|
| 916 |
+
if shx_symbol is not None:
|
| 917 |
+
return shx_symbol.number
|
| 918 |
+
return index
|
| 919 |
+
|
| 920 |
+
|
| 921 |
+
class GlyphCache(Glyphs):
|
| 922 |
+
def __init__(self, font: ShapeFile) -> None:
|
| 923 |
+
"""Text render engine for SHX/SHP fonts with integrated glyph caching."""
|
| 924 |
+
self.font: ShapeFile = font
|
| 925 |
+
self._glyph_cache: dict[int, GlyphPath] = dict()
|
| 926 |
+
self._advance_width_cache: dict[int, float] = dict()
|
| 927 |
+
self.space_width: float = self.detect_space_width(default_width=font.cap_height)
|
| 928 |
+
self.empty_box: GlyphPath = self.get_empty_box()
|
| 929 |
+
self.font_measurements: FontMeasurements = self._get_font_measurements()
|
| 930 |
+
|
| 931 |
+
def get_scaling_factor(self, cap_height: float) -> float:
|
| 932 |
+
try:
|
| 933 |
+
return cap_height / self.font_measurements.cap_height
|
| 934 |
+
except ZeroDivisionError:
|
| 935 |
+
return 1.0
|
| 936 |
+
|
| 937 |
+
def detect_space_width(self, default_width: float) -> float:
|
| 938 |
+
# space (32) or "A" (65) may not present!
|
| 939 |
+
if 32 in self.font.shapes:
|
| 940 |
+
return self.get_shape(32).end.x # width of space
|
| 941 |
+
if 65 in self.font.shapes:
|
| 942 |
+
return self.get_shape(65).end.x # width of "A"
|
| 943 |
+
return default_width
|
| 944 |
+
|
| 945 |
+
def get_empty_box(self, char: int = 65) -> GlyphPath:
|
| 946 |
+
"""Returns the empty box (tofu) representation based on the size of the given
|
| 947 |
+
character index.
|
| 948 |
+
|
| 949 |
+
The given index may not exist and a default box based on cap-height and space
|
| 950 |
+
width will be created.
|
| 951 |
+
"""
|
| 952 |
+
# default box parameters
|
| 953 |
+
font = self.font
|
| 954 |
+
height = font.cap_height
|
| 955 |
+
width = self.space_width
|
| 956 |
+
start = Vec2(0, 0)
|
| 957 |
+
end = Vec2(width, 0)
|
| 958 |
+
|
| 959 |
+
if char in font.shapes:
|
| 960 |
+
# box parameters based on the glyph size
|
| 961 |
+
glyph = self.get_shape(char)
|
| 962 |
+
box = BoundingBox2d(glyph.control_vertices())
|
| 963 |
+
height = box.size.y
|
| 964 |
+
width = box.size.x
|
| 965 |
+
start = glyph.start
|
| 966 |
+
end = glyph.end
|
| 967 |
+
|
| 968 |
+
p = path.Path(start)
|
| 969 |
+
p.line_to(start + Vec2(width, 0))
|
| 970 |
+
p.line_to(start + Vec2(width, height))
|
| 971 |
+
p.line_to(start + Vec2(0, height))
|
| 972 |
+
p.close()
|
| 973 |
+
p.move_to(end)
|
| 974 |
+
return GlyphPath(p)
|
| 975 |
+
|
| 976 |
+
def _render_shape(self, shape_number) -> GlyphPath:
|
| 977 |
+
ctx = ShapeRenderer(
|
| 978 |
+
path.Path(),
|
| 979 |
+
pen_down=True,
|
| 980 |
+
stacked=False,
|
| 981 |
+
get_codes=self.font.get_codes,
|
| 982 |
+
)
|
| 983 |
+
try:
|
| 984 |
+
ctx.render(shape_number, reset_to_baseline=False)
|
| 985 |
+
except StackUnderflow:
|
| 986 |
+
pass
|
| 987 |
+
return GlyphPath(ctx.p)
|
| 988 |
+
|
| 989 |
+
def get_shape(self, shape_number: int) -> GlyphPath:
|
| 990 |
+
try:
|
| 991 |
+
return self._glyph_cache[shape_number].clone()
|
| 992 |
+
except KeyError:
|
| 993 |
+
pass
|
| 994 |
+
try:
|
| 995 |
+
glyph = self._render_shape(shape_number)
|
| 996 |
+
except UnsupportedShapeNumber:
|
| 997 |
+
if shape_number < 32:
|
| 998 |
+
glyph = GlyphPath(None)
|
| 999 |
+
else:
|
| 1000 |
+
glyph = self.empty_box
|
| 1001 |
+
self._glyph_cache[shape_number] = glyph
|
| 1002 |
+
try:
|
| 1003 |
+
width = glyph.end.x
|
| 1004 |
+
except IndexError:
|
| 1005 |
+
width = self.space_width
|
| 1006 |
+
self._advance_width_cache[shape_number] = width
|
| 1007 |
+
return glyph.clone()
|
| 1008 |
+
|
| 1009 |
+
def get_advance_width(self, shape_number: int) -> float:
|
| 1010 |
+
if shape_number == 32:
|
| 1011 |
+
return self.space_width
|
| 1012 |
+
try:
|
| 1013 |
+
return self._advance_width_cache[shape_number]
|
| 1014 |
+
except KeyError:
|
| 1015 |
+
pass
|
| 1016 |
+
return self.get_shape(shape_number).end.x
|
| 1017 |
+
|
| 1018 |
+
@no_type_check
|
| 1019 |
+
def _get_font_measurements(self) -> FontMeasurements:
|
| 1020 |
+
# ignore last move_to command, which places the pen at the start of the
|
| 1021 |
+
# following glyph
|
| 1022 |
+
bbox = BoundingBox2d(self.get_shape(ord("x")).control_vertices()[:-1])
|
| 1023 |
+
baseline = bbox.extmin.y
|
| 1024 |
+
x_height = bbox.extmax.y - baseline
|
| 1025 |
+
|
| 1026 |
+
cap_height = self.font.above
|
| 1027 |
+
if cap_height == 0:
|
| 1028 |
+
bbox = BoundingBox2d(self.get_shape(ord("A")).control_vertices()[:-1])
|
| 1029 |
+
cap_height = bbox.extmax.y - baseline
|
| 1030 |
+
descender_height = self.font.below
|
| 1031 |
+
if descender_height == 0:
|
| 1032 |
+
bbox = BoundingBox2d(self.get_shape(ord("p")).control_vertices()[:-1])
|
| 1033 |
+
descender_height = baseline - bbox.extmin.y
|
| 1034 |
+
return FontMeasurements(
|
| 1035 |
+
baseline=baseline,
|
| 1036 |
+
cap_height=cap_height,
|
| 1037 |
+
x_height=x_height,
|
| 1038 |
+
descender_height=descender_height,
|
| 1039 |
+
)
|
| 1040 |
+
|
| 1041 |
+
def get_text_length(
|
| 1042 |
+
self, text: str, cap_height: float, width_factor: float = 1.0
|
| 1043 |
+
) -> float:
|
| 1044 |
+
scaling_factor = self.get_scaling_factor(cap_height) * width_factor
|
| 1045 |
+
return sum(self.get_advance_width(ord(c)) for c in text) * scaling_factor
|
| 1046 |
+
|
| 1047 |
+
def get_text_glyph_paths(
|
| 1048 |
+
self, text: str, cap_height: float = 1.0, width_factor: float = 1.0
|
| 1049 |
+
) -> list[GlyphPath]:
|
| 1050 |
+
"""Returns the glyph paths of string `s` as a list, scaled to cap height."""
|
| 1051 |
+
glyph_paths: list[GlyphPath] = []
|
| 1052 |
+
sy = self.get_scaling_factor(cap_height)
|
| 1053 |
+
sx = sy * width_factor
|
| 1054 |
+
m = Matrix44.scale(sx, sy, 1)
|
| 1055 |
+
current_location = 0.0
|
| 1056 |
+
for c in text:
|
| 1057 |
+
shape_number = ord(c)
|
| 1058 |
+
if shape_number > 32:
|
| 1059 |
+
glyph = self.get_shape(shape_number)
|
| 1060 |
+
m[3, 0] = current_location
|
| 1061 |
+
glyph.transform_inplace(m)
|
| 1062 |
+
glyph_paths.append(glyph)
|
| 1063 |
+
current_location += self.get_advance_width(shape_number) * sx
|
| 1064 |
+
return glyph_paths
|