vecview 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- vecview/__init__.py +85 -0
- vecview/_occlusion.py +532 -0
- vecview/_types.py +31 -0
- vecview/_vec.py +69 -0
- vecview/camera.py +299 -0
- vecview/projections.py +232 -0
- vecview/py.typed +0 -0
- vecview/scene.py +2427 -0
- vecview/shapes.py +571 -0
- vecview-0.2.0.dist-info/METADATA +290 -0
- vecview-0.2.0.dist-info/RECORD +13 -0
- vecview-0.2.0.dist-info/WHEEL +4 -0
- vecview-0.2.0.dist-info/licenses/LICENSE +21 -0
vecview/_vec.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Small vector helpers used across the package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
from vecview._types import Array, Point3, Points3
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def unit(v: Point3) -> Array:
|
|
11
|
+
"""Normalize ``v``, returning it unchanged if it has zero length.
|
|
12
|
+
|
|
13
|
+
A zero vector is passed through rather than raising: degenerate directions
|
|
14
|
+
show up naturally in generated geometry (a wave with zero amplitude, a box
|
|
15
|
+
with zero thickness) and a silent zero draws as nothing, which is the
|
|
16
|
+
intended result.
|
|
17
|
+
"""
|
|
18
|
+
a: Array = np.asarray(v, dtype=np.float64)
|
|
19
|
+
n = float(np.linalg.norm(a))
|
|
20
|
+
return a / n if n else a
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def as_points(pts: Points3) -> Array:
|
|
24
|
+
"""Coerce a point or sequence of points to a ``(n, 3)`` array."""
|
|
25
|
+
a: Array = np.atleast_2d(np.asarray(pts, dtype=np.float64))
|
|
26
|
+
if a.ndim != 2 or a.shape[1] != 3:
|
|
27
|
+
raise ValueError(f"expected world points of shape (n, 3), got {a.shape}")
|
|
28
|
+
return a
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def basis_for(normal: Point3) -> tuple[Array, Array]:
|
|
32
|
+
"""Two orthonormal in-plane directions for the plane with the given normal.
|
|
33
|
+
|
|
34
|
+
The choice of in-plane rotation is arbitrary but deterministic, which is
|
|
35
|
+
what matters for reproducible output.
|
|
36
|
+
"""
|
|
37
|
+
n = unit(normal)
|
|
38
|
+
seed = (0.0, 0.0, 1.0) if abs(float(n[2])) < 0.9 else (1.0, 0.0, 0.0)
|
|
39
|
+
a = unit(np.cross(n, seed))
|
|
40
|
+
return a, np.asarray(np.cross(n, a), dtype=np.float64)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def convex_hull(pts2: Array) -> list[int]:
|
|
44
|
+
"""Indices of the 2D convex hull of ``pts2`` (Andrew's monotone chain).
|
|
45
|
+
|
|
46
|
+
Counter-clockwise in a y-up frame, which is clockwise on an SVG screen.
|
|
47
|
+
Collinear boundary points are dropped. Ties break on index, so the result is
|
|
48
|
+
deterministic for repeated points.
|
|
49
|
+
"""
|
|
50
|
+
order = sorted(range(len(pts2)), key=lambda i: (float(pts2[i, 0]), float(pts2[i, 1]), i))
|
|
51
|
+
|
|
52
|
+
def turn(o: int, a: int, b: int) -> float:
|
|
53
|
+
return float(
|
|
54
|
+
(pts2[a, 0] - pts2[o, 0]) * (pts2[b, 1] - pts2[o, 1])
|
|
55
|
+
- (pts2[a, 1] - pts2[o, 1]) * (pts2[b, 0] - pts2[o, 0])
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
chains: list[list[int]] = []
|
|
59
|
+
for sequence in (order, order[::-1]):
|
|
60
|
+
chain: list[int] = []
|
|
61
|
+
for i in sequence:
|
|
62
|
+
while len(chain) >= 2 and turn(chain[-2], chain[-1], i) <= 0:
|
|
63
|
+
chain.pop()
|
|
64
|
+
chain.append(i)
|
|
65
|
+
chains.append(chain[:-1])
|
|
66
|
+
return chains[0] + chains[1]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
__all__ = ["as_points", "basis_for", "convex_hull", "unit"]
|
vecview/camera.py
ADDED
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
"""Cameras: world coordinates in, SVG user units out.
|
|
2
|
+
|
|
3
|
+
Every camera here is a **parallel projection** -- the projection rays are all
|
|
4
|
+
mutually parallel, so parallel world edges stay parallel on screen and no
|
|
5
|
+
perspective distortion creeps into a lattice or a repeated texture. That is the
|
|
6
|
+
reason schematics of crystals and optical benches are conventionally drawn this
|
|
7
|
+
way, and it is what makes an embedded plot an exact affine transform (see
|
|
8
|
+
:meth:`Camera.plane_matrix`).
|
|
9
|
+
|
|
10
|
+
Parallel projections split into two families, and the distinction is worth
|
|
11
|
+
keeping straight because the words are often used loosely:
|
|
12
|
+
|
|
13
|
+
**Axonometric** projections are *orthographic*: the rays meet the projection
|
|
14
|
+
plane at right angles. They are classified by how many of the three world axes
|
|
15
|
+
share a foreshortening ratio -- three (isometric), two (dimetric), or none
|
|
16
|
+
(trimetric). :class:`OrthographicCamera` covers all three.
|
|
17
|
+
|
|
18
|
+
**Oblique** projections keep one face true-shape and push the third axis away at
|
|
19
|
+
an angle, with rays that are *not* perpendicular to the projection plane.
|
|
20
|
+
Cavalier and cabinet projections are the common cases.
|
|
21
|
+
:class:`ObliqueCamera` covers them. Oblique is emphatically not axonometric,
|
|
22
|
+
though both are parallel.
|
|
23
|
+
|
|
24
|
+
The class hierarchy follows that split, and leaves room for the one projection
|
|
25
|
+
this package does not implement. The concrete projections live in
|
|
26
|
+
:mod:`vecview.projections`; this module defines only what a camera *is*::
|
|
27
|
+
|
|
28
|
+
Camera the projection contract, and nothing more
|
|
29
|
+
+-- ParallelCamera affine: constant rays, so screen offsets are
|
|
30
|
+
| | position-independent
|
|
31
|
+
| +-- OrthographicCamera axonometric, aimed by azimuth and elevation
|
|
32
|
+
| +-- ObliqueCamera cavalier and cabinet
|
|
33
|
+
+-- PerspectiveCamera not implemented; would subclass Camera directly
|
|
34
|
+
|
|
35
|
+
A perspective camera belongs on the second branch rather than under
|
|
36
|
+
:class:`ParallelCamera`, because it is projective rather than affine. It could
|
|
37
|
+
still project points and report depth -- that is all :class:`Camera` promises --
|
|
38
|
+
but :meth:`ParallelCamera.direction`, :meth:`ParallelCamera.screen_basis`,
|
|
39
|
+
:meth:`ParallelCamera.foreshortening` and :meth:`ParallelCamera.plane_matrix`
|
|
40
|
+
would all be meaningless for it, since each assumes a screen offset that does
|
|
41
|
+
not depend on where in the scene you are. Keeping them one level down is what
|
|
42
|
+
stops that from becoming a silent wrong answer.
|
|
43
|
+
|
|
44
|
+
World coordinates are right-handed ``(x, y, z)`` with ``z`` up.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
from __future__ import annotations
|
|
48
|
+
|
|
49
|
+
from abc import ABC, abstractmethod
|
|
50
|
+
from collections.abc import Iterable
|
|
51
|
+
from typing import TYPE_CHECKING
|
|
52
|
+
|
|
53
|
+
import numpy as np
|
|
54
|
+
|
|
55
|
+
from vecview._types import Array, Point3, Points3
|
|
56
|
+
from vecview._vec import as_points, basis_for, unit
|
|
57
|
+
|
|
58
|
+
if TYPE_CHECKING:
|
|
59
|
+
from vecview.shapes import Face
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Camera(ABC):
|
|
63
|
+
"""The projection contract every camera satisfies, and nothing more.
|
|
64
|
+
|
|
65
|
+
A camera turns world points into SVG user units, reports depth so a caller
|
|
66
|
+
can order things itself, and says which faces point at it. Everything
|
|
67
|
+
beyond that depends on *which* projection is in use and lives on a subclass.
|
|
68
|
+
|
|
69
|
+
Instantiate :class:`OrthographicCamera` or :class:`ObliqueCamera`; subclass
|
|
70
|
+
this directly only to add a projection that is not parallel.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
scale: SVG user units per world unit.
|
|
74
|
+
origin: World point that projects to the SVG origin.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
def __init__(self, scale: float, origin: Point3 = (0.0, 0.0, 0.0)) -> None:
|
|
78
|
+
self.scale = float(scale)
|
|
79
|
+
self.origin: Array = np.asarray(origin, dtype=np.float64)
|
|
80
|
+
|
|
81
|
+
def __repr__(self) -> str:
|
|
82
|
+
return f"{type(self).__name__}(scale={self.scale:g})"
|
|
83
|
+
|
|
84
|
+
@abstractmethod
|
|
85
|
+
def project(self, pts: Points3) -> Array:
|
|
86
|
+
"""World points -> SVG user units, shape ``(n, 2)``, ``y`` already flipped."""
|
|
87
|
+
|
|
88
|
+
@abstractmethod
|
|
89
|
+
def depth(self, pts: Points3) -> Array:
|
|
90
|
+
"""Signed depth per point; larger is nearer the camera."""
|
|
91
|
+
|
|
92
|
+
@abstractmethod
|
|
93
|
+
def visible(self, faces: Iterable[Face], *, tol: float = 0.0) -> list[Face]:
|
|
94
|
+
"""Keep the faces pointing toward the camera.
|
|
95
|
+
|
|
96
|
+
Abstract because the test itself differs: for a parallel projection an
|
|
97
|
+
outward normal decides it on its own, while a perspective camera has to
|
|
98
|
+
ask where the face *is* relative to the eye.
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def at(self, pt: Point3) -> tuple[float, float]:
|
|
102
|
+
"""Project one world point to an ``(x, y)`` pair."""
|
|
103
|
+
((x, y),) = self.project([pt])
|
|
104
|
+
return float(x), float(y)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ParallelCamera(Camera):
|
|
108
|
+
"""A parallel projection: all rays mutually parallel, so the map is affine.
|
|
109
|
+
|
|
110
|
+
Being affine is the load-bearing property. It is what makes a screen offset
|
|
111
|
+
independent of position (:meth:`direction`), lets a plane's screen frame be
|
|
112
|
+
solved once (:meth:`screen_basis`), gives every axis a single foreshortening
|
|
113
|
+
ratio (:meth:`foreshortening`), and allows flat content to be embedded in a
|
|
114
|
+
world plane exactly (:meth:`plane_matrix`).
|
|
115
|
+
|
|
116
|
+
Instantiate this directly only to define a parallel projection of your own;
|
|
117
|
+
otherwise use :class:`OrthographicCamera` or :class:`ObliqueCamera`.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
matrix: The ``(2, 3)`` linear map from world displacements to screen
|
|
121
|
+
ones, *before* ``scale``. Row 0 gives screen ``x``, row 1 gives
|
|
122
|
+
screen ``y`` (downward, as SVG counts it).
|
|
123
|
+
view: Direction from the scene *toward* the camera. A face whose outward
|
|
124
|
+
normal has a positive dot product with this is visible. It need not
|
|
125
|
+
be perpendicular to the projection plane -- for an oblique camera it
|
|
126
|
+
is not.
|
|
127
|
+
scale: SVG user units per world unit.
|
|
128
|
+
origin: World point that projects to the SVG origin.
|
|
129
|
+
"""
|
|
130
|
+
|
|
131
|
+
def __init__(
|
|
132
|
+
self,
|
|
133
|
+
matrix: Array | Iterable[Iterable[float]],
|
|
134
|
+
view: Point3,
|
|
135
|
+
scale: float,
|
|
136
|
+
origin: Point3 = (0.0, 0.0, 0.0),
|
|
137
|
+
) -> None:
|
|
138
|
+
m = np.asarray(matrix, dtype=np.float64)
|
|
139
|
+
if m.shape != (2, 3):
|
|
140
|
+
raise ValueError(
|
|
141
|
+
f"projection matrix must have shape (2, 3), got {m.shape}. "
|
|
142
|
+
"To build a camera from angles use OrthographicCamera("
|
|
143
|
+
"azim_deg, elev_deg, scale)."
|
|
144
|
+
)
|
|
145
|
+
if np.linalg.matrix_rank(m) < 2:
|
|
146
|
+
raise ValueError("projection matrix is rank-deficient: it collapses the scene")
|
|
147
|
+
self.matrix: Array = m
|
|
148
|
+
self.view: Array = unit(view)
|
|
149
|
+
super().__init__(scale, origin)
|
|
150
|
+
|
|
151
|
+
# --- projection -------------------------------------------------------
|
|
152
|
+
def project(self, pts: Points3) -> Array:
|
|
153
|
+
"""World points -> SVG user units, shape ``(n, 2)``.
|
|
154
|
+
|
|
155
|
+
The ``y`` axis is already flipped to SVG's screen convention, so the
|
|
156
|
+
result can go straight into an element's coordinates.
|
|
157
|
+
"""
|
|
158
|
+
p = as_points(pts) - self.origin
|
|
159
|
+
out: Array = (p @ self.matrix.T) * self.scale
|
|
160
|
+
return out
|
|
161
|
+
|
|
162
|
+
def direction(self, vec: Point3) -> Array:
|
|
163
|
+
"""Project a world *direction* (not a point) to a screen displacement.
|
|
164
|
+
|
|
165
|
+
Unlike :meth:`project` this ignores ``origin``: a displacement has no
|
|
166
|
+
position, so moving the camera must not change it.
|
|
167
|
+
"""
|
|
168
|
+
d = np.asarray(vec, dtype=np.float64)
|
|
169
|
+
out: Array = (self.matrix @ d) * self.scale
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
def depth(self, pts: Points3) -> Array:
|
|
173
|
+
"""Signed distance along the view axis; larger is nearer the camera.
|
|
174
|
+
|
|
175
|
+
Provided as a query for callers who want to order something by depth
|
|
176
|
+
themselves. :class:`~vecview.scene.Scene` sorts a layer by this only
|
|
177
|
+
when asked, through :meth:`~vecview.scene.Scene.sort_by_depth`.
|
|
178
|
+
"""
|
|
179
|
+
depths: Array = np.asarray(as_points(pts) @ self.view, dtype=np.float64)
|
|
180
|
+
return depths
|
|
181
|
+
|
|
182
|
+
# --- measurement ------------------------------------------------------
|
|
183
|
+
def foreshortening(self) -> tuple[float, float, float]:
|
|
184
|
+
"""Screen length of each unit world axis, in units of ``scale``.
|
|
185
|
+
|
|
186
|
+
The three numbers are what classify an axonometric projection, and they
|
|
187
|
+
are the honest way to check you got the view you meant::
|
|
188
|
+
|
|
189
|
+
OrthographicCamera.isometric(1.0).foreshortening()
|
|
190
|
+
# (0.8165, 0.8165, 0.8165)
|
|
191
|
+
"""
|
|
192
|
+
lengths = np.linalg.norm(self.matrix, axis=0)
|
|
193
|
+
return (float(lengths[0]), float(lengths[1]), float(lengths[2]))
|
|
194
|
+
|
|
195
|
+
# --- frames -----------------------------------------------------------
|
|
196
|
+
def screen_basis(self, normal: Point3 = (0.0, 0.0, 1.0)) -> tuple[Array, Array]:
|
|
197
|
+
"""In-plane world directions that move a point right and *down* on screen.
|
|
198
|
+
|
|
199
|
+
Placing things by eye inside a projected plane is otherwise guesswork:
|
|
200
|
+
at an azimuth of 35 degrees neither ``+x`` nor ``+y`` moves a point
|
|
201
|
+
horizontally across the picture. This returns the two unit world
|
|
202
|
+
vectors lying in the plane with the given ``normal`` that do.
|
|
203
|
+
|
|
204
|
+
Returns:
|
|
205
|
+
``(horizontal, down)``, both unit vectors in the plane.
|
|
206
|
+
|
|
207
|
+
Raises:
|
|
208
|
+
ValueError: If the plane is viewed edge-on. It then projects to a
|
|
209
|
+
line, so no in-plane direction has a screen ``y`` component and
|
|
210
|
+
the mapping cannot be inverted.
|
|
211
|
+
"""
|
|
212
|
+
u, v = basis_for(normal)
|
|
213
|
+
# Columns are the screen displacements of the in-plane basis vectors.
|
|
214
|
+
m = np.column_stack([self.direction(u), self.direction(v)])
|
|
215
|
+
if abs(float(np.linalg.det(m))) < 1e-12:
|
|
216
|
+
raise ValueError(
|
|
217
|
+
"plane is viewed edge-on; it has no in-plane screen basis "
|
|
218
|
+
f"(normal={np.asarray(normal, dtype=np.float64)}, camera={self!r})"
|
|
219
|
+
)
|
|
220
|
+
inv = np.linalg.inv(m)
|
|
221
|
+
right_coeffs = inv @ np.array([1.0, 0.0]) # screen +x
|
|
222
|
+
down_coeffs = inv @ np.array([0.0, 1.0]) # screen +y, i.e. downward
|
|
223
|
+
return (
|
|
224
|
+
unit(right_coeffs[0] * u + right_coeffs[1] * v),
|
|
225
|
+
unit(down_coeffs[0] * u + down_coeffs[1] * v),
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
def plane_matrix(
|
|
229
|
+
self, origin: Point3, u_edge: Point3, v_edge: Point3
|
|
230
|
+
) -> tuple[float, float, float, float, float, float]:
|
|
231
|
+
"""Affine map taking the unit square onto a world-space rectangle.
|
|
232
|
+
|
|
233
|
+
Returns the six coefficients ``(a, b, c, d, e, f)`` of an SVG
|
|
234
|
+
``matrix(a b c d e f)``, which sends content coordinates in
|
|
235
|
+
:math:`[0,1]^2` to the parallelogram spanned by ``u_edge`` and
|
|
236
|
+
``v_edge`` at ``origin``, as projected by this camera.
|
|
237
|
+
|
|
238
|
+
This is what lets flat SVG content -- a plot, an equation, a bitmap --
|
|
239
|
+
sit *in* a plane of the scene rather than on top of the picture. It is
|
|
240
|
+
exact rather than approximate, and for a reason worth knowing: a
|
|
241
|
+
parallel projection is an affine map of world space, so restricting it
|
|
242
|
+
to a plane and composing with that plane's affine parametrization gives
|
|
243
|
+
an affine map of the content, which is precisely what ``matrix``
|
|
244
|
+
expresses. A perspective camera would be *projective* instead, and the
|
|
245
|
+
restriction a homography that ``matrix`` cannot represent.
|
|
246
|
+
|
|
247
|
+
Args:
|
|
248
|
+
origin: World point that content coordinate ``(0, 0)`` lands on --
|
|
249
|
+
the content's top-left corner, since SVG ``y`` grows downward.
|
|
250
|
+
u_edge: World vector from that corner along content ``+x``. Its
|
|
251
|
+
length is the rectangle's width; it is **not** normalized.
|
|
252
|
+
v_edge: World vector from that corner along content ``+y``, i.e.
|
|
253
|
+
*down* the content. Its length is the rectangle's height.
|
|
254
|
+
|
|
255
|
+
Returns:
|
|
256
|
+
``(a, b, c, d, e, f)`` for ``matrix(a b c d e f)``.
|
|
257
|
+
|
|
258
|
+
Raises:
|
|
259
|
+
ValueError: If the rectangle is degenerate or seen exactly edge-on.
|
|
260
|
+
It then projects to a line, collapsing the content to nothing.
|
|
261
|
+
|
|
262
|
+
Content stays upright and unmirrored exactly when ``a > 0`` and
|
|
263
|
+
``d > 0`` -- its ``+x`` must project rightward and its ``+y`` downward.
|
|
264
|
+
A positive determinant alone is **not** enough: a 180-degree rotation
|
|
265
|
+
has one too. See :meth:`vecview.scene.Scene.plane` for how to choose the
|
|
266
|
+
edges.
|
|
267
|
+
"""
|
|
268
|
+
a, b = self.direction(u_edge)
|
|
269
|
+
c, d = self.direction(v_edge)
|
|
270
|
+
if abs(a * d - b * c) < 1e-12:
|
|
271
|
+
raise ValueError(
|
|
272
|
+
"degenerate plane rectangle: it projects to a line, so content "
|
|
273
|
+
f"placed in it would collapse (camera={self!r})"
|
|
274
|
+
)
|
|
275
|
+
e, f = self.at(origin)
|
|
276
|
+
return (float(a), float(b), float(c), float(d), e, f)
|
|
277
|
+
|
|
278
|
+
# --- visibility -------------------------------------------------------
|
|
279
|
+
def faces_camera(self, normal: Point3, *, tol: float = 0.0) -> bool:
|
|
280
|
+
"""Whether an outward-facing ``normal`` points toward the camera."""
|
|
281
|
+
return float(np.dot(unit(normal), self.view)) > tol
|
|
282
|
+
|
|
283
|
+
def visible(self, faces: Iterable[Face], *, tol: float = 0.0) -> list[Face]:
|
|
284
|
+
"""Keep only the faces whose outward normals point toward the camera.
|
|
285
|
+
|
|
286
|
+
This is back-face culling and nothing more. It is exactly right for a
|
|
287
|
+
convex solid such as a box, where it leaves the three visible walls; it
|
|
288
|
+
does not resolve one object occluding another, which is what the layer
|
|
289
|
+
stack is for.
|
|
290
|
+
|
|
291
|
+
Args:
|
|
292
|
+
faces: Faces to filter, typically from :func:`~vecview.shapes.box_faces`.
|
|
293
|
+
tol: Raise above ``0`` to also drop faces seen nearly edge-on,
|
|
294
|
+
which project to slivers.
|
|
295
|
+
"""
|
|
296
|
+
return [f for f in faces if self.faces_camera(f.normal, tol=tol)]
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
__all__ = ["Camera", "ParallelCamera"]
|
vecview/projections.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"""The parallel projections this package ships.
|
|
2
|
+
|
|
3
|
+
Two families, and the distinction is worth keeping straight because the words
|
|
4
|
+
are often used loosely:
|
|
5
|
+
|
|
6
|
+
**Axonometric** projections are orthographic -- the rays meet the projection
|
|
7
|
+
plane at right angles -- and are classified by how many of the three world axes
|
|
8
|
+
share a foreshortening ratio: three (isometric), two (dimetric), or none
|
|
9
|
+
(trimetric). :class:`OrthographicCamera` covers all three.
|
|
10
|
+
|
|
11
|
+
**Oblique** projections keep one face true-shape and push the third axis away at
|
|
12
|
+
an angle, with rays that are *not* perpendicular to the projection plane.
|
|
13
|
+
:class:`ObliqueCamera` covers the cavalier and cabinet cases. Oblique is
|
|
14
|
+
emphatically not axonometric, though both are parallel.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import math
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from vecview._types import Array, Point3
|
|
24
|
+
from vecview.camera import ParallelCamera
|
|
25
|
+
|
|
26
|
+
ISOMETRIC_ELEV_DEG = math.degrees(math.asin(math.tan(math.radians(30.0))))
|
|
27
|
+
"""Elevation at which all three axes foreshorten equally: 35.264... degrees."""
|
|
28
|
+
|
|
29
|
+
ISOMETRIC_RATIO = math.sqrt(2.0 / 3.0)
|
|
30
|
+
"""The shared foreshortening of a true isometric projection: 0.8165."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class OrthographicCamera(ParallelCamera):
|
|
34
|
+
"""Orthographic axonometric camera, aimed by azimuth and elevation.
|
|
35
|
+
|
|
36
|
+
The general constructor gives a **trimetric** projection; the two named
|
|
37
|
+
constructors reach the constrained cases. Which one you have is a question
|
|
38
|
+
about the foreshortening ratios, and :meth:`axonometry` answers it.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
azim_deg: Azimuth of the viewing direction, degrees CCW from ``+x``.
|
|
42
|
+
elev_deg: Elevation of the viewing direction above the ``xy`` plane.
|
|
43
|
+
scale: SVG user units per world unit.
|
|
44
|
+
origin: World point that projects to the SVG origin.
|
|
45
|
+
|
|
46
|
+
Attributes:
|
|
47
|
+
right: World direction that projects to screen ``+x``.
|
|
48
|
+
up: World direction that projects to screen *up* (SVG ``-y``).
|
|
49
|
+
|
|
50
|
+
Unlike the base class, ``right`` and ``up`` here are genuine orthonormal
|
|
51
|
+
world directions, because the projection is orthogonal.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
azim_deg: float,
|
|
57
|
+
elev_deg: float,
|
|
58
|
+
scale: float,
|
|
59
|
+
origin: Point3 = (0.0, 0.0, 0.0),
|
|
60
|
+
) -> None:
|
|
61
|
+
az, el = np.radians(float(azim_deg)), np.radians(float(elev_deg))
|
|
62
|
+
self.azim_deg = float(azim_deg)
|
|
63
|
+
self.elev_deg = float(elev_deg)
|
|
64
|
+
self.right: Array = np.array([-np.sin(az), np.cos(az), 0.0])
|
|
65
|
+
self.up: Array = np.array([-np.cos(az) * np.sin(el), -np.sin(az) * np.sin(el), np.cos(el)])
|
|
66
|
+
view = np.array([np.cos(az) * np.cos(el), np.sin(az) * np.cos(el), np.sin(el)])
|
|
67
|
+
super().__init__(np.array([self.right, -self.up]), view, scale, origin)
|
|
68
|
+
|
|
69
|
+
def __repr__(self) -> str:
|
|
70
|
+
return (
|
|
71
|
+
f"OrthographicCamera(azim_deg={self.azim_deg:g}, "
|
|
72
|
+
f"elev_deg={self.elev_deg:g}, scale={self.scale:g})"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def isometric(
|
|
77
|
+
cls, scale: float, *, azim_deg: float = 45.0, origin: Point3 = (0.0, 0.0, 0.0)
|
|
78
|
+
) -> OrthographicCamera:
|
|
79
|
+
r"""All three axes equally foreshortened, to ``0.8165`` of true length.
|
|
80
|
+
|
|
81
|
+
The classic drafting view: the two horizontal axes come out at exactly
|
|
82
|
+
30 degrees below the horizon, which is why a 30-60 set square draws it.
|
|
83
|
+
|
|
84
|
+
Both angles are forced, not just the elevation. Requiring the two
|
|
85
|
+
horizontal axes to share a ratio gives
|
|
86
|
+
:math:`(\sin^2 a - \cos^2 a)(1 - \sin^2 e) = 0`, so the azimuth must be
|
|
87
|
+
an odd multiple of 45 degrees. The four such azimuths are all isometric
|
|
88
|
+
and differ only in which octant you view from, which is the one choice
|
|
89
|
+
``azim_deg`` leaves open.
|
|
90
|
+
|
|
91
|
+
Note that "isometric drawing" as draftsmen use the term usually scales
|
|
92
|
+
the result back up by ``1 / 0.8165`` so the axes measure true length;
|
|
93
|
+
pass a correspondingly larger ``scale`` if you want that.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
ValueError: If ``azim_deg`` is not an odd multiple of 45 degrees,
|
|
97
|
+
where the projection would not in fact be isometric.
|
|
98
|
+
"""
|
|
99
|
+
if abs((float(azim_deg) - 45.0) % 90.0) > 1e-9:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
f"azim_deg={azim_deg:g} is not isometric: equal foreshortening of the "
|
|
102
|
+
"two horizontal axes requires an odd multiple of 45 degrees "
|
|
103
|
+
"(45, 135, 225, 315), which selects the viewing octant"
|
|
104
|
+
)
|
|
105
|
+
return cls(azim_deg, ISOMETRIC_ELEV_DEG, scale, origin)
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def dimetric(
|
|
109
|
+
cls, scale: float, *, ratio: float = 0.5, origin: Point3 = (0.0, 0.0, 0.0)
|
|
110
|
+
) -> OrthographicCamera:
|
|
111
|
+
r"""Two axes equally foreshortened, the vertical one by ``ratio`` of those.
|
|
112
|
+
|
|
113
|
+
The azimuth is fixed at 45 degrees, which is what makes ``x`` and ``y``
|
|
114
|
+
share a ratio at any elevation; ``ratio`` then picks the elevation:
|
|
115
|
+
|
|
116
|
+
.. math:: \sin^2 e = \frac{2 - r^2}{2 + r^2}
|
|
117
|
+
|
|
118
|
+
``ratio=1`` is isometric. The drafting-standard ``1:1:0.5`` is the
|
|
119
|
+
default, and puts the receding axes 41.4 degrees below the horizon.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
ratio: Vertical foreshortening as a fraction of the horizontal one.
|
|
123
|
+
Must lie in ``(0, sqrt(2)]``; at ``sqrt(2)`` the elevation
|
|
124
|
+
reaches zero and the view is edge-on to the ground plane.
|
|
125
|
+
"""
|
|
126
|
+
if not 0.0 < ratio <= math.sqrt(2.0):
|
|
127
|
+
raise ValueError(f"ratio must lie in (0, sqrt(2)], got {ratio:g}")
|
|
128
|
+
sin_sq = (2.0 - ratio**2) / (2.0 + ratio**2)
|
|
129
|
+
elev = math.degrees(math.asin(math.sqrt(max(sin_sq, 0.0))))
|
|
130
|
+
return cls(45.0, elev, scale, origin)
|
|
131
|
+
|
|
132
|
+
def axonometry(self, *, tol: float = 1e-6) -> str:
|
|
133
|
+
"""Classify this projection: ``"isometric"``, ``"dimetric"``, or ``"trimetric"``.
|
|
134
|
+
|
|
135
|
+
Decided from :meth:`foreshortening`, so it reports what the camera
|
|
136
|
+
actually does rather than how it was constructed.
|
|
137
|
+
"""
|
|
138
|
+
fx, fy, fz = self.foreshortening()
|
|
139
|
+
equal = sum(abs(a - b) <= tol for a, b in ((fx, fy), (fy, fz), (fx, fz)))
|
|
140
|
+
if equal == 3:
|
|
141
|
+
return "isometric"
|
|
142
|
+
if equal >= 1:
|
|
143
|
+
return "dimetric"
|
|
144
|
+
return "trimetric"
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class ObliqueCamera(ParallelCamera):
|
|
148
|
+
"""Oblique parallel projection: one plane true-shape, the third axis pushed back.
|
|
149
|
+
|
|
150
|
+
The ``xz`` plane is drawn at true shape and true angle -- world ``x`` runs
|
|
151
|
+
along screen ``+x`` and world ``z`` straight up -- while world ``y`` recedes
|
|
152
|
+
at ``angle_deg`` above the horizon, foreshortened by ``depth_ratio``.
|
|
153
|
+
|
|
154
|
+
Oblique is **not** axonometric: its rays are not perpendicular to the
|
|
155
|
+
projection plane, so no choice of azimuth and elevation reproduces it. It
|
|
156
|
+
is still a parallel projection, so every guarantee this package rests on --
|
|
157
|
+
parallel edges, exact affine plane embedding -- continues to hold.
|
|
158
|
+
|
|
159
|
+
Args:
|
|
160
|
+
scale: SVG user units per world unit.
|
|
161
|
+
depth_ratio: Foreshortening of the receding ``y`` axis. ``1`` is
|
|
162
|
+
cavalier, ``0.5`` cabinet.
|
|
163
|
+
angle_deg: Screen angle of the receding axis above the horizon,
|
|
164
|
+
conventionally 30, 45, or 60. Must not be a multiple of 180, which
|
|
165
|
+
would flatten ``y`` onto the horizontal axis.
|
|
166
|
+
origin: World point that projects to the SVG origin.
|
|
167
|
+
"""
|
|
168
|
+
|
|
169
|
+
def __init__(
|
|
170
|
+
self,
|
|
171
|
+
scale: float,
|
|
172
|
+
*,
|
|
173
|
+
depth_ratio: float = 0.5,
|
|
174
|
+
angle_deg: float = 45.0,
|
|
175
|
+
origin: Point3 = (0.0, 0.0, 0.0),
|
|
176
|
+
) -> None:
|
|
177
|
+
if depth_ratio <= 0.0:
|
|
178
|
+
raise ValueError(f"depth_ratio must be positive, got {depth_ratio:g}")
|
|
179
|
+
a = math.radians(float(angle_deg))
|
|
180
|
+
if abs(math.sin(a)) < 1e-12:
|
|
181
|
+
raise ValueError(
|
|
182
|
+
f"angle_deg={angle_deg:g} puts the receding axis on the horizontal, "
|
|
183
|
+
"collapsing the projection"
|
|
184
|
+
)
|
|
185
|
+
self.depth_ratio = float(depth_ratio)
|
|
186
|
+
self.angle_deg = float(angle_deg)
|
|
187
|
+
dx = self.depth_ratio * math.cos(a)
|
|
188
|
+
dy = self.depth_ratio * math.sin(a)
|
|
189
|
+
# Row 0 is screen x, row 1 screen y (downward): x -> right, z -> up, and
|
|
190
|
+
# y -> up-and-right by (dx, dy).
|
|
191
|
+
matrix = np.array([[1.0, dx, 0.0], [0.0, -dy, -1.0]])
|
|
192
|
+
# The projection direction is the null vector of `matrix`; the camera
|
|
193
|
+
# lies along it on the -y side, so front faces (normal -y) are visible.
|
|
194
|
+
view = np.array([dx, -1.0, dy])
|
|
195
|
+
super().__init__(matrix, view, scale, origin)
|
|
196
|
+
|
|
197
|
+
def __repr__(self) -> str:
|
|
198
|
+
return (
|
|
199
|
+
f"ObliqueCamera(scale={self.scale:g}, depth_ratio={self.depth_ratio:g}, "
|
|
200
|
+
f"angle_deg={self.angle_deg:g})"
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
@classmethod
|
|
204
|
+
def cavalier(
|
|
205
|
+
cls, scale: float, *, angle_deg: float = 45.0, origin: Point3 = (0.0, 0.0, 0.0)
|
|
206
|
+
) -> ObliqueCamera:
|
|
207
|
+
"""Cavalier oblique: the receding axis at full length.
|
|
208
|
+
|
|
209
|
+
Nothing is foreshortened, so every edge measures true -- convenient, and
|
|
210
|
+
the reason the result looks too deep to the eye.
|
|
211
|
+
"""
|
|
212
|
+
return cls(scale, depth_ratio=1.0, angle_deg=angle_deg, origin=origin)
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def cabinet(
|
|
216
|
+
cls, scale: float, *, angle_deg: float = 45.0, origin: Point3 = (0.0, 0.0, 0.0)
|
|
217
|
+
) -> ObliqueCamera:
|
|
218
|
+
"""Cabinet oblique: the receding axis at half length.
|
|
219
|
+
|
|
220
|
+
Halving the depth is what makes cabinet projection look right where
|
|
221
|
+
cavalier looks stretched, at the cost of one axis no longer measuring
|
|
222
|
+
true.
|
|
223
|
+
"""
|
|
224
|
+
return cls(scale, depth_ratio=0.5, angle_deg=angle_deg, origin=origin)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
__all__ = [
|
|
228
|
+
"ISOMETRIC_ELEV_DEG",
|
|
229
|
+
"ISOMETRIC_RATIO",
|
|
230
|
+
"ObliqueCamera",
|
|
231
|
+
"OrthographicCamera",
|
|
232
|
+
]
|
vecview/py.typed
ADDED
|
File without changes
|