brokkr_kitbash.plate: hard plates from a plate table, in numpy alone

plate.py turns a brokkr.plates.v0 table into each plate's convex solid (by
faces, slab, sections or points), its seeded detail panels, their corner
bolts and its anchors' frames. The table alone decides the result: the hull
is built here, facets are ordered in the table frame, seeds are data.

Fixtures plates_bastion/paladin/raptor.json hold tables converted from the
three mech branches (eeda8bf, c35e57e, 0c27103) and the truth each branch's
own builder made in Blender 5.3. test_plate.py's KNOWN names the eleven
fixture plates the truth cannot be met on (float32 solves, a corner
bastion's builder lost, one tie Blender's loop order decided).

Cut hard-plate-core (aetheria-release:cut_spec:cut-hard-plate-core.r1).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 14:29:40 +01:00
commit ed2ed9eeb8
6 changed files with 5895 additions and 1 deletions

View file

@ -0,0 +1,802 @@
"""brokkr.plates.v0: {"schema": "brokkr.plates.v0", "plates": [row, ...]}, a table of hard armour plates.
numpy and the standard library only, tested without Blender (tests/test_plate.py); docs/kitbash.md, Hard plates,
states the format in full. A hard plate is a convex faceted solid: every facet flat, every edge a chamfer the
caller's Bevel makes. This module turns one table into each plate's solid, its detail panels, their corner bolts
and the frames of its anchors. The table alone decides the result: coordinates are metres in the table's own frame
(no host and no world reach this module), every clad carries its seed as data, and facets are ordered by a rule on
the solid as built in the table frame.
A row: name, mat, bevel, sides ("one" or "both"), mirror, exactly one solid form, clad, face, fits.
Solid forms, each a set of points whose convex hull is the plate:
faces [{at, normal} | {through: [a, b, c], out}, ...]: the corners of what the half-spaces bound
slab {at, normal, up, right, outline, thick, taper, back, gap}: an outline drawn on the outer face, the
face's rim chamfered taper, the back face thick behind and scaled back about the outline's middle;
or {corners, names, inside, lift, ...}: the outer face is the least-squares plane of the corners,
outward away from `inside`, standing lift off them
sections [[z, w, y0, y1, c], ...]: chamfered rectangles down a limb
points [[x, y, z], ...]
check(document) returns the table with every default written in, or raises PlateError naming the path.
build(table, side=1) returns one entry per plate built: name, solid (V, faces), facets, panels (V, faces),
bolts (V, faces), anchors, report. Both are pure: nothing is cached and nothing is written.
"""
from __future__ import annotations
import math
import random
import re
from typing import Any
import numpy as np
from . import core
SCHEMA = "brokkr.plates.v0"
ROWS = (1, 256)
OUTLINE = (3, 64)
FACES = (4, 32)
SECTIONS = (2, 16)
POINTS = (4, 64)
SELECTORS = (1, 8)
FITS = 64
FAR = 1e3 # a corner of a faces row farther than this from the origin: the faces bound nothing useful
FLAT = 0.05 # a corners slab's points may stand off their plane by this share of their extent
MERGE = 0.5 # degrees: facets closer than this are one facet; a two-edged vertex turning less is dropped
TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: the tie rules decide
OUTER = 0.97 # clad facets "outer": the facet's normal on the face's normal is over this
SHARE = (0.36, 0.64) # where a split panel's cut falls along the facet's longest edge
MITER = 0.3 # an inset corner moves at most c / MITER
PANEL_MIN = (0.25, 0.02) # a panel under this share of its facet, or under this many m2, is not made
SINK, CHAMFER = 0.02, 0.02 # a panel starts this far under its facet; its far rim is chamfered this much
BOLT = 0.028
RANGES = {"thick": (0.001, 2.0), "taper": (0.0, 0.5), "back": (0.1, 1.5), "gap": (0.0, 0.5), "lift": (0.0, 1.0)}
KINDS = ("mark", "hose_port")
class PlateError(ValueError):
"""The plate table breaks a rule of the format, or a row bounds no solid; the message names the path."""
# --- reading the table ----------------------------------------------------------------------------------------------
def _number(value: Any, path: str, low: float | None = None, high: float | None = None) -> float:
if not core.finite(value):
raise PlateError(f"{path}: {value!r} is not a finite number")
if (low is not None and value < low) or (high is not None and value > high):
raise PlateError(f"{path}: {value} is outside {low} to {high}")
return float(value)
def _vector(value: Any, path: str, size: int = 3) -> list[float]:
if not isinstance(value, (list, tuple)) or len(value) != size:
raise PlateError(f"{path}: wants {size} numbers")
return [_number(v, f"{path}[{i}]") for i, v in enumerate(value)]
def _object(value: Any, path: str, required: tuple[str, ...], optional: tuple[str, ...] = ()) -> dict:
if not isinstance(value, dict):
raise PlateError(f"{path}: wants an object")
for key in value:
if key not in required and key not in optional:
raise PlateError(f"{path}.{key}: unknown key (known: {', '.join(required + optional)})")
for key in required:
if key not in value:
raise PlateError(f"{path}.{key}: missing")
return value
def _list(value: Any, path: str, bounds: tuple[int, int]) -> list:
if not isinstance(value, (list, tuple)) or not bounds[0] <= len(value) <= bounds[1]:
raise PlateError(f"{path}: wants {bounds[0]} to {bounds[1]} entries")
return list(value)
def _area2(ring: np.ndarray) -> float:
x, y = ring[:, 0], ring[:, 1]
return 0.5 * float(np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))
def _crosses(ring: np.ndarray) -> bool:
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
n = len(ring)
for i in range(n):
a, b = ring[i], ring[(i + 1) % n]
for j in range(i + 2, n):
if (j + 1) % n == i:
continue
c, d = ring[j], ring[(j + 1) % n]
if turn(a, b, c) * turn(a, b, d) < 0 and turn(c, d, a) * turn(c, d, b) < 0:
return True
return False
def _width(ring: np.ndarray) -> float:
"""The least width of an outline: over its edges, how far the farthest point stands from the edge's line."""
least = math.inf
for i in range(len(ring)):
e = ring[(i + 1) % len(ring)] - ring[i]
off = (ring - ring[i]) @ (np.array([-e[1], e[0]]) / np.linalg.norm(e))
least = min(least, float(off.max() - off.min()))
return least
def outline_points(outline: Any) -> list[list[float]]:
"""An outline's points: the list as given, or {w, h, clip} as a w by h rectangle with its corners cut clip."""
if isinstance(outline, dict):
w, h, c = outline["w"], outline["h"], outline["clip"]
if not c:
return [[-w / 2, h / 2], [w / 2, h / 2], [w / 2, -h / 2], [-w / 2, -h / 2]]
return [[-w / 2 + c, h / 2], [w / 2 - c, h / 2], [w / 2, h / 2 - c], [w / 2, -h / 2 + c], [w / 2 - c, -h / 2], [-w / 2 + c, -h / 2], [-w / 2, -h / 2 + c], [-w / 2, h / 2 - c]]
return [list(p) for p in outline]
def _check_ring(ring: np.ndarray, path: str) -> None:
if any(np.linalg.norm(ring[i] - ring[i - 1]) < TIE for i in range(len(ring))):
raise PlateError(f"{path}: two neighbouring points are the same point")
if abs(_area2(ring)) < 1e-12:
raise PlateError(f"{path}: the outline has zero area")
if _crosses(ring):
raise PlateError(f"{path}: the outline crosses itself")
def _check_slab(slab: Any, path: str) -> dict:
if isinstance(slab, dict) and "corners" in slab:
_object(slab, path, ("corners", "inside", "thick"), ("names", "lift", "taper", "back", "gap", "up"))
out = {"corners": [_vector(p, f"{path}.corners[{i}]") for i, p in enumerate(_list(slab["corners"], f"{path}.corners", OUTLINE))], "inside": _vector(slab["inside"], f"{path}.inside")}
if slab.get("names") is not None:
names = slab["names"]
if not isinstance(names, (list, tuple)) or len(names) != len(out["corners"]) or not all(isinstance(n, str) and n for n in names) or len(set(names)) != len(names):
raise PlateError(f"{path}.names: wants one distinct name per corner")
out["names"] = list(names)
out["lift"] = _number(slab.get("lift", 0.06), f"{path}.lift", *RANGES["lift"])
else:
_object(slab, path, ("at", "normal", "outline", "thick"), ("up", "right", "taper", "back", "gap"))
out = {"at": _vector(slab["at"], f"{path}.at"), "normal": _vector(slab["normal"], f"{path}.normal")}
if slab.get("right") is not None:
out["right"] = _vector(slab["right"], f"{path}.right")
outline = slab["outline"]
if isinstance(outline, dict):
_object(outline, f"{path}.outline", ("w", "h", "clip"))
w, h = (_number(outline[k], f"{path}.outline.{k}", 1e-6, 1e3) for k in "wh")
out["outline"] = {"w": w, "h": h, "clip": _number(outline["clip"], f"{path}.outline.clip", 0.0, 0.5 * min(w, h) - 1e-9)}
else:
out["outline"] = [_vector(p, f"{path}.outline[{i}]", 2) for i, p in enumerate(_list(outline, f"{path}.outline", OUTLINE))]
out["up"] = _vector(slab.get("up", [0, 0, 1]), f"{path}.up")
for key, default in (("thick", None), ("taper", 0.04), ("back", 1.0), ("gap", 0.0)):
out[key] = _number(slab.get(key, default), f"{path}.{key}", *RANGES[key])
return out
def _check_clad(clad: Any, row: dict, path: str) -> dict:
_object(clad, path, ("mat", "min_area", "lifts", "inset", "gap", "split", "seed"), ("facets", "floor", "bolt_r"))
out = {"mat": _name(clad["mat"], f"{path}.mat", 63, None)}
facets = clad.get("facets", "outer" if "slab" in row else None)
if facets is None:
raise PlateError(f"{path}.facets: missing (only a slab has a default, its outer face)")
if facets == "outer":
if "slab" not in row and "face" not in row:
raise PlateError(f"{path}.facets: \"outer\" wants a slab or a row with a face")
elif facets != "all":
picked = []
if isinstance(facets, str):
raise PlateError(f"{path}.facets: wants \"outer\", \"all\" or selectors")
for i, sel in enumerate(_list(facets, f"{path}.facets", SELECTORS)):
at = f"{path}.facets[{i}]"
if isinstance(sel, dict) and "radial" in sel:
_object(sel, at, ("radial", "min_r", "cos"))
picked.append({"radial": _vector(sel["radial"], f"{at}.radial"), "min_r": _number(sel["min_r"], f"{at}.min_r", 0.0, FAR), "cos": _number(sel["cos"], f"{at}.cos", -1.0, 1.0)})
else:
_object(sel, at, ("n", "cos"))
picked.append({"n": _vector(sel["n"], f"{at}.n"), "cos": _number(sel["cos"], f"{at}.cos", -1.0, 1.0)})
axis = picked[-1].get("radial", picked[-1].get("n"))
if not np.linalg.norm(axis) > 0:
raise PlateError(f"{at}: the direction has no length")
facets = picked
out["facets"] = facets
if clad.get("floor") is not None:
out["floor"] = _number(clad["floor"], f"{path}.floor", -1.0, 1.0)
out["min_area"] = _number(clad["min_area"], f"{path}.min_area", 0.0, 1e6)
lifts = clad["lifts"]
if not isinstance(lifts, (list, tuple)) or len(lifts) != 2:
raise PlateError(f"{path}.lifts: wants two lifts")
out["lifts"] = [_number(v, f"{path}.lifts[{i}]", 0.0, 1.0) for i, v in enumerate(lifts)]
out["inset"] = _number(clad["inset"], f"{path}.inset", 0.0, 10.0)
out["gap"] = _number(clad["gap"], f"{path}.gap", 0.0, 10.0)
out["split"] = _number(clad["split"], f"{path}.split", 0.0, 1e6)
seed = clad["seed"]
whole = lambda v: isinstance(v, int) and not isinstance(v, bool) and 0 <= v < 2 ** 63 # noqa: E731
if isinstance(seed, (list, tuple)):
if row["sides"] != "both":
raise PlateError(f"{path}.seed: a pair of seeds is for a row with sides \"both\"")
if len(seed) != 2 or not all(whole(v) for v in seed):
raise PlateError(f"{path}.seed: wants an integer or [right, left]")
seed = list(seed)
elif not whole(seed):
raise PlateError(f"{path}.seed: wants an integer or [right, left]")
out["seed"] = seed
out["bolt_r"] = _number(clad.get("bolt_r", BOLT), f"{path}.bolt_r", 0.001, 1.0)
return out
def _name(value: Any, path: str, most: int, pattern: str | None) -> str:
if not isinstance(value, str) or not 1 <= len(value) <= most or (pattern and not re.fullmatch(pattern, value)):
raise PlateError(f"{path}: wants a name of 1 to {most} characters" + (" from a-z A-Z 0-9 _ ." if pattern else ""))
return value
def _check_row(row: Any, path: str) -> dict:
forms = ("faces", "slab", "sections", "points")
_object(row, path, ("name", "mat"), ("bevel", "sides", "mirror", "clad", "face", "fits") + forms)
out = {"name": _name(row["name"], f"{path}.name", 48, r"[A-Za-z0-9_.]+"), "mat": _name(row["mat"], f"{path}.mat", 63, None),
"bevel": _number(row.get("bevel", 0.0), f"{path}.bevel", 0.0, 0.1), "sides": row.get("sides", "one"), "mirror": row.get("mirror", False)}
if out["sides"] not in ("one", "both"):
raise PlateError(f"{path}.sides: wants \"one\" or \"both\"")
if not isinstance(out["mirror"], bool):
raise PlateError(f"{path}.mirror: wants true or false")
given = [f for f in forms if f in row]
if len(given) != 1:
raise PlateError(f"{path}: wants exactly one solid form of {', '.join(forms)} (has {', '.join(given) or 'none'})")
form = given[0]
if form == "faces":
faces = []
for i, face in enumerate(_list(row["faces"], f"{path}.faces", FACES)):
at = f"{path}.faces[{i}]"
if isinstance(face, dict) and "through" in face:
_object(face, at, ("through", "out"))
if not isinstance(face["through"], (list, tuple)) or len(face["through"]) != 3:
raise PlateError(f"{at}.through: wants three points")
faces.append({"through": [_vector(p, f"{at}.through[{k}]") for k, p in enumerate(face["through"])], "out": _vector(face["out"], f"{at}.out")})
else:
_object(face, at, ("at", "normal"))
faces.append({"at": _vector(face["at"], f"{at}.at"), "normal": _vector(face["normal"], f"{at}.normal")})
out["faces"] = faces
elif form == "slab":
out["slab"] = _check_slab(row["slab"], f"{path}.slab")
elif form == "sections":
out["sections"] = [_vector(s, f"{path}.sections[{i}]", 5) for i, s in enumerate(_list(row["sections"], f"{path}.sections", SECTIONS))]
else:
out["points"] = [_vector(p, f"{path}.points[{i}]") for i, p in enumerate(_list(row["points"], f"{path}.points", POINTS))]
if row.get("face") is not None:
if form == "slab":
raise PlateError(f"{path}.face: a slab's face is its outer face")
face = _object(row["face"], f"{path}.face", ("at", "normal"), ("up", "right"))
out["face"] = {"at": _vector(face["at"], f"{path}.face.at"), "normal": _vector(face["normal"], f"{path}.face.normal"), "up": _vector(face.get("up", [0, 0, 1]), f"{path}.face.up")}
if face.get("right") is not None:
out["face"]["right"] = _vector(face["right"], f"{path}.face.right")
out["clad"] = None if row.get("clad") is None else _check_clad(row["clad"], out, f"{path}.clad")
fits, names = [], set()
for i, fit in enumerate(_list(row.get("fits", []), f"{path}.fits", (0, FITS))):
at = f"{path}.fits[{i}]"
kind = fit.get("kind") if isinstance(fit, dict) else None
if kind not in KINDS:
raise PlateError(f"{at}.kind: {kind!r} is not a fit of this table (known: {', '.join(KINDS)})")
if form != "slab" and "face" not in out:
raise PlateError(f"{at}: a fit stands on a face; this row is no slab and names no face")
if kind == "mark":
_object(fit, at, ("kind", "id", "at", "height"))
entry = {"kind": kind, "id": _name(fit["id"], f"{at}.id", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "height": _number(fit["height"], f"{at}.height", 1e-4, 100.0)}
else:
_object(fit, at, ("kind", "name", "at"), ("lift",))
entry = {"kind": kind, "name": _name(fit["name"], f"{at}.name", 63, None), "at": _vector(fit["at"], f"{at}.at", 2), "lift": _number(fit.get("lift", 0.0), f"{at}.lift", -1.0, 1.0)}
name = entry.get("id", entry.get("name"))
if name in names:
raise PlateError(f"{at}: a second anchor named {name!r} in this row")
names.add(name)
fits.append(entry)
out["fits"] = fits
return out
def check(document: Any) -> dict:
"""The table with every default written in. Raises PlateError naming the path of what breaks the format, and
of a row that bounds no solid: every row's solid and anchors are made here once, at side +1, and build makes
them the same way, so build meets no refusal check has not."""
table = _read(document)
for i, row in enumerate(table["plates"]):
points, face = _row_points(row, f"plates[{i}]")
hull(_mirrored(points, row["mirror"]), f"plates[{i}]")
for j, fit in enumerate(row["fits"]):
_frame(face[0], face[3], (0.0, 0.0, 1.0) if fit["kind"] == "mark" else face[2], f"plates[{i}].fits[{j}]")
return table
def _read(document: Any) -> dict:
_object(document, "document", ("schema", "plates"))
if document["schema"] != SCHEMA:
raise PlateError(f"document.schema: {document['schema']!r} is not {SCHEMA}")
rows = [_check_row(row, f"plates[{i}]") for i, row in enumerate(_list(document["plates"], "plates", ROWS))]
built: dict[str, int] = {}
for i, row in enumerate(rows):
for name in ((row["name"] + ".R", row["name"] + ".L") if row["sides"] == "both" else (row["name"],)):
if name in built:
raise PlateError(f"plates[{i}].name: {name!r} is built by plates[{built[name]}] too")
built[name] = i
return {"schema": SCHEMA, "plates": rows}
# --- points of a solid form -----------------------------------------------------------------------------------------
def _frame(point, normal, up, path: str) -> np.ndarray:
try:
return core.surface_frame(point, normal, up)
except core.KitError as error:
raise PlateError(f"{path}: {error}") from None
def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"):
"""(a, b, n): unit axes of the plane facing `normal`: b the in-plane part of `up`, a across it (b cross n),
turned to the side `right` points to where one is given, so an outline's +a is a named direction."""
frame = _frame((0.0, 0.0, 0.0), normal, up, path)
a, b, n = frame[:3, 0].copy(), frame[:3, 1].copy(), frame[:3, 2].copy()
if right is not None and a @ np.asarray(right, dtype=np.float64) < 0:
a = -a
return a, b, n
def inset2d(ring, c: float) -> np.ndarray:
"""A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER."""
ring = np.asarray(ring, dtype=np.float64)
out = np.empty_like(ring)
for i in range(len(ring)):
p0, p1, p2 = ring[i - 1], ring[i], ring[(i + 1) % len(ring)]
e0, e1 = (p1 - p0) / np.linalg.norm(p1 - p0), (p2 - p1) / np.linalg.norm(p2 - p1)
n0, n1 = np.array([-e0[1], e0[0]]), np.array([-e1[1], e1[0]])
miter = n0 + n1
length = np.linalg.norm(miter)
miter = miter / length if length > 0 else n0
out[i] = p1 + miter * (c / max(float(miter @ n0), MITER))
return out
def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray:
"""A slab's corners: the outline (either winding) drawn in gap, on the plane through origin; the face is that
ring moved in taper, the ring itself stands taper behind it, and the back ring thick behind, scaled back about
the ring's middle."""
ring = np.asarray(outline, dtype=np.float64)
if _area2(ring) < 0:
ring = ring[::-1]
if gap:
ring = inset2d(ring, gap)
inner = inset2d(ring, taper) if taper else ring
middle = ring.mean(axis=0)
rear = middle + (ring - middle) * back
lift = lambda flat, z: origin + np.outer(flat[:, 0], a) + np.outer(flat[:, 1], b) + n * z # noqa: E731
parts = [lift(inner, 0.0)] + ([lift(ring, -taper)] if taper else []) + [lift(rear, -thick)]
return np.vstack(parts)
def corners_of(planes, path: str = "faces") -> np.ndarray:
"""The corners of the convex solid a set of faces [(n, d): kept where n.p <= d] bounds: every three faces'
meeting point inside all the others within 1e-6."""
normals = np.array([p[0] for p in planes], dtype=np.float64)
offsets = np.array([p[1] for p in planes], dtype=np.float64)
out: list[np.ndarray] = []
for i in range(len(planes)):
for j in range(i + 1, len(planes)):
for k in range(j + 1, len(planes)):
m = normals[[i, j, k]]
if abs(np.linalg.det(m)) < 1e-7:
continue
p = np.linalg.solve(m, offsets[[i, j, k]])
if not np.all(normals @ p <= offsets + 1e-6):
continue
if np.linalg.norm(p) >= FAR:
raise PlateError(f"{path}: faces {i}, {j} and {k} meet {np.linalg.norm(p):.0f} m away: the faces do not close the solid")
if not any(np.linalg.norm(p - q) < 1e-5 for q in out):
out.append(p)
if len(out) < 4:
raise PlateError(f"{path}: {len(planes)} faces bound no solid ({len(out)} corners)")
return np.array(out)
def section_points(sections) -> np.ndarray:
"""A housing's corners from its sections down a limb: [z, width, y0, y1, chamfer] each a chamfered rectangle."""
out = []
for z, w, y0, y1, c in sections:
out += [(x, y, z) for x, y in ((-w / 2 + c, y0), (w / 2 - c, y0), (w / 2, y0 + c), (w / 2, y1 - c), (w / 2 - c, y1), (-w / 2 + c, y1), (-w / 2, y1 - c), (-w / 2, y0 + c))]
return np.array(out, dtype=np.float64)
def _unit(v, path: str) -> np.ndarray:
v = np.asarray(v, dtype=np.float64)
length = np.linalg.norm(v)
if not length > 0:
raise PlateError(f"{path}: the direction has no length")
return v / length
def _row_points(row: dict, path: str):
"""(points, face): the row's points at side +1 and its face (origin, a, b, n), None where it has none."""
face = None
if "faces" in row:
planes = []
for i, f in enumerate(row["faces"]):
if "through" in f:
a, b, c = (np.array(p) for p in f["through"])
n = _unit(np.cross(b - a, c - a), f"{path}.faces[{i}].through")
if n @ np.array(f["out"]) < 0:
n = -n
planes.append((n, float(n @ a)))
else:
n = _unit(f["normal"], f"{path}.faces[{i}].normal")
planes.append((n, float(n @ np.array(f["at"]))))
points = corners_of(planes, f"{path}.faces")
elif "slab" in row:
slab, at = row["slab"], f"{path}.slab"
if "corners" in slab:
corners = np.array(slab["corners"])
centre = corners.mean(axis=0)
n = np.linalg.svd(corners - centre)[2][2]
extent = max(float(np.linalg.norm(p - q)) for p in corners for q in corners)
if not extent > 0 or float(np.abs((corners - centre) @ n).max()) > FLAT * extent:
raise PlateError(f"{at}.corners: the corners stand more than {FLAT} of their extent off one plane: that is not a plate")
if n @ (centre - np.array(slab["inside"])) < 0:
n = -n
origin = centre + n * slab["lift"]
a, b, n = plane_basis(n, slab["up"], None, f"{at}.up")
ring = np.column_stack(((corners - origin) @ a, (corners - origin) @ b))
else:
origin = np.array(slab["at"])
a, b, n = plane_basis(slab["normal"], slab["up"], slab.get("right"), f"{at}.normal")
ring = np.array(outline_points(slab["outline"]), dtype=np.float64)
_check_ring(ring, f"{at}.{'corners' if 'corners' in slab else 'outline'}")
drawn = inset2d(ring if _area2(ring) > 0 else ring[::-1], slab["gap"]) if slab["gap"] else ring
if slab["gap"] and _area2(drawn) <= 0:
raise PlateError(f"{at}.gap: {slab['gap']} leaves nothing of the outline")
if slab["taper"] and 2 * slab["taper"] >= _width(drawn):
raise PlateError(f"{at}.taper: {slab['taper']} is half the outline's least width ({_width(drawn):.4f}) or more")
points = slab_points(origin, a, b, n, ring, slab["thick"], slab["taper"], slab["back"], slab["gap"])
face = (origin, a, b, n)
elif "sections" in row:
points = section_points(row["sections"])
else:
points = np.array(row["points"], dtype=np.float64)
if "face" in row:
f = row["face"]
a, b, n = plane_basis(f["normal"], f["up"], f.get("right"), f"{path}.face.normal")
face = (np.array(f["at"]), a, b, n)
return points, face
def _mirrored(points: np.ndarray, mirror: bool) -> np.ndarray:
if not mirror:
return points
return np.vstack([points, points[np.abs(points[:, 0]) > 1e-6] * (-1.0, 1.0, 1.0)])
# --- the hull and its facets ------------------------------------------------------------------------------------------
def _newell(loop: np.ndarray) -> np.ndarray:
return 0.5 * np.cross(loop, np.roll(loop, -1, axis=0)).sum(axis=0)
def _angle(a: np.ndarray, b: np.ndarray) -> float:
return math.degrees(math.atan2(float(np.linalg.norm(np.cross(a, b))), float(a @ b)))
def _lexical(point) -> tuple:
return tuple(round(float(c) / TIE) for c in point)
def hull(points, path: str = "points", merge: float = MERGE):
"""(V, faces, facets): the convex hull of `points`. A facet is every supporting plane's point set, ordered by
angle; adjacent facets whose normals are within `merge` degrees are one facet, and a vertex left with two
edges turning less than `merge` is dropped. faces are wound outward; facets[i] is face i's
{"normal", "area", "centre"} (centre the mean of its vertices). Order: area descending, ties (TIE) by centre
x, y, z; each face starts at its least vertex by x, y, z."""
P = np.asarray(points, dtype=np.float64)
keep: list[int] = []
for i in range(len(P)):
if not any(np.linalg.norm(P[i] - P[k]) < TIE for k in keep):
keep.append(i)
P = P[keep]
n = len(P)
scale = float(np.linalg.norm(P.max(axis=0) - P.min(axis=0))) if n else 0.0
eps = TIE * max(1.0, scale)
found: dict[frozenset, np.ndarray] = {}
probe = P[np.linspace(0, n - 1, min(n, 12)).astype(int)] if n else P
for i in range(n - 2): # every plane through point i and two later points, at once
J, K = np.triu_indices(n - i - 1, 1)
first, second = P[J + i + 1] - P[i], P[K + i + 1] - P[i]
normals = np.cross(first, second)
lengths = np.linalg.norm(normals, axis=1)
good = lengths > 1e-6 * np.linalg.norm(first, axis=1) * np.linalg.norm(second, axis=1)
for key in found: # a plane already found is not found again from its other points
if i in key:
inside = np.zeros(n, dtype=bool)
inside[list(key)] = True
good &= ~(inside[J + i + 1] & inside[K + i + 1])
if not good.any():
continue
normals = normals[good] / lengths[good, None]
part = (probe - P[i]) @ normals.T # a plane a few points stand on both sides of supports nothing
normals = normals[(part.max(axis=0) <= eps) | (part.min(axis=0) >= -eps)]
off = (P - P[i]) @ normals.T
above, below = off.max(axis=0) <= eps, off.min(axis=0) >= -eps
support = np.nonzero(above | below)[0]
if not len(support):
continue
on = np.abs(off[:, support]) <= eps
if on.all(axis=0).any():
raise PlateError(f"{path}: the points lie in one plane: they bound no solid")
for c in np.unique(np.packbits(on, axis=0).T, axis=0, return_index=True)[1]:
key = frozenset(np.nonzero(on[:, c])[0].tolist())
if key not in found:
found[key] = normals[support[c]] if above[support[c]] else -normals[support[c]]
if n < 4 or len(found) < 4:
raise PlateError(f"{path}: {n} distinct points bound no solid")
sets = [s for s in found if not any(s < t for t in found)]
loops, normals = [], []
for on in sets:
normal = found[on]
idx = sorted(on)
centre = P[idx].mean(axis=0)
u = _unit(P[idx[0]] - centre if np.linalg.norm(P[idx[0]] - centre) > eps else P[idx[1]] - centre, path)
u = _unit(u - normal * (u @ normal), path)
v = np.cross(normal, u)
flat = np.column_stack(((P[idx] - centre) @ u, (P[idx] - centre) @ v))
loops.append([idx[k] for k in _hull2d(flat, eps)])
normals.append(normal)
# facets within `merge` degrees across an edge are one facet
group = list(range(len(loops)))
def root(k: int) -> int:
while group[k] != k:
group[k] = group[group[k]]
k = group[k]
return k
owner: dict[tuple[int, int], int] = {}
for k, loop in enumerate(loops):
for a, b in zip(loop, loop[1:] + loop[:1]):
owner[(a, b)] = k
for (a, b), k in owner.items():
other = owner.get((b, a))
if other is not None and other > k and _angle(normals[k], normals[other]) < merge:
group[root(other)] = root(k)
merged: dict[int, list[int]] = {}
for k in range(len(loops)):
merged.setdefault(root(k), []).append(k)
faces: list[list[int]] = []
for members in merged.values():
inside = set(members)
step = {a: b for k in members for a, b in zip(loops[k], loops[k][1:] + loops[k][:1]) if owner.get((b, a)) not in inside}
start = min(step)
loop, at = [start], step[start]
while at != start and len(loop) <= len(step):
loop.append(at)
at = step.get(at, start)
if len(loop) != len(step) or len(loop) < 3:
raise PlateError(f"{path}: facets within {merge} degrees of each other do not make one outline")
faces.append(loop)
# a vertex left on two edges that run on straight is no corner
while True:
edges: dict[int, set[int]] = {}
for loop in faces:
for a, b in zip(loop, loop[1:] + loop[:1]):
edges.setdefault(a, set()).add(b)
edges.setdefault(b, set()).add(a)
gone = set()
for v, ends in edges.items():
if len(ends) == 2 and not ends & gone:
a, b = sorted(ends)
if _angle(P[v] - P[a], P[b] - P[v]) < merge:
gone.add(v)
if not gone:
break
faces = [[v for v in loop if v not in gone] for loop in faces]
faces = [loop for loop in faces if len(loop) >= 3]
used = sorted({v for loop in faces for v in loop})
slot = {v: k for k, v in enumerate(used)}
V = P[used]
rows = []
for loop in faces:
loop = [slot[v] for v in loop]
first = min(range(len(loop)), key=lambda k: _lexical(V[loop[k]]))
loop = loop[first:] + loop[:first]
normal = _newell(V[loop])
area = float(np.linalg.norm(normal))
rows.append((loop, {"normal": normal / area, "area": area, "centre": V[loop].mean(axis=0)}))
rows.sort(key=lambda r: -r[1]["area"])
ordered, k = [], 0
while k < len(rows):
m = k + 1
while m < len(rows) and rows[m - 1][1]["area"] - rows[m][1]["area"] <= TIE:
m += 1
ordered += sorted(rows[k:m], key=lambda r: _lexical(r[1]["centre"]), reverse=True)
k = m
return V, [r[0] for r in ordered], [r[1] for r in ordered]
def _hull2d(flat: np.ndarray, eps: float) -> list[int]:
"""The indices of a planar point set's convex outline, counter-clockwise: the points ordered by angle about
their middle, then every point that does not turn left by more than eps (one inside, or on a straight run)
left out until none is."""
centre = flat.mean(axis=0)
loop = sorted(range(len(flat)), key=lambda k: math.atan2(flat[k][1] - centre[1], flat[k][0] - centre[0]))
changed = True
while changed and len(loop) > 3:
changed = False
for at in range(len(loop)):
a, b, c = flat[loop[at - 1]], flat[loop[at]], flat[loop[(at + 1) % len(loop)]]
if (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0]) <= eps * max(float(np.linalg.norm(c - a)), eps):
del loop[at]
changed = True
break
return loop
# --- detail panels and their bolts ------------------------------------------------------------------------------------
class _Mesh:
def __init__(self):
self.verts: list[np.ndarray] = []
self.faces: list[list[int]] = []
def add(self, verts, faces) -> None:
base = len(self.verts)
self.verts += [np.asarray(v, dtype=np.float64) for v in verts]
self.faces += [[base + k for k in face] for face in faces]
def done(self):
return (np.array(self.verts, dtype=np.float64).reshape(-1, 3), self.faces)
def _stand(normal: np.ndarray):
"""(x, y) across a facet whose normal is given: y the table's +z off the normal (its +y where the facet is
level), x = y cross normal. A panel's bolts are turned by it."""
y = np.array([0.0, 0.0, 1.0]) - normal * normal[2]
if np.linalg.norm(y) < 1e-4:
y = np.array([0.0, 1.0, 0.0]) - normal * normal[1]
y = y / np.linalg.norm(y)
return np.cross(y, normal), y
def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[np.ndarray]:
"""A convex polygon (3D points in one plane) kept on the side of a line the normal points away from."""
out = []
for i, a in enumerate(poly):
b = poly[(i + 1) % len(poly)]
da, db = float((a - point) @ normal), float((b - point) @ normal)
if da <= 0:
out.append(a)
if (da < 0) != (db < 0) and abs(da - db) > 1e-9:
out.append(a + (b - a) * (da / (da - db)))
return out
def prism(mesh: _Mesh, origin, x, y, z, outline: np.ndarray, depth: float, chamfer: float) -> None:
"""A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered."""
c = min(chamfer, 0.45 * depth)
rings = [(outline, 0.0), (outline, depth - c), (inset2d(outline, c) if c > 1e-6 else outline, depth)]
n = len(outline)
verts = [origin + x * q[0] + y * q[1] + z * h for ring, h in rings for q in ring]
faces = [list(reversed(range(n))), [2 * n + k for k in range(n)]]
for low in (0, n):
faces += [[low + k, low + (k + 1) % n, low + n + (k + 1) % n, low + n + k] for k in range(n)]
mesh.add(verts, faces)
def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None:
"""A hexagonal head centred on origin: r to its corners, depth along z, half each way."""
ring = [(r * math.sin(k * math.pi / 3), r * math.cos(k * math.pi / 3)) for k in range(6)]
verts = [origin + x * q[0] + y * q[1] + z * h for h in (-depth / 2, depth / 2) for q in ring]
faces = [[0, 5, 4, 3, 2, 1], [6, 7, 8, 9, 10, 11]] + [[k, (k + 1) % 6, 6 + (k + 1) % 6, 6 + k] for k in range(6)]
faces = [list(reversed(f)) for f in faces] # the ring runs clockwise about z
mesh.add(verts, faces)
def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarray, lift: float, inset: float, bolt_r: float) -> bool:
"""A raised panel on a flat convex polygon: the polygon moved in inset on every edge, standing lift over it from
SINK below, its far rim chamfered; a bolt inside each of its corners. False for a polygon too small for one."""
pts = np.array(polygon)
centre = pts.mean(axis=0)
normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0)
if np.linalg.norm(normal) < 1e-9:
return False
normal = normal / np.linalg.norm(normal)
if normal @ out < 0:
pts, normal = pts[::-1], -normal
x, y = _stand(normal)
flat = np.column_stack(((pts - centre) @ x, (pts - centre) @ y))
inner = inset2d(flat, inset)
if _area2(inner) < PANEL_MIN[0] * _area2(flat) or _area2(inner) < PANEL_MIN[1]:
return False
prism(panels, centre - normal * SINK, x, y, normal, inner, lift + SINK, CHAMFER)
for q in inset2d(inner, 3.2 * bolt_r):
hex_bolt(bolts, centre + x * q[0] + y * q[1] + normal * (lift + 0.3 * bolt_r), x, y, normal, bolt_r, 0.6 * bolt_r)
return True
def _longest(pts: list[np.ndarray]) -> int:
"""The index of a polygon's longest edge; edges within TIE of it tie, and the tie goes to the edge whose middle
is least by x, y, z."""
lengths = [float(np.linalg.norm(pts[(k + 1) % len(pts)] - pts[k])) for k in range(len(pts))]
top = max(lengths)
return max((k for k in range(len(pts)) if top - lengths[k] <= TIE), key=lambda k: _lexical((pts[k] + pts[(k + 1) % len(pts)]) / 2))
def _selected(clad: dict, normal: np.ndarray, centre: np.ndarray, face_n, side: int) -> bool:
if "floor" in clad and normal[2] < clad["floor"]:
return False
if clad["facets"] == "all":
return True
if clad["facets"] == "outer":
return float(normal @ face_n) > OUTER
flip = np.array([float(side), 1.0, 1.0])
for sel in clad["facets"]:
if "radial" in sel:
axis = _unit(sel["radial"], "radial") * flip
radial = centre - axis * (centre @ axis)
length = float(np.linalg.norm(radial))
if length > sel["min_r"] and float(normal @ radial) / length > sel["cos"]:
return True
elif float(normal @ (_unit(sel["n"], "n") * flip)) > sel["cos"]:
return True
return False
def clad_layout(V: np.ndarray, faces, facets, clad: dict, seed: int, face_n, side: int):
"""(panels, bolts, count, lift on the face): the detail plating of one solid. One seeded source draws, in facet
order: for a kept facet over `split`, where its cut falls (SHARE); for every kept facet, which lift comes
first."""
rnd = random.Random(seed)
panels, bolts, made, on_face = _Mesh(), _Mesh(), 0, 0.0
for loop, facet in zip(faces, facets):
if facet["area"] < clad["min_area"]:
continue
pts = [V[k] for k in loop]
if not _selected(clad, facet["normal"], facet["centre"], face_n, side):
continue
if facet["area"] > clad["split"]:
k = _longest(pts)
a, b = pts[k], pts[(k + 1) % len(pts)]
way = (b - a) / np.linalg.norm(b - a)
at = a + (b - a) * rnd.uniform(*SHARE)
parts = [clip(pts, at - way * clad["gap"] / 2, way), clip(pts, at + way * clad["gap"] / 2, -way)]
else:
parts = [pts]
order = list(clad["lifts"]) if rnd.random() < 0.5 else list(reversed(clad["lifts"]))
for i, part in enumerate(parts):
if len(part) >= 3 and panel(panels, bolts, part, facet["normal"], order[i % 2], clad["inset"], clad["bolt_r"]):
made += 1
if face_n is not None and float(facet["normal"] @ face_n) > OUTER:
on_face = clad["lifts"][0]
return panels.done(), bolts.done(), made, on_face
# --- build ------------------------------------------------------------------------------------------------------------
def build(table: Any, side: int = 1) -> list[dict]:
"""One entry per plate built, in the table's order: a row with sides "both" is built at `side`, then at -side.
Side -1 negates x of every point before the hull, so facets, panels and anchors are those of the mirrored solid
as built; a clad selector's direction is mirrored with it. Names end .R at side +1 and .L at -1 on a two-sided
row. Each entry: {name, row (its index in the table), mat, bevel, side, solid: (V, faces), facets, panels: (V, faces), bolts: (V, faces),
anchors: [{kind, name, matrix, mirrored, height?}], report: {corners, facets, panels, bolts}}."""
if side not in (1, -1):
raise PlateError(f"side: {side!r} is not 1 or -1")
table = _read(table)
built = []
for i, row in enumerate(table["plates"]):
path = f"plates[{i}]"
points, face = _row_points(row, path)
for s in ((side, -side) if row["sides"] == "both" else (side,)):
flip = np.array([float(s), 1.0, 1.0])
V, faces, facets = hull(_mirrored(points * flip, row["mirror"]), path)
face_n = None if face is None else face[3] * flip
clad, top = row["clad"], 0.0
panels = bolts = (np.zeros((0, 3)), [])
made = 0
if clad is not None:
seed = clad["seed"] if isinstance(clad["seed"], int) else clad["seed"][0 if s > 0 else 1]
panels, bolts, made, top = clad_layout(V, faces, facets, clad, seed, face_n, s)
anchors = []
for j, fit in enumerate(row["fits"]):
origin, a, b, n = face
at = (origin + a * fit["at"][0] + b * fit["at"][1] + n * (top + fit.get("lift", 0.0))) * flip
up = (0.0, 0.0, 1.0) if fit["kind"] == "mark" else b * flip
anchor = {"kind": fit["kind"], "name": fit.get("id", fit.get("name")), "matrix": _frame(at, face_n, up, f"{path}.fits[{j}]").tolist(), "mirrored": s < 0}
if fit["kind"] == "mark":
anchor["height"] = fit["height"]
anchors.append(anchor)
built.append({"name": row["name"] + ((".R" if s > 0 else ".L") if row["sides"] == "both" else ""), "row": i, "mat": row["mat"], "bevel": row["bevel"], "side": s,
"solid": (V, faces), "facets": facets, "panels": panels, "bolts": bolts, "anchors": anchors,
"report": {"corners": len(V), "facets": len(faces), "panels": made, "bolts": len(bolts[0]) // 12}})
return built

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -2267,7 +2267,7 @@ class OwnershipTests(unittest.TestCase):
return {p.name: p.read_text(encoding="utf-8") for p in sorted((SURFACE / "brokkr_kitbash").rglob("*")) if p.suffix in (".py", ".json")}
def test_no_pattern_matches(self):
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "ram.py", "route.py"])
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "frame.v0.json", "mechanical.v0.json", "plate.py", "ram.py", "route.py"])
for pattern in self.PACKAGE:
for name, text in self.sources().items():
if pattern is self.PACKAGE[2] and name == "__init__.py":
@ -2279,6 +2279,9 @@ class OwnershipTests(unittest.TestCase):
self.assertIn('modifier.solver = "MANIFOLD"', source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0])
self.assertIn('"COLLECTION", "EXACT", True', source.split("def operation_collection(")[1].split("\n\n\n")[0])
self.assertIsNone(re.search(self.CORE, self.sources()["core.py"], re.M))
# plate.py is core's kind: no Blender, no experiment module, and no random source but a seeded one
self.assertIsNone(re.search(self.CORE, self.sources()["plate.py"], re.M))
self.assertIsNone(re.search(r"Random\(\)|^\s*(import|from)\s+(massing|mechlib|surface|mathutils)", self.sources()["plate.py"], re.M))
schemas = [p for p in (SURFACE.parents[1] / "schemas").rglob("*") if p.is_file()]
self.assertTrue(schemas)
for path in schemas:

