Files
tiny-gpt/spatial/geom.py
T

168 lines
5.8 KiB
Python

"""Geometry primitives: points, boxes, faces, gaps.
No third-party dependencies on purpose. Everything here is a few dots and norms
on hand-written tuples, because these modules have to run on machines where pip
cannot install numpy, and the inputs are four boxes, not a mesh.
The one idea worth keeping straight: a *box* is not enough to talk about
contact, because contact is a statement about **surfaces**. ``box_faces`` turns
a box into six (axis, sign, plane, rect) records, which is the poor man's B-rep
and the object every rule below is written against.
"""
from __future__ import annotations
def _sub(u, v):
return (u[0] - v[0], u[1] - v[1], u[2] - v[2])
def _add(u, v):
return (u[0] + v[0], u[1] + v[1], u[2] + v[2])
def _mul(u, s):
return (u[0] * s, u[1] * s, u[2] * s)
def _dot(u, v):
return u[0] * v[0] + u[1] * v[1] + u[2] * v[2]
def _len(u):
return _dot(u, u) ** 0.5
def box_triangles(box) -> list:
"""12 triangles for an axis-aligned box. Surface only, no interior.
Plain tuples on purpose: this module has to run on a machine that has no
third-party packages at all, and the arithmetic here is a few dots and
norms on four boxes. numpy would be the only dependency in the file.
"""
x0, y0, z0, x1, y1, z1 = (float(v) for v in box)
c = [(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0),
(x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)]
faces = [(0, 2, 1), (0, 3, 2), (4, 5, 6), (4, 6, 7), (0, 1, 5), (0, 5, 4),
(1, 2, 6), (1, 6, 5), (2, 3, 7), (2, 7, 6), (3, 0, 4), (3, 4, 7)]
return [tuple(c[i] for i in f) for f in faces]
def _pt_tri(p, tri) -> float:
"""Distance from a point to a triangle (Ericson, clamped barycentric)."""
a, b, c = tri
ab, ac, ap = _sub(b, a), _sub(c, a), _sub(p, a)
d1, d2 = _dot(ab, ap), _dot(ac, ap)
if d1 <= 0 and d2 <= 0:
return _len(ap)
bp = _sub(p, b)
d3, d4 = _dot(ab, bp), _dot(ac, bp)
if d3 >= 0 and d4 <= d3:
return _len(bp)
vc = d1 * d4 - d3 * d2
if vc <= 0 <= d1 and d3 <= 0:
return _len(_sub(p, _add(a, _mul(ab, d1 / (d1 - d3)))))
cp = _sub(p, c)
d5, d6 = _dot(ab, cp), _dot(ac, cp)
if d6 >= 0 and d5 <= d6:
return _len(cp)
vb = d5 * d2 - d1 * d6
if vb <= 0 <= d2 and d6 <= 0:
return _len(_sub(p, _add(a, _mul(ac, d2 / (d2 - d6)))))
va = d3 * d6 - d5 * d4
if va <= 0 and (d4 - d3) >= 0 and (d5 - d6) >= 0:
w = (d4 - d3) / ((d4 - d3) + (d5 - d6))
return _len(_sub(p, _add(b, _mul(_sub(c, b), w))))
denom = 1.0 / (va + vb + vc)
return _len(_sub(p, _add(a, _add(_mul(ab, vb * denom), _mul(ac, vc * denom)))))
def _aabb_gap(a, b) -> float:
"""Lower bound on the surface distance -- used only as a cheap prefilter."""
dx = max(0.0, max(a[0] - b[3], b[0] - a[3]))
dy = max(0.0, max(a[1] - b[4], b[1] - a[4]))
dz = max(0.0, max(a[2] - b[5], b[2] - a[5]))
return (dx * dx + dy * dy + dz * dz) ** 0.5
def box_faces(box) -> list:
"""The six faces of an axis-aligned box as (axis, sign, plane, rect2d).
``rect2d`` is the face's extent in the two axes it spans, in ascending order.
This is the poor man's B-rep: faces are stored as *surfaces*, not as vertex
triples, because contact is a statement about surfaces.
"""
x0, y0, z0, x1, y1, z1 = (float(v) for v in box)
lo, hi = (x0, y0, z0), (x1, y1, z1)
out = []
for ax in range(3):
u, v = [i for i in range(3) if i != ax]
rect = (lo[u], lo[v], hi[u], hi[v])
out.append((ax, -1, lo[ax], rect))
out.append((ax, +1, hi[ax], rect))
return out
def contact_area(fa, fb, eps: float = 0.0) -> float:
"""Overlap area of two faces if they are coincident, else 0.
Coincident means: same plane orientation (same axis, opposite outward
normals -- two faces pointing the same way are facing each other, not
touching) and the same offset along that axis, up to ``eps``, which only
has to absorb floating-point noise from transforms. Line and point contacts
(zero overlap area) are deliberately *not* contacts: in a B-rep they are a
separate topological case and pretending a rectangle of zero width is a
surface would be the same mistake as the distance threshold.
"""
ax, sa, pa, ra = fa
bx, sb, pb, rb = fb
if ax != bx or sa == sb or abs(pa - pb) > eps:
return 0.0
ou = min(ra[2], rb[2]) - max(ra[0], rb[0])
ov = min(ra[3], rb[3]) - max(ra[1], rb[1])
if ou <= 0 or ov <= 0:
return 0.0
return ou * ov
def box_contact_area(box_a, box_b, eps: float = 0.0) -> float:
best = 0.0
for fa in box_faces(box_a):
for fb in box_faces(box_b):
a = contact_area(fa, fb, eps)
if a > best:
best = a
return best
def surface_gap(box_a, box_b) -> float:
"""Minimum distance between two box surfaces, measured on triangles.
Vertex-to-triangle only: edge-to-edge minima are missed, which can overestimate
the gap when two edges cross without a vertex near the contact. For the
separation this benchmark actually has (>=16 grid units) it never matters --
and that "never matters" is itself one of the findings.
Kept for the clearance column only. Contact is decided by ``contact_area``,
which needs no distance at all.
"""
ta, tb = box_triangles(box_a), box_triangles(box_b)
va, vb = _vertices(ta), _vertices(tb)
best = float("inf")
for tri in ta:
for p in vb:
best = min(best, _pt_tri(p, tri))
for tri in tb:
for p in va:
best = min(best, _pt_tri(p, tri))
return best
def _vertices(tris) -> list:
seen, out = set(), []
for tri in tris:
for p in tri:
if p not in seen:
seen.add(p)
out.append(p)
return out