diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 8e8766f..93573f7 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -212,6 +212,8 @@ def _check_clad(clad: Any, row: dict, path: str) -> dict: 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]") + if seed[0] == seed[1]: + raise PlateError(f"{path}.seed: an equal pair draws two different layouts; write one seed for a mirrored pair") seed = list(seed) elif not whole(seed): raise PlateError(f"{path}.seed: wants an integer or [right, left]") @@ -337,18 +339,35 @@ def plane_basis(normal, up=(0.0, 0.0, 1.0), right=None, path: str = "plane"): 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.""" + """A convex counter-clockwise outline moved in by c on every edge; a sharp corner moves at most c / MITER. An + edge the move leaves running backwards (or no longer than TIE) is dropped, the shortest first, and its two + neighbours meet where their own lines moved in by c cross. Empty, shape (0, 2), when nothing is left: under + three edges, or two neighbours that never meet.""" ring = np.asarray(ring, dtype=np.float64) + count = len(ring) + ways = [(ring[(k + 1) % count] - ring[k]) / np.linalg.norm(ring[(k + 1) % count] - ring[k]) for k in range(count)] + lefts = [np.array([-e[1], e[0]]) for e in ways] 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 + for i in range(count): + n0 = lefts[i - 1] + miter = n0 + lefts[i] 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 + out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) + live, pts = list(range(count)), list(out) # pts[i] starts edge live[i] + while True: + m = len(live) + runs = [float((pts[(i + 1) % m] - pts[i]) @ ways[live[i]]) for i in range(m)] + i = min(range(m), key=runs.__getitem__) + if runs[i] > TIE: + return out if m == count else np.array(pts) + a, b = live[i - 1], live[(i + 1) % m] + cross = ways[a][0] * ways[b][1] - ways[a][1] * ways[b][0] + if m <= 3 or abs(cross) < 1e-12: + return np.zeros((0, 2)) + start = ring[b] + lefts[b] * c - ring[a] - lefts[a] * c + pts[(i + 1) % m] = ring[a] + lefts[a] * c + ways[a] * ((start[0] * ways[b][1] - start[1] * ways[b][0]) / cross) + del pts[i], live[i] def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray: @@ -666,10 +685,12 @@ def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[ 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.""" + """A block on a counter-clockwise outline, drawn depth along z, its far rim chamfered; the rim is the outline + itself where the chamfer leaves it fewer corners.""" 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) + rim = inset2d(outline, c) if c > 1e-6 else outline + rings = [(outline, 0.0), (outline, depth - c), (rim if len(rim) == n else outline, depth)] 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): @@ -688,7 +709,9 @@ def hex_bolt(mesh: _Mesh, origin, x, y, z, r: float, depth: float) -> None: 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.""" + SINK below, its far rim chamfered; a bolt inside each of its corners, 3.2 bolt_r in, none where that leaves no + ring, and bolts whose centres stand under 2 bolt_r apart made one at their middle. False for a polygon too small + for a panel, or one the inset leaves nothing of.""" pts = np.array(polygon) centre = pts.mean(axis=0) normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) @@ -703,7 +726,17 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra 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): + heads = list(inset2d(inner, 3.2 * bolt_r)) + k = 0 + while k < len(heads) > 1: # neighbours in ring order, the first pair first + after = (k + 1) % len(heads) + if np.linalg.norm(heads[after] - heads[k]) < 2 * bolt_r: + heads[k] = (heads[k] + heads[after]) / 2 + del heads[after] + k = 0 + else: + k += 1 + for q in heads: 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 diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1ff9134..c82223f 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -1039,7 +1039,7 @@ first. | `inset` | how far a panel stands in from its facet's edges | | `gap` | the seam between the two panels of a split facet | | `split` | a facet over this area is cut in two | -| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, also where the two are equal. | +| `seed` | an integer, or `[right, left]` on a row with `sides: "both"`. There is no default. One integer on a two-sided row makes a mirrored pair; a pair of seeds draws each side on its own solid, and an equal pair is refused: it would draw two different layouts, and one seed is how a row asks for the same on both sides. | | `bolt_r` | a bolt's corner radius (default 0.028) | | `bolt_mat` | the bolts' material, 1 to 63 characters (default `gunmetal`). Carried: `build` draws nothing from it; `brokkr_kitbash.plates` reads it | | `bevel` | the width of the panels' Bevel, 0 to 0.05 (default 0.012). Carried, as the row's `bevel` is | @@ -1047,16 +1047,19 @@ first. One `random.Random(seed)` draws, in facet order. A chosen facet over `split` is cut across its longest edge at a share drawn from 0.36 to 0.64 of that edge, the two parts `gap` apart; edges within 1e-9 m of the longest tie and go to the edge whose middle is greater by x, y, z. Then every chosen facet draws once: under 0.5 the parts take -`l0, l1`, otherwise `l1, l0`. A panel is its part moved in by `inset` (a sharp corner moves at most inset / 0.3), -refused under a quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift -above, its far rim chamfered 0.02. A hexagonal bolt of radius `bolt_r` stands inside each panel corner, 3.2 -`bolt_r` in. +`l0, l1`, otherwise `l1, l0`. A panel is its part moved in by `inset`, not made where that leaves nothing, under a +quarter of the part's area or under 0.02 m2; it is a prism from 0.02 below the facet to its lift above, its far +rim chamfered 0.02 (not chamfered where the chamfer would cost the rim a corner). A hexagonal bolt of radius +`bolt_r` stands inside each panel corner, on the panel's outline moved in 3.2 `bolt_r`: a panel with no room for +that ring has no bolts, and bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their middle +(neighbours in ring order, the first such pair first, until none is left). -The inset moves each corner along its own miter and does not look at its neighbours, so where it passes the two -ends of a short edge over each other the panel's outline crosses itself. `build` makes that panel as it stands; -Blender fills a face that crosses itself by where its loop starts, so the same vertices can render differently -from another builder's mesh. Two of the 104 fixture panels do it (bastion's `Hull.Cheek.R` and paladin's -`Thigh.Outer`), and the test names them. +One inset, `inset2d`, makes every such ring: a slab's `gap` and `taper`, a panel's outline, its rim and its bolt +ring. It moves each corner along its miter (a sharp corner at most the distance / 0.3). An edge that move leaves +running backwards, its two ends passed over each other, is dropped, the shortest first, and its two neighbours +meet where their own lines moved in cross; under three edges, or two neighbours that never meet, nothing is left +and the ring is empty. For a convex outline with no corner at the 0.3 limit that is exactly what stands the +distance inside every edge. A ring no edge of which runs backwards is the corner move alone, to the byte. ### Anchors @@ -1089,7 +1092,8 @@ Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates or two; a name built twice; a number that is not finite; an outline under 3 points or over 64, one that crosses itself, repeats a point or has zero area; `thick`, `taper`, `back` or `gap` outside 0.001 to 2, 0 to 0.5, 0.1 to 1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; corners that are not a plate; faces that -bound nothing; points in one plane; a pair of seeds on a one-sided row, or no seed; an `up` along the normal; a +bound nothing; points in one plane; a pair of seeds on a one-sided row, an equal pair, or no seed; an `up` along +the normal; a fit on a row with no face; an unknown fit kind; two anchors of one name in a row. ### Against the mech tracks' builders @@ -1104,7 +1108,17 @@ eight stand 1 to 2 micrometres (solid) or 29 micrometres (panels) from the float so the branch's solid is smaller than the table's and its panels are another solid's; and one of bastion's two belly-side plates splits its panel from the other of two equally long edges. Those three are held, solid, facets, panels and bolts, to `repaired` in `plates_bastion.json`: the branch's own builder run in Blender 5.3 with the -inside test at 1e-5 m, and with its clad cutting from the other tied edge. +inside test at 1e-5 m, and with its clad cutting from the other tied edge; `repaired.how` quotes both edits as +code. + +The branches' inset has no edge event, so 31 of the 126 are held to another bolt count, each named in the test's +`EVENT`: eleven stand bare (raptor's thin trims and paladin's tail have no room for a bolt ring), and the +others lose one to four to a ring with no room, a dropped edge or heads that would overlap. Two of them, bastion's `Hull.Cheek.R` +and paladin's `Thigh.Outer`, have a panel whose outline dropped a corner, and that panel's vertices are held to +no truth. What holds every ring instead: every `inset2d` call the three fixtures make at both sides (812) stands +inside its outline, and the 782 with no corner at the miter limit equal, within 1e-12 m, the outline's half-planes +moved in and clipped (37 of them an edge or more short, 22 empty); and no panel ring or bolt ring of any plate at +either side turns right or crosses, and no two bolt heads of a panel overlap. The same test builds the three fixtures to one sha256 of every coordinate rounded to 1e-9 m and every face, pinned from Starfire (Windows 11, numpy 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK). The diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index ad6c9ca..c3e3388 100644 --- a/surfaces/blender/tests/test_plate.py +++ b/surfaces/blender/tests/test_plate.py @@ -5,7 +5,7 @@ Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; 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 it -is held to instead. +is held to instead, and EVENT every one whose bolts or panel corners the inset's edge event changes. """ from __future__ import annotations @@ -18,7 +18,9 @@ import math import sys import types import unittest +import warnings from pathlib import Path +from unittest import mock SURFACE = Path(__file__).resolve().parents[1] FIXTURES = Path(__file__).resolve().parent / "fixtures" @@ -89,6 +91,137 @@ def rings(panels): at += 2 + 2 * n +def corner_move(ring, c): + """(ring, clamped): every corner moved along its miter by c, at most c / MITER, and whether any met that limit: + the inset before any edge is dropped.""" + ring = np.asarray(ring, dtype=np.float64) + out, clamped = np.empty_like(ring), False + 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) / np.linalg.norm(n0 + n1) + clamped = clamped or float(miter @ n0) < plate.MITER + out[i] = p1 + miter * (c / max(float(miter @ n0), plate.MITER)) + return out, clamped + + +def depths(points, ring): + """How far each point stands inside each edge's line of a counter-clockwise ring: (points, edges).""" + ring = np.asarray(ring, dtype=np.float64) + edges = np.roll(ring, -1, axis=0) - ring + lefts = np.column_stack((-edges[:, 1], edges[:, 0])) / np.linalg.norm(edges, axis=1)[:, None] + return np.einsum("pek,ek->pe", np.asarray(points, dtype=np.float64)[:, None, :] - ring[None, :, :], lefts) + + +def half_planes(ring, c): + """What is left of a convex counter-clockwise ring c inside every edge's line: a square around the ring clipped + by each edge's half-plane moved in by c. Empty, shape (0, 2), where nothing is.""" + ring = np.asarray(ring, dtype=np.float64) + (x0, y0), (x1, y1) = ring.min(axis=0) - 1, ring.max(axis=0) + 1 + poly = [np.array(p) for p in ((x0, y0), (x1, y0), (x1, y1), (x0, y1))] + for k in range(len(ring)): + edge = ring[(k + 1) % len(ring)] - ring[k] + left = np.array([-edge[1], edge[0]]) / np.linalg.norm(edge) + deep = [float((p - ring[k]) @ left) - c for p in poly] + kept = [] + for i, p in enumerate(poly): + j = (i + 1) % len(poly) + if deep[i] >= 0: + kept.append(p) + if (deep[i] > 0) != (deep[j] > 0) and deep[i] != deep[j]: + kept.append(p + (poly[j] - p) * (deep[i] / (deep[i] - deep[j]))) + poly = kept + if len(poly) < 3: + return np.zeros((0, 2)) + return np.array(poly) + + +def turns(ring): + """Each corner's turn (the cross product of the unit edges into and out of it): over 0 is a left turn.""" + ring = np.asarray(ring, dtype=np.float64) + edges = np.roll(ring, -1, axis=0) - ring + edges = edges / np.linalg.norm(edges, axis=1)[:, None] + before = np.roll(edges, 1, axis=0) + return before[:, 0] * edges[:, 1] - before[:, 1] * edges[:, 0] + + +def apart2(a, b): + """apart, for rings in a plane; an empty ring stands nowhere near one that is not.""" + return apart(np.column_stack((a, np.zeros(len(a)))), np.column_stack((b, np.zeros(len(b))))) + + +def sides(mech): + """Every row of a fixture as a one-sided row alone, at each side, with the seed build draws that side from: + (side, row name, table of that one row).""" + for one in fixture(mech)["table"]["plates"]: + for side in (1, -1): + alone = dict(one, sides="one") + if one.get("clad") and isinstance(one["clad"]["seed"], list): + alone["clad"] = dict(one["clad"], seed=one["clad"]["seed"][0 if side > 0 else 1]) + yield side, one["name"], {"schema": "brokkr.plates.v0", "plates": [alone]} + + +@unittest.skipIf(np is None, "numpy is not installed") +class InsetTests(unittest.TestCase): + """plate.inset2d, the one inset of every ring. Kills: the edge event removed; the vanish test at three edges + made two; the shortest-first pick made the first edge found (the clamped sliver alone: without a clamped corner + every order drops the same edges).""" + + def test_a_short_edge_is_dropped_and_its_neighbours_meet(self): + ring = [[0, 0], [4, 0], [4, 3], [2.1, 4], [1.9, 4]] # the top edge is 0.2 long + made = plate.inset2d(ring, 0.5) + self.assertEqual(len(made), 4) + self.assertLess(apart2(made, half_planes(ring, 0.5)), 1e-12) + self.assertGreater(float(depths(made, ring).min()), 0.5 - 1e-12) + self.assertEqual(len(plate.inset2d(ring, 0.05)), 5) + + def test_nothing_left_is_an_empty_ring(self): + cases = (([[0, 0], [3, 0], [3, 1], [0, 1]], 0.5), ([[0, 0], [3, 0], [3, 1], [0, 1]], 0.6), ([[0, 0], [4, 0], [0, 3]], 1.01), ([[0, 0], [1, 0], [1, 1], [0, 1]], 0.7), + ([[2, 0], [0, 1], [0, 0]], 0.5)) # its sharp corner is clamped: two edges are left that run forwards + with warnings.catch_warnings(): + warnings.simplefilter("error") # the long sides of the rectangle never meet + for ring, c in cases: + self.assertEqual(plate.inset2d(ring, c).shape, (0, 2)) + self.assertEqual(half_planes(ring, c + 1e-9).shape, (0, 2)) + self.assertEqual(len(plate.inset2d([[0, 0], [4, 0], [0, 3]], 0.99)), 3) # the triangle's inradius is 1 + + def test_a_ring_with_room_is_the_corner_move_to_the_byte(self): + hexagon = [[math.cos(k * math.pi / 3), math.sin(k * math.pi / 3)] for k in range(6)] + for ring, c in ((hexagon, 0.2), ([[0, 0], [4, 0], [4, 3], [2.1, 4], [1.9, 4]], 0.05), ([[0, 0], [5, 0], [0, 1]], 0.1)): + self.assertEqual(plate.inset2d(ring, c).tobytes(), corner_move(ring, c)[0].tobytes()) + self.assertTrue(corner_move([[0, 0], [5, 0], [0, 1]], 0.1)[1]) # its sharp corner is clamped + + def test_the_shortest_edge_goes_first(self): + sliver = [[11, 1], [12, 1], [6, 3], [4, 3], [6, 2]] # two corners clamped, three edges run backwards + made = plate.inset2d(sliver, 0.5) + self.assertLess(apart2(made, np.array([[6.516380, 2.300827], [5.918861, 2.5], [5.622082, 2.617078]])), 1e-6) + self.assertGreater(float(depths(made, sliver).min()), 0) + + def test_every_inset_of_the_fixtures_is_what_the_half_planes_leave(self): + inset, calls = plate.inset2d, [] + + def spy(ring, c): + calls.append((np.array(ring, dtype=np.float64), c, inset(ring, c))) + return calls[-1][2] + with mock.patch.object(plate, "inset2d", spy): + for mech in ("bastion", "paladin", "raptor"): + for side in (1, -1): + plate.build(fixture(mech)["table"], side) + held = dropped = empty = 0 + for ring, c, made in calls: + if float(turns(ring).min()) <= 0: # a slab's outline need not be convex: no edge of those runs backwards + self.assertEqual(made.tobytes(), corner_move(ring, c)[0].tobytes()) + continue + if len(made): + self.assertGreater(float(depths(made, ring).min()), 0) # clamped or not, it stands inside its outline + self.assertGreater(float(turns(made).min()), 0) + if not corner_move(ring, c)[1]: + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + held, dropped, empty = held + 1, dropped + (0 < len(made) < len(ring)), empty + (not len(made)) + self.assertEqual((len(calls), held, dropped, empty), (812, 782, 37, 22)) + + @unittest.skipIf(np is None, "numpy is not installed") class CheckTests(unittest.TestCase): def refused(self, document, path): @@ -187,6 +320,9 @@ class CheckTests(unittest.TestCase): 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_an_equal_seed_pair(self): + self.refused(doc(row(slab=SLAB, sides="both", clad=dict(CLAD, seed=[5, 5]))), "plates[0].clad.seed: an equal pair") + 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") @@ -376,10 +512,55 @@ class CladTests(unittest.TestCase): self.assertEqual(back[0]["panels"][0].tobytes(), left["panels"][0].tobytes()) self.assertEqual(back[1]["panels"][0].tobytes(), right["panels"][0].tobytes()) - def test_a_pair_of_seeds_draws_each_side_on_its_own_solid(self): - pair = plate.build(doc(row(sides="both", clad=dict(CLAD, facets="all", seed=[5, 5])))) - self.assertGreater(apart(across(pair[0]["panels"])[0], pair[1]["panels"][0]), 0.1) - self.assertEqual(pair[1]["panels"][0].tobytes(), plate.build(doc(row(clad=dict(CLAD, facets="all"))), -1)[0]["panels"][0].tobytes()) + def test_every_fixture_pair_row_on_one_seed_is_a_mirrored_pair(self): + pairs = mirrored = 0 + for mech in ("bastion", "paladin", "raptor"): + table = fixture(mech)["table"] + for one in table["plates"]: + if one.get("clad") and isinstance(one["clad"]["seed"], list): + one["clad"]["seed"] = one["clad"]["seed"][0] + pairs += 1 + built = plate.build(table) + for right, left in zip(built, built[1:]): + if right["name"].endswith(".R") and right["row"] == left["row"]: + mirrored += 1 + with self.subTest(plate=right["name"]): + self.assertEqual(left["report"], right["report"]) + for key in ("solid", "panels", "bolts"): + self.assertTrue(np.array_equal(across(right[key])[0], left[key][0])) + self.assertEqual(across(right[key])[1], left[key][1]) + self.assertEqual((pairs, mirrored), (23, 38)) # every two-sided row of the three, 23 of them rewritten + + def test_bolt_heads_too_close_are_one_at_their_middle(self): + strip = [np.array(p, dtype=float) for p in ([-0.5, -0.1, 0], [0.5, -0.1, 0], [0.5, 0.1, 0], [-0.5, 0.1, 0])] + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertTrue(plate.panel(panels, bolts, strip, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028)) + heads = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1) # the bolt ring is 0.8208 by 0.0208: its ends are 0.0208 apart + self.assertLess(apart(heads, [[-0.4104, 0, 0.0484], [0.4104, 0, 0.0484]]), 1e-12) + self.assertEqual(len(heads), 2) + wide = [p * (1, 1.5, 1) for p in strip] # 0.1208 apart: four bolts + bolts = plate._Mesh() + plate.panel(plate._Mesh(), bolts, wide, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028) + self.assertEqual(len(bolts.done()[0]) // 12, 4) + thin = [p * (1, 0.85, 1) for p in strip] # 0.17 wide: no bolt ring, a bare panel + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertTrue(plate.panel(panels, bolts, thin, np.array([0.0, 0.0, 1.0]), 0.04, 0.0, 0.028)) + self.assertEqual((len(panels.done()[0]), len(bolts.done()[0])), (12, 0)) + + def test_a_rim_the_chamfer_leaves_fewer_corners_is_the_outline(self): + mesh, axes = plate._Mesh(), np.eye(3) + plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0.502, 1.2], [0.498, 1.2], [0, 1]], dtype=float), 0.1, 0.02) + V = mesh.done()[0] + self.assertEqual(len(V), 18) + self.assertTrue(np.array_equal(V[12:, :2], V[:6, :2])) # the edge 0.004 long has no room for a chamfer of 0.02 + plate.prism(mesh, np.zeros(3), *axes, np.array([[0, 0], [1, 0], [1, 1], [0, 1]], dtype=float), 0.1, 0.02) + self.assertTrue(np.allclose(mesh.done()[0][26:, :2], [[0.02, 0.02], [0.98, 0.02], [0.98, 0.98], [0.02, 0.98]], atol=1e-12)) + + def test_no_panel_where_the_inset_leaves_nothing(self): + strip = [np.array(p, dtype=float) for p in ([-0.5, -0.1, 0], [0.5, -0.1, 0], [0.5, 0.1, 0], [-0.5, 0.1, 0])] + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertFalse(plate.panel(panels, bolts, strip, np.array([0.0, 0.0, 1.0]), 0.04, 0.1, 0.028)) + self.assertEqual((len(panels.verts), len(bolts.verts)), (0, 0)) 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] @@ -507,55 +688,72 @@ KNOWN = {("bastion", "Hull.Cheek.R"): "float32", ("bastion", "Hull.Cheek.L"): "f ("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 plate: a few float32 steps at 8 m, and the same through an inset -# Panels whose outline crosses itself: the inset passes the two ends of a short edge over each other, as the branches' own inset does. -# Blender fills such a cap by where its loop starts, and a facet's loop starts at plate.py's least vertex but at Blender's own in a -# branch's mesh: that is the whole of Hull.Cheek.R's difference in a render (109 pixels at 1024 from above, vertices 2e-6 m apart). -CROSSED = {("bastion", 1, "Hull.Cheek.R", 4), ("paladin", 1, "Thigh.Outer", 0)} # (mech, side, plate, panel) +# Fixture plates the inset's edge event changes from the branch's truth, which has no such event: (mech, side, plate) to (bolts, +# panel corners dropped). A bolt ring with no room is no bolts, an edge of it that ran backwards is one bolt less, and heads under two +# radii apart are one. Each is held to this bolt count in place of the truth's; one whose panel outline dropped a corner (three +# vertices, one in each ring of the prism) is held to that vertex count and to no panel vertex of the truth. A plate may be KNOWN too. +EVENT = {("bastion", 1, "Hull.Cheek.R"): (32, 1), ("bastion", 1, "Hull.Cheek.L"): (32, 0), ("bastion", 1, "Hull.Quarter.R"): (29, 0), + ("bastion", 1, "Hull.BellySide.R"): (10, 0), ("bastion", 1, "Hull.BellySide.L"): (10, 0), + ("paladin", 1, "Thigh.Outer"): (11, 1), ("paladin", 1, "Thigh.Inner"): (9, 0), ("paladin", 1, "Shin.Greave"): (11, 0), + ("paladin", 1, "Shin.Ankle"): (4, 0), ("paladin", 1, "Pelvis.Wing.R"): (3, 0), ("paladin", 1, "Pelvis.Wing.L"): (3, 0), + ("paladin", 1, "Pelvis.Tail"): (0, 0), ("paladin", -1, "Thigh.Outer"): (11, 0), ("paladin", -1, "Thigh.Inner"): (8, 0), + ("raptor", 1, "Torso.Jaw2.R"): (2, 0), ("raptor", 1, "Torso.Jaw2.L"): (2, 0), ("raptor", 1, "Torso.Jaw3.R"): (2, 0), + ("raptor", 1, "Torso.Jaw3.L"): (2, 0), ("raptor", 1, "Torso.JawLip2.R"): (0, 0), ("raptor", 1, "Torso.JawLip2.L"): (0, 0), + ("raptor", 1, "Torso.ShoulderDeck.R"): (3, 0), ("raptor", 1, "Torso.ShoulderDeck.L"): (3, 0), ("raptor", 1, "Torso.Belt1.R"): (0, 0), + ("raptor", 1, "Torso.Belt1.L"): (0, 0), ("raptor", 1, "Torso.Belt2.R"): (0, 0), ("raptor", 1, "Torso.Belt2.L"): (0, 0), + ("raptor", 1, "Torso.Lip2.R"): (0, 0), ("raptor", 1, "Torso.Lip2.L"): (0, 0), ("raptor", 1, "Torso.Hood1D.R"): (0, 0), + ("raptor", 1, "Torso.Hood1D.L"): (0, 0), ("raptor", 1, "Torso.Hood1F.R"): (7, 0)} # The three fixtures' builds as one sha256, of coordinates rounded to QUANTUM metres and of every face. Starfire (Windows 11, numpy -# 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK) give this hash; their coordinates differ in 3,221 of 34,359 by up -# to 2.7e-15 m and in no face. QUANTUM is TIE: 3.7e5 times that, and 1e3 under the least difference KNOWN holds (1.06e-6 m). +# 2.5.4) and Yggdrasil (Debian 13, numpy 2.2.4 on the system LAPACK) give this hash; their numbers (every coordinate and anchor matrix +# entry) differ in 2,821 of 30,909 by up to 2.7e-15 m and in no face. QUANTUM is TIE: 3.7e5 times that, and 1e3 under the least difference KNOWN holds (1.06e-6 m). QUANTUM = 1e-9 -HASH = "ff870b40db0baac928dd6462260e92e8c4e1ebb77f80adc15e1aff551fe41f0e" +HASH = "ee58f30a9492f1a7b0809b92bf46aa5fd01d1e06a6fa40edde15b2842f4afa1e" @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 + bolt count; a plate of EVENT to its bolt count there. Kills: an EVENT bolt count one off; 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 clad of Hull.Quarter left out; Hull.BellySide.R's panels moved 0.5 m. The outer test 0.97 -> 0.9 is CladTests' (no fixture facet stands between the two).""" - def held(self, made, truth, solid, panels): + def held(self, made, truth, solid, panels, event=None): + bolts, dropped = event or (truth["bolts"], 0) self.assertEqual(made["report"]["facets"], truth["facets"]) - self.assertEqual(made["report"]["bolts"], truth["bolts"]) - self.assertEqual(len(made["panels"][0]), len(truth["panels"])) + self.assertEqual(made["report"]["bolts"], bolts) + self.assertEqual(len(made["panels"][0]), len(truth["panels"]) - 3 * dropped) self.assertEqual(len(made["solid"][0]), len(truth["solid"])) self.assertLessEqual(apart(made["solid"][0], truth["solid"]), solid) - self.assertLessEqual(apart(made["panels"][0], truth["panels"]), panels) + if not dropped: + self.assertLessEqual(apart(made["panels"][0], truth["panels"]), panels) def parity(self, mech, plates): table, cases, repaired = fixture(mech)["table"], fixture(mech)["cases"], fixture(mech).get("repaired", {"truth": {}})["truth"] - seen = 0 + seen, events = 0, set() self.assertEqual(set(repaired), {name for (m, name), kind in KNOWN.items() if m == mech and kind != "float32"}) for case in cases: built = {e["name"]: e for e in plate.build(table, case["side"])} for name, truth in case["truth"].items(): - made, known = built[name], KNOWN.get((mech, name)) + made, known, event = built[name], KNOWN.get((mech, name)), EVENT.get((mech, case["side"], name)) seen += 1 + branch = repaired[name] if known == "corner" else truth + if made["report"]["bolts"] != branch["bolts"] or len(made["panels"][0]) != len(branch["panels"]): + events.add((mech, case["side"], name)) with self.subTest(plate=name, side=case["side"]): 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 - self.held(made, repaired[name], *FLOAT32) + self.held(made, repaired[name], *FLOAT32, event) elif known == "tie": self.assertGreater(apart(made["panels"][0], truth["panels"]), 0.1) # the branch cut from the other edge - self.held(made, dict(truth, panels=repaired[name]["panels"]), *FLOAT32) + self.held(made, dict(truth, panels=repaired[name]["panels"]), *FLOAT32, event) self.assertEqual({key: repaired[name][key] for key in ("solid", "facets", "bolts")}, {key: truth[key] for key in ("solid", "facets", "bolts")}) else: - self.held(made, truth, *(FLOAT32 if known == "float32" else (SOLID, PANELS))) + self.held(made, truth, *(FLOAT32 if known == "float32" else (SOLID, PANELS)), event) self.assertEqual(seen, plates) + self.assertEqual(events, {key for key in EVENT if key[0] == mech}) def test_bastion(self): self.parity("bastion", 23) @@ -575,14 +773,40 @@ class ParityTests(unittest.TestCase): 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 - def test_the_panels_whose_outline_crosses_itself(self): - crossed = set() - for mech in ("bastion", "paladin", "raptor"): - for case in fixture(mech)["cases"]: - for entry in plate.build(fixture(mech)["table"], case["side"]): - if entry["name"] in case["truth"]: - crossed |= {(mech, case["side"], entry["name"], k) for k, three in enumerate(rings(entry["panels"])) if any(plate._crosses(ring) for ring in three)} - self.assertEqual(crossed, CROSSED) + def test_no_ring_runs_backwards(self): + """Every panel of every fixture plate, at both sides: its three rings and its bolts' ring turn left at every + corner and do not cross, the rim's edges run the way the outline's do, and no two of its bolts' heads overlap. + Kills: the edge event removed (bastion's Hull.Cheek first); the merge of near heads removed.""" + prism, bolt, heads, panels = plate.prism, plate.hex_bolt, [], 0 + + def spy_prism(*args): + heads.append([]) + return prism(*args) + + def spy_bolt(mesh, origin, x, y, z, r, depth): + heads[-1].append((float(origin @ x), float(origin @ y), r)) + return bolt(mesh, origin, x, y, z, r, depth) + with mock.patch.object(plate, "prism", spy_prism), mock.patch.object(plate, "hex_bolt", spy_bolt): + for mech in ("bastion", "paladin", "raptor"): + for side, name, table in sides(mech): + del heads[:] + drawn = list(rings(plate.build(table, side)[0]["panels"])) + self.assertEqual(len(drawn), len(heads)) + for k, (three, ring) in enumerate(zip(drawn, heads)): + panels += 1 + with self.subTest(mech=mech, side=side, plate=name, panel=k): + for one in three: + self.assertGreater(float(turns(one).min()), 0) + self.assertFalse(plate._crosses(one)) + self.assertGreater(float(((np.roll(three[2], -1, axis=0) - three[2]) * (np.roll(three[0], -1, axis=0) - three[0])).sum(axis=1).min()), 0) + at = np.array([h[:2] for h in ring]).reshape(-1, 2) + if len(at) > 2: + self.assertGreater(float(turns(at).min()), 0) + self.assertFalse(plate._crosses(at)) + for i in range(len(at)): + for j in range(i): + self.assertGreaterEqual(float(np.linalg.norm(at[i] - at[j])), 2 * ring[0][2]) + self.assertEqual(panels, 128) if __name__ == "__main__":