View file

@ -0,0 +1,484 @@
"""Hard plate tests. No Blender: brokkr_kitbash/plate.py against solids with known corners and against the three mech
tracks' own builders (fixtures/plates_*.json: each a table and the truth its branch's builder made in Blender 5.3).
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
The truth is float32 (mathutils and Blender meshes) and plate.py is float64; KNOWN lists every fixture plate where
that, a corner the branch's builder lost, or a tie Blender's mesh order decided keeps the two apart, with what is
asserted of it instead.
"""
from __future__ import annotations
import copy
import importlib
import inspect
import json
import math
import sys
import types
import unittest
from pathlib import Path
SURFACE = Path(__file__).resolve().parents[1]
FIXTURES = Path(__file__).resolve().parent / "fixtures"
try:
import numpy as np
except ImportError: # pragma: no cover
np = None
if np is not None:
package = types.ModuleType("brokkr_kitbash_plates") # the package's own __init__ wants bpy
package.__path__ = [str(SURFACE / "brokkr_kitbash")]
sys.modules["brokkr_kitbash_plates"] = package
plate = importlib.import_module("brokkr_kitbash_plates.plate")
BOX = [{"at": [1, 0, 0], "normal": [1, 0, 0]}, {"at": [-1, 0, 0], "normal": [-1, 0, 0]}, {"at": [0, 1, 0], "normal": [0, 1, 0]},
{"at": [0, -1, 0], "normal": [0, -1, 0]}, {"at": [0, 0, 1], "normal": [0, 0, 1]}, {"through": [[0, 0, -1], [1, 0, -1], [0, 1, -1]], "out": [0, 0, -1]}]
CLAD = {"mat": "olive_light", "min_area": 0.2, "lifts": [0.04, 0.07], "inset": 0.075, "gap": 0.045, "split": 0.8, "seed": 5}
SLAB = {"at": [0.5, 1.0, 0.0], "normal": [0.06, 1, 0.05], "outline": {"w": 0.8, "h": 1.2, "clip": 0.1}, "thick": 0.2}
def doc(*rows):
return {"schema": "brokkr.plates.v0", "plates": [copy.deepcopy(r) for r in rows]}
def row(name="p", **more):
out = {"name": name, "mat": "olive"}
out.update(copy.deepcopy(more))
if not any(k in out for k in ("faces", "slab", "sections", "points")):
out["faces"] = copy.deepcopy(BOX)
return out
def volume(mesh):
V, faces = mesh
return sum(float(np.dot(V[f[0]], np.cross(V[f[i]], V[f[i + 1]]))) for f in faces for i in range(1, len(f) - 1)) / 6
def apart(a, b):
"""How far two point sets stand from each other: the farthest any point of one is from the other's nearest."""
a, b = np.asarray(a, dtype=float).reshape(-1, 3), np.asarray(b, dtype=float).reshape(-1, 3)
if not len(a) or not len(b):
return 0.0 if len(a) == len(b) else math.inf
d = np.linalg.norm(a[:, None, :] - b[None, :, :], axis=2)
return float(max(d.min(axis=1).max(), d.min(axis=0).max()))
@unittest.skipIf(np is None, "numpy is not installed")
class CheckTests(unittest.TestCase):
def refused(self, document, path):
with self.assertRaises(plate.PlateError) as caught:
plate.check(document)
self.assertIn(path, str(caught.exception))
def test_defaults_are_written_in_and_check_takes_its_own_answer(self):
table = plate.check(doc(row(slab=SLAB, clad=CLAD)))
slab = table["plates"][0]["slab"]
self.assertEqual((slab["taper"], slab["back"], slab["gap"], slab["up"]), (0.04, 1.0, 0.0, [0.0, 0.0, 1.0]))
self.assertEqual((table["plates"][0]["sides"], table["plates"][0]["mirror"], table["plates"][0]["clad"]["facets"], table["plates"][0]["clad"]["bolt_r"]), ("one", False, "outer", 0.028))
self.assertEqual(plate.check(table), table)
def test_schema(self):
self.refused({"schema": "brokkr.plates.v1", "plates": [row()]}, "document.schema")
def test_unknown_key(self):
self.refused(doc(row(colour="red")), "plates[0].colour")
self.refused(doc(row(slab=dict(SLAB, depth=1))), "plates[0].slab.depth")
self.refused(doc(row(slab=SLAB, clad=dict(CLAD, lift=0.1))), "plates[0].clad.lift")
self.refused(dict(doc(row()), units="m"), "document.units")
def test_no_solid_form_and_two(self):
bare = {"name": "p", "mat": "olive"}
self.refused(doc(bare), "plates[0]: wants exactly one solid form")
self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]], faces=BOX)), "plates[0]: wants exactly one solid form")
def test_duplicate_name(self):
self.refused(doc(row("a"), row("a")), "plates[1].name")
self.refused(doc(row("a", sides="both"), row("a.L")), "plates[1].name")
def test_name(self):
self.refused(doc(row("a b")), "plates[0].name")
self.refused(doc(row("a" * 49)), "plates[0].name")
def test_non_finite_number(self):
self.refused(doc(row(slab=dict(SLAB, at=[0, math.nan, 0]))), "plates[0].slab.at[1]")
self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, math.inf]])), "plates[0].points[3][2]")
self.refused(doc(row(slab=dict(SLAB, thick=True))), "plates[0].slab.thick")
def test_outline_under_three_points(self):
self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0]]))), "plates[0].slab.outline")
def test_outline_of_sixty_five_points(self):
ring = [[math.cos(2 * math.pi * k / 65), math.sin(2 * math.pi * k / 65)] for k in range(65)]
self.refused(doc(row(slab=dict(SLAB, outline=ring))), "plates[0].slab.outline")
plate.check(doc(row(slab=dict(SLAB, outline=ring[:64]))))
def test_outline_crossing_itself(self):
self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [2, 2], [2, 0], [0, 1]]))), "plates[0].slab.outline: the outline crosses itself")
def test_outline_of_zero_area(self):
self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [2, 0]]))), "plates[0].slab.outline: the outline has zero area")
def test_slab_ranges(self):
for key, low, high in (("thick", 0.0005, 2.5), ("taper", -0.01, 0.6), ("back", 0.05, 1.6), ("gap", -0.01, 0.6)):
for value in (low, high):
self.refused(doc(row(slab=dict(SLAB, **{key: value}))), f"plates[0].slab.{key}")
def test_taper_half_the_least_width(self):
self.refused(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 0.2], [0, 0.2]], taper=0.1))), "plates[0].slab.taper")
plate.check(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 0.2], [0, 0.2]], taper=0.09))))
def test_corners_off_their_plane(self):
slab = {"corners": [[0, 0, 0], [1, 0, 0], [1, 1, 0.5], [0, 1, 0]], "inside": [0.5, 0.5, -1], "thick": 0.1}
self.refused(doc(row(slab=slab)), "plates[0].slab.corners")
plate.check(doc(row(slab=dict(slab, corners=[[0, 0, 0], [1, 0, 0], [1, 1, 0.1], [0, 1, 0]]))))
def test_faces_that_bound_nothing(self):
self.refused(doc(row(faces=BOX[:4])), "plates[0].faces")
self.refused(doc(row(faces=BOX[:5] + [{"at": [0, 0, 2], "normal": [0, 0, -1]}])), "plates[0].faces")
open_box = BOX[:5] + [{"at": [0, 0, -5000], "normal": [0, 0, -1]}]
self.refused(doc(row(faces=open_box)), "plates[0].faces")
def test_coplanar_points(self):
self.refused(doc(row(points=[[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0.3, 0.2, 0]])), "plates[0]: the points lie in one plane")
def test_seed_pair_on_a_one_sided_row(self):
self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=[1, 2]))), "plates[0].clad.seed")
plate.check(doc(row(slab=SLAB, sides="both", clad=dict(CLAD, seed=[1, 2]))))
def test_no_default_seed(self):
self.refused(doc(row(slab=SLAB, clad={k: v for k, v in CLAD.items() if k != "seed"})), "plates[0].clad.seed")
self.refused(doc(row(slab=SLAB, clad=dict(CLAD, seed=1.5))), "plates[0].clad.seed")
def test_up_along_the_normal(self):
self.refused(doc(row(slab=dict(SLAB, normal=[0, 0, 1]))), "plates[0].slab.normal")
plate.check(doc(row(slab=dict(SLAB, normal=[0, 0, 1], up=[0, 1, 0]))))
def test_unknown_fit_kind(self):
with self.assertRaises(plate.PlateError) as caught:
plate.check(doc(row(slab=SLAB, fits=[{"kind": "bolts", "at": [0, 0]}])))
self.assertIn("plates[0].fits[0].kind", str(caught.exception))
self.assertIn("mark, hose_port", str(caught.exception))
def test_duplicate_anchor_name(self):
fits = [{"kind": "mark", "id": "a", "at": [0, 0], "height": 0.3}, {"kind": "hose_port", "name": "a", "at": [0.1, 0]}]
self.refused(doc(row(slab=SLAB, fits=fits)), "plates[0].fits[1]")
def test_fit_without_a_face(self):
self.refused(doc(row(fits=[{"kind": "hose_port", "name": "a", "at": [0, 0]}])), "plates[0].fits[0]")
self.refused(doc(row(slab=SLAB, face={"at": [0, 0, 0], "normal": [0, 1, 0]})), "plates[0].face")
def test_outer_wants_a_face(self):
self.refused(doc(row(clad=dict(CLAD, facets="outer"))), "plates[0].clad.facets")
self.refused(doc(row(clad=CLAD)), "plates[0].clad.facets")
def test_rows(self):
self.refused({"schema": "brokkr.plates.v0", "plates": [row(f"p{k}") for k in range(257)]}, "plates: wants 1 to 256")
self.refused({"schema": "brokkr.plates.v0", "plates": []}, "plates: wants 1 to 256")
def test_side(self):
with self.assertRaises(plate.PlateError):
plate.build(doc(row()), 0)
@unittest.skipIf(np is None, "numpy is not installed")
class SolidTests(unittest.TestCase):
def test_a_cube_from_six_faces(self):
made = plate.build(doc(row()))[0]
self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 0, "bolts": 0})
self.assertEqual(sorted(map(tuple, np.round(made["solid"][0]).astype(int).tolist())), sorted((x, y, z) for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)))
self.assertAlmostEqual(volume(made["solid"]), 8.0, places=12)
def test_a_slab_has_a_flat_outer_face_and_its_taper_ring(self):
made = plate.build(doc(row(slab=dict(SLAB, back=0.9))))[0]
V, faces = made["solid"]
n = np.array(SLAB["normal"]) / np.linalg.norm(SLAB["normal"])
depth = np.round((V - np.array(SLAB["at"])) @ n, 9)
self.assertEqual(sorted(set(depth.tolist())), [-0.2, -0.04, 0.0])
self.assertEqual([int((depth == d).sum()) for d in (0.0, -0.04, -0.2)], [8, 8, 8])
outer = [f for f, facet in zip(faces, made["facets"]) if facet["normal"] @ n > 0.999]
self.assertEqual(len(outer), 1)
self.assertEqual(len(outer[0]), 8)
self.assertAlmostEqual(made["facets"][faces.index(outer[0])]["area"], (0.8 - 0.08) * (1.2 - 0.08) - 2 * (0.1 - 0.04 * (2 - math.sqrt(2))) ** 2, places=9)
ring, rear = V[depth == -0.04], V[depth == -0.2]
middle = ring.mean(axis=0) - n * 0.16
self.assertLess(apart(rear, middle + (ring - n * 0.16 - middle) * 0.9), 1e-12)
def test_an_outline_as_a_clipped_rectangle_is_its_eight_points(self):
ring = [[-0.3, 0.6], [0.3, 0.6], [0.4, 0.5], [0.4, -0.5], [0.3, -0.6], [-0.3, -0.6], [-0.4, -0.5], [-0.4, 0.5]]
a, b = plate.build(doc(row(slab=SLAB)))[0], plate.build(doc(row(slab=dict(SLAB, outline=ring[::-1]))))[0]
self.assertLess(apart(a["solid"][0], b["solid"][0]), 1e-12)
self.assertEqual(len(plate.build(doc(row(slab=dict(SLAB, outline={"w": 0.8, "h": 1.2, "clip": 0}))))[0]["solid"][0]), 12)
def test_a_gap_draws_the_outline_in(self):
wide, drawn = (plate.build(doc(row(slab=dict(SLAB, outline=[[0, 0], [1, 0], [1, 1], [0, 1]], taper=0.0, gap=g))))[0] for g in (0.0, 0.1))
self.assertAlmostEqual(wide["facets"][0]["area"], 1.0, places=12)
self.assertAlmostEqual(drawn["facets"][0]["area"], 0.64, places=12)
def test_a_corners_slab_stands_its_lift_off_coplanar_corners(self):
corners = [[1, 0, 0], [0, 1, 0], [0, 1, 1], [1, 0, 1]] # all on x + y = 1
made = plate.build(doc(row(slab={"corners": corners, "names": ["a", "b", "c", "d"], "inside": [0, 0, 0.5], "lift": 0.06, "thick": 0.1, "taper": 0.03})))[0]
n = np.array([1.0, 1.0, 0.0]) / math.sqrt(2)
off = np.round(made["solid"][0] @ n - 1 / math.sqrt(2), 12)
self.assertEqual(sorted(set(off.tolist())), [-0.04, 0.03, 0.06])
flipped = plate.build(doc(row(slab={"corners": corners, "inside": [2, 2, 0.5], "thick": 0.1, "taper": 0.03})))[0]
self.assertEqual(sorted(set(np.round(flipped["solid"][0] @ -n + 1 / math.sqrt(2), 12).tolist())), [-0.04, 0.03, 0.06])
def test_sections(self):
made = plate.build(doc(row(sections=[[0.4, 0.9, -0.3, 0.5, 0.12], [-1.8, 0.95, -0.3, 0.5, 0.14]])))[0]
self.assertEqual(made["report"]["corners"], 16)
self.assertEqual(made["report"]["facets"], 10)
self.assertEqual(sorted(set(np.round(made["solid"][0][:, 2], 12).tolist())), [-1.8, 0.4])
def test_mirror_is_one_solid_across_the_centre(self):
half = [[0.5, 0, 0], [0.5, 1, 0], [0.5, 0, 1], [0.5, 1, 1], [0, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 1]]
made = plate.build(doc(row(points=half, mirror=True)))[0]
self.assertEqual(made["report"]["corners"], 8)
self.assertAlmostEqual(volume(made["solid"]), 1.0, places=12)
self.assertEqual(sorted(set(made["solid"][0][:, 0].tolist())), [-0.5, 0.5])
def test_side_minus_one_is_the_mirror_and_both_sides_are_named(self):
right, left = plate.build(doc(row(slab=SLAB, sides="both")))
self.assertEqual((right["name"], right["side"], left["name"], left["side"]), ("p.R", 1, "p.L", -1))
self.assertLess(apart(right["solid"][0] * (-1, 1, 1), left["solid"][0]), 1e-12)
self.assertAlmostEqual(volume(left["solid"]), volume(right["solid"]), places=12)
self.assertEqual([e["name"] for e in plate.build(doc(row(slab=SLAB, sides="both")), -1)], ["p.L", "p.R"])
self.assertLess(apart(plate.build(doc(row(slab=SLAB)), -1)[0]["solid"][0], left["solid"][0]), 1e-12)
@unittest.skipIf(np is None, "numpy is not installed")
class HullTests(unittest.TestCase):
def roof(self, degrees):
"""A box whose top is two facets meeting on a ridge, their normals `degrees` apart."""
h = math.tan(math.radians(degrees / 2))
return [[x, y, 0] for x in (-1, 1) for y in (-1, 1)] + [[x, y, 1] for x in (-1, 1) for y in (-1, 1)] + [[0, -1, 1 + h], [0, 1, 1 + h]]
def test_facets_are_flat_closed_and_face_out(self):
for case in (row(), row(slab=SLAB), row(sections=[[0.4, 0.9, -0.3, 0.5, 0.12], [-1.8, 0.95, -0.3, 0.5, 0.14]])):
made = plate.build(doc(case))[0]
V, faces = made["solid"]
edges = {}
for face, facet in zip(faces, made["facets"]):
self.assertLess(float(np.abs((V[face] - V[face[0]]) @ facet["normal"]).max()), 1e-9)
self.assertGreater(float((facet["centre"] - V.mean(axis=0)) @ facet["normal"]), 0)
for a, b in zip(face, face[1:] + face[:1]):
edges[(a, b)] = edges.get((a, b), 0) + 1
self.assertTrue(all(count == 1 and edges.get((b, a)) == 1 for (a, b), count in edges.items()))
self.assertGreater(volume(made["solid"]), 0)
def test_facets_within_half_a_degree_are_one(self):
V, faces, facets = plate.hull(self.roof(0.4))
self.assertEqual((len(V), len(faces)), (8, 6)) # the ridge's ends turn 0.4 degrees on the gables: dropped
def test_facets_over_half_a_degree_stay_two(self):
V, faces, facets = plate.hull(self.roof(0.6))
self.assertEqual((len(V), len(faces)), (10, 7))
def test_a_vertex_on_a_straight_run_is_dropped(self):
V, faces, facets = plate.hull(self.roof(0.3))
self.assertEqual(sorted(len(f) for f in faces), [4] * 6)
def test_points_inside_and_on_edges_are_no_corners(self):
cube = [[x, y, z] for x in (0, 1) for y in (0, 1) for z in (0, 1)]
V, faces, facets = plate.hull(cube + [[0.5, 0.5, 0.5], [0.5, 0, 0], [0.5, 0.5, 0], [1, 1, 1]])
self.assertEqual((len(V), len(faces)), (8, 6))
def test_order_is_area_then_the_greater_centre(self):
V, faces, facets = plate.hull([[x, y, z] for x in (-1, 1) for y in (-2, 2) for z in (-3, 3)])
self.assertEqual([round(f["area"]) for f in facets], [24, 24, 12, 12, 8, 8])
self.assertEqual([f["normal"].round().astype(int).tolist() for f in facets], [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]])
self.assertTrue(all(tuple(V[face[0]]) == min(tuple(V[k]) for k in face) for face in faces))
@unittest.skipIf(np is None, "numpy is not installed")
class CladTests(unittest.TestCase):
def test_same_seed_same_bytes(self):
table = doc(row("a", slab=SLAB, clad=CLAD), row("b", clad=dict(CLAD, facets="all", seed=9)))
one, two = plate.build(table), plate.build(copy.deepcopy(table))
for a, b in zip(one, two):
for key in ("solid", "panels", "bolts"):
self.assertEqual(a[key][0].tobytes(), b[key][0].tobytes())
self.assertEqual(a[key][1], b[key][1])
self.assertEqual(json.dumps(a["anchors"]), json.dumps(b["anchors"]))
def test_seed_plus_one_changes_that_plate_and_no_other(self):
table = doc(row("a", clad=dict(CLAD, facets="all", seed=9)), row("b", clad=dict(CLAD, facets="all", seed=9)))
base = plate.build(table)
table["plates"][0]["clad"]["seed"] = 10
moved = plate.build(table)
self.assertNotEqual(base[0]["panels"][0].tobytes(), moved[0]["panels"][0].tobytes())
self.assertEqual(base[1]["panels"][0].tobytes(), moved[1]["panels"][0].tobytes())
self.assertEqual(base[0]["panels"][0].tobytes(), base[1]["panels"][0].tobytes())
def test_a_seed_pair_is_right_then_left(self):
pair = plate.build(doc(row(sides="both", clad=dict(CLAD, facets="all", seed=[9, 10]))))
nine, ten = (plate.build(doc(row(clad=dict(CLAD, facets="all", seed=s))), side)[0] for s, side in ((9, 1), (10, -1)))
self.assertEqual(pair[0]["panels"][0].tobytes(), nine["panels"][0].tobytes())
self.assertEqual(pair[1]["panels"][0].tobytes(), ten["panels"][0].tobytes())
self.assertNotEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all", seed=9))), -1)[0]["panels"][0].tobytes())
def test_a_split_facet_takes_two_panels_and_a_whole_one_a_panel(self):
made = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=2.2))))[0]
self.assertEqual(made["report"], {"corners": 8, "facets": 6, "panels": 2, "bolts": 8})
self.assertEqual((len(made["panels"][0]), len(made["bolts"][0])), (24, 96))
self.assertGreater(volume(made["panels"]), 0)
self.assertAlmostEqual(volume(made["bolts"]), 8 * 1.5 * math.sqrt(3) * 0.028 ** 2 * 0.6 * 0.028, places=12)
tops = sorted(set(np.round(made["panels"][0][:, 2] - 1, 9).tolist()))
self.assertEqual(tops, [-0.02, 0.02, 0.04, 0.05, 0.07]) # sunk 0.02; rims at lift less 0.02; lifts 0.04 and 0.07
whole = plate.build(doc(row(clad=dict(CLAD, facets=[{"n": [0, 0, 1], "cos": 0.9}], split=4.0))))[0]
self.assertEqual(whole["report"]["panels"], 1)
def test_outer_is_the_face_and_not_its_neighbour(self):
lean = math.radians(18) # the neighbour's normal is cos 0.951 on the face's
faces = BOX[:4] + [{"at": [0, 0, 1], "normal": [0, 0, 1]}, {"at": [0, 0, -1], "normal": [0, 0, -1]}, {"at": [0.2, 0, 1], "normal": [math.sin(lean), 0, math.cos(lean)]}]
made = plate.build(doc(row(faces=faces, face={"at": [0, 0, 1], "normal": [0, 0, 1], "up": [0, 1, 0]}, clad=dict(CLAD, facets="outer", min_area=0.5, split=99))))[0]
big = [f for f in made["facets"] if f["normal"][2] > 0.9]
self.assertEqual(len(big), 2)
self.assertTrue(all(f["area"] > 0.5 for f in big))
self.assertEqual(made["report"]["panels"], 1)
def test_selectors_and_the_floor(self):
count = lambda **clad: plate.build(doc(row(clad=dict(CLAD, split=99, **clad))))[0]["report"]["panels"] # noqa: E731
self.assertEqual(count(facets="all"), 6)
self.assertEqual(count(facets="all", floor=-0.35), 5)
self.assertEqual(count(facets=[{"n": [0, 0, 1], "cos": 0.6}]), 1)
self.assertEqual(count(facets=[{"radial": [0, 0, 1], "min_r": 0.5, "cos": 0.25}]), 4)
self.assertEqual(count(facets=[{"radial": [0, 0, 1], "min_r": 1.5, "cos": 0.25}]), 0)
self.assertEqual(count(facets=[{"n": [0, 0, 1], "cos": 0.6}, {"radial": [0, 0, 1], "min_r": 0.5, "cos": 0.25}]), 5)
self.assertEqual(count(facets="all", min_area=4.5), 0)
def test_a_selector_is_mirrored_with_the_side(self):
table = doc(row(clad=dict(CLAD, split=99, facets=[{"n": [1, 0, 0], "cos": 0.9}])))
right, left = plate.build(table, 1)[0], plate.build(table, -1)[0]
self.assertGreater(float(right["panels"][0][:, 0].min()), 0.9)
self.assertLess(float(left["panels"][0][:, 0].max()), -0.9)
def test_a_tied_longest_edge_goes_to_the_greater_middle(self):
made = plate.build(doc(row(points=[[x, y, z] for x in (-2, 2) for y in (-1, 1) for z in (0, 1)], clad=dict(CLAD, split=1.0, facets=[{"n": [0, 0, 1], "cos": 0.9}]))))[0]
self.assertEqual(plate._longest([np.array(p, dtype=float) for p in ([-2, -1, 1], [2, -1, 1], [2, 1, 1], [-2, 1, 1])]), 2)
self.assertEqual(made["report"]["panels"], 2)
@unittest.skipIf(np is None, "numpy is not installed")
class AnchorTests(unittest.TestCase):
FITS = [{"kind": "mark", "id": "07", "at": [0.1, -0.05], "height": 0.42}, {"kind": "hose_port", "name": "feed", "at": [-0.2, 0.3], "lift": 0.01}]
def test_frames_stand_on_the_face(self):
mark, port = plate.build(doc(row(slab=dict(SLAB, right=[1, 0, 0]), fits=self.FITS)))[0]["anchors"]
a, b, n = plate.plane_basis(SLAB["normal"], (0, 0, 1), (1, 0, 0))
self.assertGreater(a[0], 0)
m, p = np.array(mark["matrix"]), np.array(port["matrix"])
self.assertEqual((mark["kind"], mark["name"], mark["height"], mark["mirrored"]), ("mark", "07", 0.42, False))
self.assertEqual((port["kind"], port["name"], port["mirrored"], "height" in port), ("hose_port", "feed", False, False))
self.assertLess(float(np.abs(m[:3, 3] - (np.array(SLAB["at"]) + a * 0.1 - b * 0.05)).max()), 1e-12)
self.assertLess(float(np.abs(p[:3, 3] - (np.array(SLAB["at"]) - a * 0.2 + b * 0.3 + n * 0.01)).max()), 1e-12)
for frame in (m, p):
self.assertLess(float(np.abs(frame[:3, 2] - n).max()), 1e-12)
self.assertAlmostEqual(float(np.linalg.det(frame[:3, :3])), 1.0, places=12)
upright = np.array([0.0, 0.0, 1.0]) - n * n[2] # a mark's y is the table's +z off the normal
self.assertLess(float(np.abs(m[:3, 1] - upright / np.linalg.norm(upright)).max()), 1e-12)
self.assertGreater(float(m[2, 1]), 0.99)
self.assertLess(float(np.abs(p[:3, 1] - b).max()), 1e-12) # a port's y is the face's up
def test_right_handed_at_side_minus_one(self):
table = doc(row(slab=dict(SLAB, right=[1, 0, 0]), fits=self.FITS))
for right, left in zip(plate.build(table, 1)[0]["anchors"], plate.build(table, -1)[0]["anchors"]):
r, m = np.array(right["matrix"]), np.array(left["matrix"])
self.assertTrue(left["mirrored"])
self.assertAlmostEqual(float(np.linalg.det(m[:3, :3])), 1.0, places=12)
self.assertLess(float(np.abs(m[:3, 3] - r[:3, 3] * (-1, 1, 1)).max()), 1e-12)
self.assertLess(float(np.abs(m[:3, 2] - r[:3, 2] * (-1, 1, 1)).max()), 1e-12)
self.assertLess(float(np.abs(m[:3, 1] - r[:3, 1] * (-1, 1, 1)).max()), 1e-12)
def test_anchors_stand_on_the_clad_face(self):
bare = plate.build(doc(row(slab=SLAB, fits=self.FITS)))[0]["anchors"][0]
clad = plate.build(doc(row(slab=SLAB, fits=self.FITS, clad=dict(CLAD, lifts=[0.05, 0.05], split=99))))[0]["anchors"][0]
n = np.array(SLAB["normal"]) / np.linalg.norm(SLAB["normal"])
self.assertLess(float(np.abs(np.array(clad["matrix"])[:3, 3] - np.array(bare["matrix"])[:3, 3] - n * 0.05).max()), 1e-12)
def test_a_face_on_a_row_that_is_no_slab(self):
made = plate.build(doc(row(face={"at": [0, 1, 0], "normal": [0, 1, 0]}, fits=[self.FITS[1]])))[0]
self.assertLess(float(np.abs(np.array(made["anchors"][0]["matrix"])[:3, 3] - np.array([0.2, 1.01, 0.3])).max()), 1e-12)
@unittest.skipIf(np is None, "numpy is not installed")
class DeterminismTests(unittest.TestCase):
def test_the_table_and_the_side_are_the_only_inputs(self):
self.assertEqual(list(inspect.signature(plate.build).parameters), ["table", "side"])
self.assertEqual(list(inspect.signature(plate.check).parameters), ["document"])
def test_build_leaves_the_table_as_given(self):
table = doc(row(slab=SLAB, clad=CLAD))
kept = copy.deepcopy(table)
plate.build(table)
self.assertEqual(table, kept)
# Fixture plates the truth cannot be met on, each with what is asserted instead (cut hard-plate-core's report has the readings):
# float32 the branch solved the plate in float32 (mathutils); it stands up to 2e-6 m (solid) or 3e-5 m (panels) from the float64 solid
# corner the branch's massing.corners lost a true corner to its float32 inside test: its solid lacks one corner plate.py has
# tie two edges of the split facet are equally long and the branch's choice followed Blender's loop order, which differs
# between the two sides of this row; plate.py's rule (the greater middle) meets the other side's truth
KNOWN = {("bastion", "Hull.Cheek.R"): "float32", ("bastion", "Hull.Cheek.L"): "float32", ("bastion", "Hull.BellySide.L"): "float32",
("bastion", "Hull.Quarter.R"): "corner", ("bastion", "Hull.Quarter.L"): "corner", ("bastion", "Hull.BellySide.R"): "tie",
("raptor", "Torso.Jaw1.L"): "float32", ("raptor", "Torso.Cheek.R"): "float32", ("raptor", "Torso.Cheek.L"): "float32",
("raptor", "Torso.Belt3.R"): "float32", ("raptor", "Torso.Belt3.L"): "float32"}
SOLID, PANELS = 1e-6, 1e-5 # the cut's tolerances, metres
FLOAT32 = (4e-6, 4e-5) # for a KNOWN float32 plate: a few float32 steps at 8 m, and the same through an inset
@unittest.skipIf(np is None, "numpy is not installed")
class ParityTests(unittest.TestCase):
"""plate.build against each branch's own builder: solid vertices as a set, facet count, panel vertices as a set,
bolt count. Kills: the miter clamp 0.3 -> 0.5; the cut's share (0.36, 0.64) -> (0.3, 0.7); the lift-order coin
removed; a slab's gap ignored (raptor). The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands
between the two)."""
def parity(self, mech, plates):
fixture = json.loads((FIXTURES / f"plates_{mech}.json").read_text(encoding="utf-8"))
seen = 0
for case in fixture["cases"]:
built = {e["name"]: e for e in plate.build(fixture["table"], case["side"])}
for name, truth in case["truth"].items():
made, known = built[name], KNOWN.get((mech, name))
seen += 1
with self.subTest(plate=name, side=case["side"]):
solid, panels = apart(made["solid"][0], truth["solid"]), apart(made["panels"][0], truth["panels"])
if known == "corner":
V, T = made["solid"][0], np.array(truth["solid"])
d = np.linalg.norm(V[:, None, :] - T[None, :, :], axis=2)
self.assertLess(float(d.min(axis=0).max()), FLOAT32[0]) # every corner of the branch's is one of these
self.assertEqual(int((d.min(axis=1) > 1e-3).sum()), 1) # and one more, which the faces do bound
continue
self.assertEqual(made["report"]["facets"], truth["facets"])
self.assertEqual(made["report"]["bolts"], truth["bolts"])
self.assertEqual(len(made["panels"][0]), len(truth["panels"]))
self.assertLessEqual(solid, FLOAT32[0] if known == "float32" else SOLID)
if known == "tie":
self.assertGreater(panels, 0.1)
else:
self.assertLessEqual(panels, FLOAT32[1] if known == "float32" else PANELS)
self.assertEqual(seen, plates)
def test_bastion(self):
self.parity("bastion", 23)
def test_paladin(self):
self.parity("paladin", 53)
def test_raptor(self):
self.parity("raptor", 50)
def test_the_lost_corner_is_a_corner(self):
table = plate.check(json.loads((FIXTURES / "plates_bastion.json").read_text(encoding="utf-8"))["table"])
quarter = next(r for r in table["plates"] if r["name"] == "Hull.Quarter")
points, _ = plate._row_points(quarter, "plates")
planes = [(np.array(f["normal"]) / np.linalg.norm(f["normal"]), np.array(f["at"])) for f in quarter["faces"]]
slack = np.array([[float(n @ (p - at)) for n, at in planes] for p in points])
self.assertTrue((slack < 1e-9).all()) # every corner is inside every face
self.assertTrue(((np.abs(slack) < 1e-9).sum(axis=1) >= 3).all()) # and on three of them
if __name__ == "__main__":
unittest.main()