diff --git a/surfaces/blender/brokkr_kitbash/plate.py b/surfaces/blender/brokkr_kitbash/plate.py index 8e8766f..be0150c 100644 --- a/surfaces/blender/brokkr_kitbash/plate.py +++ b/surfaces/blender/brokkr_kitbash/plate.py @@ -48,6 +48,8 @@ TIE = 1e-9 # areas (m2) and lengths (m) closer than this are equal: th 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 +REFLEX = 1e-6 # a corner turning right by more than this (radians) can reach an edge that is not its own +PARALLEL = 1e-9 # two edges whose normals cross by less than this (the sine) are parallel 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 @@ -59,6 +61,10 @@ class PlateError(ValueError): """The plate table breaks a rule of the format, or a row bounds no solid; the message names the path.""" +class NotSimple(PlateError): + """inset2d cannot keep the ring simple: moved in, a corner that turns right reaches an edge that is not its own.""" + + # --- reading the table ---------------------------------------------------------------------------------------------- def _number(value: Any, path: str, low: float | None = None, high: float | None = None) -> float: if not core.finite(value): @@ -212,6 +218,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 +345,94 @@ 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 counter-clockwise outline moved in by c on every edge, and it stands inside the outline. Each corner moves + along its miter, where its two edges' lines, moved in, cross. Where no edge runs out of length on the way (TIE) + those corners are the answer, a sharp one held to c / MITER from where it was unless that turns the ring the + other way at some corner. Otherwise the ring is followed in: the edge that runs out first is dropped where it + does and its neighbours meet there, then the next, the sharp corners standing where the lines cross; two edges + left facing each other on one line take the shorter away, two left on one line are one. Empty, shape (0, 2), + when nothing is left. A corner that turns right can reach an edge that is not its own before c: the ring would + meet itself there, and NotSimple names them; a slab's row adds its path. An outline with no right turn over + REFLEX never does.""" 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 + 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] + turn = lambda into, away: float(into[0] * away[1] - into[1] * away[0]) # noqa: E731 + move = lambda n0, n1: (n0 + n1) * (2.0 / max(float((n0 + n1) @ (n0 + n1)), 1e-24)) # noqa: E731 the miter over its cosine, with no 1 + cos lost to rounding at a sharp corner + met, out = np.empty_like(ring), np.empty_like(ring) + corners = [] # where a corner stood, at what inset, its move per metre, its turn + 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 + met[i] = ring[i] + miter * (c / max(float(miter @ n0), 1e-12)) + out[i] = ring[i] + miter * (c / max(float(miter @ n0), MITER)) + corners.append((ring[i], 0.0, move(n0, lefts[i]), math.atan2(turn(ways[i - 1], ways[i]), float(ways[i - 1] @ ways[i])))) + live = list(range(count)) # the edges left, in ring order: corner j stands where live[j - 1] meets live[j] + + def at(j: int, t: float) -> np.ndarray: + q, since, move, _ = corners[j % len(corners)] + return q + move * (t - since) + now = 0.0 + while len(live) > 2: + n = len(live) + first, when = None, math.inf + for j in range(n): # the edge that runs out first, of those with no length left at c + if float((at(j + 1, c) - at(j, c)) @ ways[live[j]]) > TIE: + continue + length, rate = float((at(j + 1, now) - at(j, now)) @ ways[live[j]]), float((corners[(j + 1) % n][2] - corners[j][2]) @ ways[live[j]]) + t = min(now + max(length, 0.0) / -rate, c) if rate < 0 else now + if t < when: + first, when = j, t + for j in range(n): # a corner turning right that reaches another edge before that + if corners[j][3] >= -REFLEX: + continue + for m in range(n): + if m in (j, (j - 1) % n): + continue + edge = live[m] + closing = 1.0 - float(lefts[edge] @ corners[j][2]) + ahead = float(lefts[edge] @ (at(j, now) - ring[edge])) - now + if closing <= 1e-12 or ahead < -TIE: + continue + t = now + max(ahead, 0.0) / closing + if t <= min(when - TIE, c + TIE) and float((at(j, t) - at(m, t)) @ ways[edge]) >= -TIE and float((at(m + 1, t) - at(j, t)) @ ways[edge]) >= -TIE: + raise NotSimple(f"moved in {c}, the outline meets itself: the corner of the edges from points {live[j - 1]} and {live[j]} reaches the edge from point {edge}") + if first is None: + break + now = when + q, angle = at(first, now), corners[first][3] + corners[(first + 1) % n][3] + del live[first], corners[first] + i = first % len(live) # the corner the dropped edge's two ends are now + while len(live) > 2: + n = len(live) + a, b = live[i - 1], live[i] + level = abs(turn(lefts[a], lefts[b])) <= PARALLEL + if not level and angle < math.pi: # a corner: it turns left by less than half a turn + corners[i] = (q, now, move(lefts[a], lefts[b]), angle) + break + if level and float(lefts[a] @ lefts[b]) > 0: # one line: the two edges are one edge, and no corner is between them + del live[i], corners[i] + break + span = float((q - at(i - 1, now)) @ ways[a]), float((at(i + 1, now) - q) @ ways[b]) # facing each other: the shorter is gone + if span[1] < span[0] - TIE: + q, angle = at(i + 1, now), angle + corners[(i + 1) % n][3] + else: + q, angle = at(i - 1, now), angle + corners[i - 1][3] + (corners[(i + 1) % n][3] if span[1] <= span[0] + TIE else 0.0) + i = (i - 1) % n + del live[i], corners[i] + i %= len(live) + if span[1] <= span[0] + TIE: + del live[i], corners[i] + i %= max(len(live), 1) + if len(live) == count: + held = np.array_equal(met, out) or all(turn(out[k] - out[k - 1], out[(k + 1) % count] - out[k]) * turn(ways[k - 1], ways[k]) >= 0 for k in range(count)) + return out if held else met + left = [at(j, c) for j in range(len(live))] if len(live) > 2 else [] + left = [p for k, p in enumerate(left) if np.linalg.norm(p - left[k - 1]) > TIE] + return np.array(left) if len(left) > 2 else np.zeros((0, 2)) def slab_points(origin, a, b, n, outline, thick: float, taper: float, back: float, gap: float) -> np.ndarray: @@ -442,13 +526,17 @@ def _row_points(row: dict, path: str): 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"]) + key = f"{at}.{'corners' if 'corners' in slab else 'outline'}" + _check_ring(ring, key) + try: + 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"]) + except NotSimple as error: + raise PlateError(f"{key}: {error}") from None face = (origin, a, b, n) elif "sections" in row: points = section_points(row["sections"]) @@ -665,11 +753,23 @@ def clip(poly: list[np.ndarray], point: np.ndarray, normal: np.ndarray) -> list[ return out +def _moved(outline: np.ndarray, c: float) -> np.ndarray: + """inset2d for a ring build makes of a facet: empty where the outline, moved in, would meet itself. No table row + draws such a ring, so there is none to refuse; a slab's outline is refused in _row_points, which check and build + both run.""" + try: + return inset2d(outline, c) + except NotSimple: + return np.zeros((0, 2)) + + 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 = _moved(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): @@ -687,8 +787,10 @@ 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.""" + """A raised panel on a flat polygon, a facet or a part of one: 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, 3.2 bolt_r in, + none where that leaves no ring, and any two 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 or cannot keep simple.""" pts = np.array(polygon) centre = pts.mean(axis=0) normal = np.cross(pts - centre, np.roll(pts, -1, axis=0) - centre).sum(axis=0) @@ -699,11 +801,23 @@ def panel(panels: _Mesh, bolts: _Mesh, polygon: list[np.ndarray], out: np.ndarra pts, normal = pts[::-1], -normal x, y = _stand(normal) flat = np.column_stack(((pts - centre) @ x, (pts - centre) @ y)) - inner = inset2d(flat, inset) + inner = _moved(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): + heads = list(_moved(inner, 3.2 * bolt_r)) + reach, k = 1, 0 + while reach <= len(heads) // 2: # the pair fewest corners apart round the ring first, of those the first + other = (k + reach) % len(heads) + if np.linalg.norm(heads[other] - heads[k]) < 2 * bolt_r: + heads[k] = (heads[k] + heads[other]) / 2 + del heads[other] + reach, k = 1, 0 + elif k + 1 < len(heads): + k += 1 + else: + reach, k = reach + 1, 0 + 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..e83da17 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,42 @@ 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 any two bolts whose centres would stand under 2 `bolt_r` apart are one bolt at their +middle, in the first one's place in the ring. Neighbours in ring order are read first, from the first corner, then +pairs one corner further apart round the ring, and after each joining the reading starts again; so no two bolt +heads of a panel overlap, neighbours or not. -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. What it returns stands inside the outline. It moves each corner along its miter, where its two edges' +lines, moved in, cross. Where no edge runs out of length on the way, those corners are the ring, a sharp one held +to the distance / 0.3 from where it was (unless that would turn the ring the other way at some corner): the +corner move alone, to the byte. Otherwise the ring is followed in, as a straight skeleton's front is: the edge +that runs out first is dropped where it does and its two neighbours meet there, then the next, and the sharp +corners stand where the lines cross. Two edges left facing each other on one line (a tab's sides when its end has +run out) take the shorter away, both when they are equal, and two left on one line are one edge. Where nothing is +left the ring is empty. For a convex outline that is what its edges' half-planes, each moved in, leave of it. + +A held corner steps. While no edge has run out, a corner sharper than 35 degrees (the sine of its half angle +under 0.3) stands distance / 0.3 along its miter; from the distance where the ring first loses an edge it stands +where its lines cross, distance / that sine along the same miter. The step is their difference and no more: on a +10.5 degree tip that loses its first edge at 0.109, from 0.36 to 1.19 m from the outline's corner. It is the +skeleton's own corner the step lands on, and it is inside the outline before and after; a facet near that +distance changes its panel by the step for a small change of `inset`. + +An outline need not be convex: a slab's may be drawn so, and facets within 0.5 degrees of each other are one +facet whose outline can turn right. Its corners that turn right move in too, faster the sharper they are (the +distance / the sine of half the corner), and such a corner can reach an edge that is not its own: a neck between +two parallel edges closes at half its width. From there the ring would meet itself and be two rings or none, and +`inset2d` refuses it (`NotSimple`, a `PlateError`), naming the corner's two edges and the edge it reaches. For a +slab's `gap` or `taper` that is the row's refusal at `slab.outline` (or `slab.corners`), from `check` and from +`build` in the same words, since both make the slab's points the same way. A facet is no row's drawing: where +the inset of a facet or of a facet's part would meet itself, that part takes no panel; where the bolt ring of a +panel would, the panel takes no bolts; where the rim would, the rim is the outline. So `build` refuses nothing +that `check` passed. ### Anchors @@ -1088,8 +1114,10 @@ Every refusal is a `PlateError` (a `ValueError`) that names the path, as `plates `plates[0].clad.seed`: a schema that is not `brokkr.plates.v0`; an unknown key anywhere; a row with no solid form 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 +1.5 and 0 to 0.5; a `taper` of half the outline's least width or more; a `gap` or `taper` at which an outline +that is not convex would meet itself; corners that are not a plate; faces that +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 +1132,28 @@ 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. The 6 on a slab outline that is not convex are the corner move, every corner the distance +clear of every edge; 24 hold a sharp corner at the 0.3 limit with every edge running forwards; the other 782 +equal, within 1e-12 m, the outline's half-planes moved in and clipped by the test's own clipper (37 of them an +edge or more short, 22 empty). 3,000 drawn convex rings are held the same way, and every bolt of 104 blade plates +(tips of 14 to 32 degrees) stands whole on its plate. 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; nor do any two on 3,591 blade plates (tips of 8 to 44 +degrees), 50 of which kept such a pair while only neighbours were joined. + +No fixture facet turns right, so 1,500 drawn sheets hold that case: 5 to 9 points up to 12 mm off one plane, whose +top facets the hull makes one. Each passes `check` and builds. Of their 519 rings that turn right, 84 lose an +edge, and each of those stands inside its outline without crossing, the distance clear of every edge, each of its +edges along one of the outline's in the outline's order; 2, both bolt rings, would meet themselves, and their +panels stand bare. A two-lobed facet with a neck holds the rest: no panel at an inset over half the neck, a bare +panel under it, and a prism whose rim would meet itself keeps its outline for a rim. 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/fixtures/plates_bastion.json b/surfaces/blender/tests/fixtures/plates_bastion.json index f57150a..77308d7 100644 --- a/surfaces/blender/tests/fixtures/plates_bastion.json +++ b/surfaces/blender/tests/fixtures/plates_bastion.json @@ -43,7 +43,7 @@ "Hull.BellySide.L": {"solid":[[-2.0999999,2.2,3.9000001],[-2.0999999,-2.4000001,3.95],[-2.45,2.0,4.0999999],[-2.45,-2.2,4.1500001],[-2.45,2.0,4.8499999],[-2.45,-2.2,4.9000001],[-2.25,2.2,5.0999999],[-2.25,-2.4000001,5.1500001],[-1.8,2.2,3.9000001],[-1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[-2.4300001,-2.0900002,4.2586985],[-2.4300001,-2.0900002,4.7886829],[-2.4300001,0.1687398,4.7617931],[-2.4300001,0.1624316,4.2318835],[-2.5050001,-2.0900002,4.2586985],[-2.5050001,-2.0900002,4.7886829],[-2.5050001,0.1687398,4.7617931],[-2.5050001,0.1624316,4.2318835],[-2.5250001,-2.0700002,4.2784615],[-2.5250001,-2.0700002,4.7684431],[-2.5250001,0.1485032,4.7420325],[-2.5250001,0.1426711,4.2521205],[-2.4300001,0.4387209,4.7585793],[-2.4300001,1.89,4.7413015],[-2.4300001,1.89,4.2113171],[-2.4300001,0.4324124,4.2286692],[-2.4750001,0.4387209,4.7585793],[-2.4750001,1.89,4.7413015],[-2.4750001,1.89,4.2113171],[-2.4750001,0.4324124,4.2286692],[-2.4950001,0.4584814,4.7383423],[-2.4950001,1.87,4.7215385],[-2.4950001,1.87,4.2315569],[-2.4950001,0.4526491,4.2484298],[-2.2321301,1.8335732,5.0840106],[-2.1400001,-2.2902241,5.1287899],[-1.9212852,-2.2902241,5.1287899],[-2.2321301,1.8340623,5.1290078],[-2.1400001,-2.2897351,5.1737871],[-1.9212852,-2.2897351,5.1737871],[-2.2288792,1.7676963,5.1497297],[-2.1204419,-2.2695189,5.1935692],[-1.9428494,-2.2695189,5.1935692]],"bolts":11} }} ], - "repaired": {"how": {"corner": "the branch's builder with massing.corners' inside test at 1e-5 m in place of 1e-6: the corner float32 lost is kept", "tie": "the branch's massing.clad cutting from the other of the split facet's two equally long edges"}, "truth": { + "repaired": {"how": {"script": "Blender 5.3 in the background at source.sha, with surfaces/blender/experiments/mechs on sys.path: import mechlib, massing, bastion_body, bastion_form. For a plate of bastion_form.PLATES built as key at side sx (1 for .R, -1 for .L): obj = massing.hard(key, pts, None, plate[\"mat\"], mirror=plate.get(\"mirror\", False), bevel=plate[\"bevel\"], sx=sx); g, bolts = mechlib.Geo(), mechlib.Geo(); clad(obj, g, keep=bastion_body.outward, seed=seed, bolts=bolts), seed the table's clad.seed for that side. solid is obj.data.vertices, facets len(obj.data.polygons), panels g.bm.verts, bolts len(bolts.bm.verts) // 12, coordinates rounded to 7 places.", "corner": "Hull.Quarter.R and .L: pts = massing.corners([bastion_body._face(f) for f in plate[\"faces\"]], tol=1e-5) where the branch calls it at its default, tol=1e-6 (the slack of its inside test, all(n.dot(p) <= d + tol ...)): the corner float32 lost is kept. clad is massing.clad.", "tie": "Hull.BellySide.R: pts = bastion_body._points(plate), and clad is massing.clad with two lines added after its line `k = max(range(len(pts)), key=lambda i: (pts[(i + 1) % len(pts)] - pts[i]).length)`: `tied = [i for i in range(len(pts)) if abs((pts[(i + 1) % len(pts)] - pts[i]).length - (pts[(k + 1) % len(pts)] - pts[k]).length) < 1e-5]` and `k = next((i for i in tied if i != k), k) if len(tied) == 2 else k`: the cut starts from the other of the split facet's two equally long edges."}, "truth": { "Hull.Quarter.R": {"solid":[[4.2910318,-2.9193861,6.8925695],[4.7526722,-3.0549133,5.7045879],[4.3936944,-1.4,7.0157642],[4.9976001,-1.4,5.506],[3.5958304,-4.3421259,6.9449539],[3.9363332,-4.6085348,5.8910241],[1.75,-4.8604336,7.409956],[1.75,-5.3931999,5.9851837],[2.5643883,-1.4,7.5279703],[1.75,-2.3254409,7.6634545],[2.5643883,-1.4,5.5060005],[1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[2.6039631,-1.5075765,7.4852662],[1.8505968,-2.3636744,7.6105995],[1.8505968,-3.7839808,7.4685688],[3.7708514,-3.7307458,6.9362202],[4.181469,-2.8904121,6.9052806],[4.2749047,-1.5075765,7.0174022],[2.6160405,-1.5118898,7.5284004],[1.8626742,-2.3679876,7.6537333],[1.8626742,-3.7882941,7.5117025],[3.7829289,-3.7350593,6.9793544],[4.1935463,-2.8947253,6.9484148],[4.2869821,-1.5118899,7.0605364],[2.6295795,-1.5337148,7.543292],[1.8873084,-2.3772049,7.6667795],[1.8873082,-3.7697763,7.5275221],[3.7765129,-3.7174025,7.0037818],[4.1799693,-2.8917232,6.9733815],[4.2717276,-1.5337149,7.0834904],[1.8505965,-4.0526409,7.4417028],[1.8505965,-4.7160707,7.37536],[3.5181954,-4.2478104,6.9552579],[3.6377716,-4.0030956,6.9462481],[1.8707256,-4.0598297,7.5135922],[1.8707258,-4.7232594,7.4472499],[3.5383244,-4.2549992,7.0271478],[3.6579008,-4.0102844,7.0181379],[1.8953596,-4.0811133,7.5254316],[1.8953596,-4.6992774,7.4636159],[3.5305526,-4.2401166,7.0516772],[3.6317692,-4.0329757,7.0440507],[2.7647738,-4.5948009,7.0421376],[1.8471562,-4.8524671,7.273304],[1.8471562,-5.2996264,6.0774708],[2.8457143,-4.9412479,6.0344653],[2.7796867,-4.6345687,7.0570083],[1.862069,-4.8922348,7.2881742],[1.8620691,-5.3393941,6.0923409],[2.8606274,-4.9810157,6.049336],[2.7687323,-4.6642437,7.0491562],[1.8875668,-4.9116745,7.2711391],[1.8875669,-5.3432689,6.1169314],[2.8469315,-4.9989567,6.075614],[3.5113626,-4.385159,6.8540578],[3.0230417,-4.5222793,6.9770751],[3.0996346,-4.8501167,6.0235305],[3.7892847,-4.6026044,5.9938288],[3.5362175,-4.4514389,6.8788414],[3.0478966,-4.5885587,7.0018592],[3.1244895,-4.9163966,6.0483146],[3.8141394,-4.6688843,6.0186129],[3.5286927,-4.4801512,6.8701258],[3.0752041,-4.6074901,6.9843683],[3.1484115,-4.9208369,6.0729723],[3.7952363,-4.688694,6.0451155],[4.3817148,-1.9071758,6.8648353],[4.3201332,-2.8185694,6.7909379],[4.710516,-2.9331768,5.7863297],[4.8316121,-2.1149623,5.6881447],[4.4233174,-1.9113361,6.8814764],[4.3617358,-2.8227296,6.8075786],[4.7521186,-2.9373369,5.8029709],[4.8732147,-2.1191227,5.7047858],[4.4476438,-1.9368703,6.8683591],[4.3888788,-2.8065846,6.7978411],[4.7663054,-2.9173882,5.8265738],[4.8817496,-2.1373634,5.7329712],[4.9214897,-1.5076798,5.6152711],[4.4087076,-1.5076798,6.8972268],[4.400281,-1.6323925,6.887115],[4.8708658,-1.8497338,5.6563177],[4.9908276,-1.5146136,5.6430063],[4.478045,-1.5146136,6.924962],[4.4696183,-1.6393265,6.9148502],[4.9402032,-1.8566676,5.6840525],[4.9988408,-1.536377,5.6716146],[4.5026264,-1.5363771,6.9121504],[4.4966955,-1.6241521,6.9050336],[4.9545536,-1.8356153,5.7075229],[4.2655559,-3.0223532,6.786387],[3.6602807,-4.2610564,6.8319945],[3.9375505,-4.4779921,5.9737864],[4.6440229,-3.1334624,5.8124413],[4.3285189,-3.0520933,6.8142467],[3.723244,-4.2907968,6.8598547],[4.0005136,-4.5077324,6.001646],[4.706986,-3.1632028,5.840301],[4.34373,-3.0801873,6.8037205],[3.7548051,-4.28543,6.8480964],[4.0205779,-4.4933701,6.0254736],[4.7070746,-3.186857,5.868691]],"bolts":30}, "Hull.Quarter.L": {"solid":[[-4.2910318,-2.9193861,6.8925695],[-4.7526722,-3.0549133,5.7045879],[-4.3936944,-1.4,7.0157642],[-4.9976001,-1.4,5.506],[-3.5958304,-4.3421259,6.9449539],[-3.9363332,-4.6085348,5.8910241],[-1.75,-4.8604336,7.409956],[-1.75,-5.3931999,5.9851837],[-2.5643883,-1.4,7.5279703],[-1.75,-2.3254409,7.6634545],[-2.5643883,-1.4,5.5060005],[-1.75,-2.3254409,5.6170526]],"facets":8,"panels":[[-1.8505965,-4.7160707,7.3753595],[-1.8505963,-4.0014849,7.4468179],[-3.6631114,-3.9512372,6.9443383],[-3.5181952,-4.2478104,6.9552579],[-1.8707256,-4.7232594,7.4472494],[-1.8707255,-4.0086741,7.5187078],[-3.6832407,-3.9584262,7.0162282],[-3.5383244,-4.2549992,7.0271473],[-1.8953596,-4.6992774,7.4636154],[-1.8953595,-4.0299578,7.5305471],[-3.6571088,-3.9811172,7.042141],[-3.5305526,-4.2401166,7.0516772],[-1.8505961,-3.7328248,7.4736838],[-1.8505962,-2.3636742,7.6105995],[-2.6039624,-1.5075763,7.4852662],[-4.2749043,-1.5075763,7.0174017],[-4.1814685,-2.8904119,6.9052796],[-3.7961907,-3.6788878,6.93431],[-1.8626735,-3.7371383,7.5168176],[-1.8626738,-2.3679876,7.6537333],[-2.61604,-1.5118898,7.5283999],[-4.2869816,-1.5118897,7.0605354],[-4.1935458,-2.8947253,6.9484134],[-3.8082683,-3.6832011,6.9774437],[-1.8873075,-3.7186203,7.5326371],[-1.8873078,-2.3772047,7.666779],[-2.6295791,-1.5337147,7.543292],[-4.2717271,-1.5337147,7.0834894],[-4.1799688,-2.8917229,6.9733806],[-3.8018522,-3.6655443,7.0018711],[-3.5113626,-4.385159,6.8540568],[-3.7892847,-4.6026049,5.9938283],[-2.8620911,-4.9353704,6.0337601],[-2.7814307,-4.5901232,7.0379415],[-3.5362175,-4.4514389,6.8788409],[-3.8141396,-4.6688843,6.0186124],[-2.8869457,-5.0016503,6.0585442],[-2.8062856,-4.6564031,7.0627251],[-3.5286927,-4.4801512,6.8701248],[-3.7952363,-4.6886945,6.0451145],[-2.9108679,-5.0060902,6.0832024],[-2.8335931,-4.6753345,7.0452342],[-2.6081707,-5.0265012,6.0446959],[-1.8471559,-5.2996264,6.0774708],[-1.8471559,-4.8524671,7.273304],[-2.5231626,-4.6626449,7.103004],[-2.6230836,-5.0662689,6.059566],[-1.8620688,-5.3393941,6.0923409],[-1.8620689,-4.8922348,7.2881746],[-2.5380757,-4.7024126,7.1178746],[-2.6093876,-5.0842099,6.0858445],[-1.8875666,-5.3432684,6.1169314],[-1.8875667,-4.9116745,7.2711396],[-2.5271213,-4.7320881,7.1100225],[-4.3919301,-1.7559885,6.8770943],[-4.4087081,-1.5076798,6.8972273],[-4.9214902,-1.5076798,5.615272],[-4.85321,-1.969032,5.6706338],[-4.4335327,-1.7601488,6.8937349],[-4.4503107,-1.5118401,6.9138684],[-4.9630928,-1.5118401,5.6319127],[-4.8948126,-1.9731923,5.6872749],[-4.4606104,-1.7449744,6.8839188],[-4.4748921,-1.5336035,6.9010572],[-4.9711065,-1.5336035,5.660521],[-4.909163,-1.95214,5.7107453],[-4.3201332,-2.8185692,6.7909379],[-4.373363,-2.0307715,6.8548145],[-4.8139558,-2.2342606,5.7024608],[-4.7105155,-2.9331768,5.7863297],[-4.3894706,-2.8255031,6.8186731],[-4.4427004,-2.0377054,6.8825493],[-4.8832932,-2.2411945,5.7301955],[-4.7798533,-2.9401107,5.814065],[-4.4166136,-2.8093579,6.8089352],[-4.4670272,-2.0632396,6.869432],[-4.8918281,-2.2594352,5.7583814],[-4.7940402,-2.920162,5.8376679],[-3.9375505,-4.4779921,5.9737859],[-3.6602805,-4.2610569,6.8319945],[-4.2655559,-3.0223532,6.7863865],[-4.6440229,-3.1334624,5.8124409],[-4.0005136,-4.5077324,6.0016456],[-3.7232437,-4.2907968,6.8598542],[-4.3285189,-3.0520935,6.8142462],[-4.706986,-3.1632028,5.8403006],[-4.0205779,-4.4933701,6.0254736],[-3.7548048,-4.28543,6.8480964],[-4.34373,-3.0801876,6.8037205],[-4.7070746,-3.1868572,5.8686905]],"bolts":30}, "Hull.BellySide.R": {"solid":[[2.0999999,2.2,3.9000001],[2.0999999,-2.4000001,3.95],[2.45,2.0,4.0999999],[2.45,-2.2,4.1500001],[2.45,2.0,4.8499999],[2.45,-2.2,4.9000001],[2.25,2.2,5.0999999],[2.25,-2.4000001,5.1500001],[1.8,2.2,3.9000001],[1.8,-2.4000001,5.1500001]],"facets":15,"panels":[[2.4300001,0.4573603,4.2283726],[2.4300001,1.89,4.2113171],[2.4300001,1.89,4.7413015],[2.4300001,0.4636687,4.7582817],[2.5050001,0.4573603,4.2283726],[2.5050001,1.89,4.2113171],[2.5050001,1.89,4.7413015],[2.5050001,0.4636687,4.7582817],[2.5250001,0.4775969,4.2481332],[2.5250001,1.87,4.2315569],[2.5250001,1.87,4.7215385],[2.5250001,0.4834292,4.7380452],[2.4300001,-2.0900002,4.7886829],[2.4300001,-2.0900002,4.2586985],[2.4300001,0.1873795,4.2315865],[2.4300001,0.193688,4.7614961],[2.4750001,-2.0900002,4.7886829],[2.4750001,-2.0900002,4.2586985],[2.4750001,0.1873795,4.2315865],[2.4750001,0.193688,4.7614961],[2.4950001,-2.0700002,4.7684431],[2.4950001,-2.0700002,4.2784615],[2.4950001,0.167619,4.2518234],[2.4950001,0.1734514,4.7417355],[2.2321301,1.8335732,5.0840106],[1.9212853,-2.2902241,5.1287899],[2.1400001,-2.2902241,5.1287899],[2.2321301,1.8343884,5.1590061],[1.9212853,-2.2894089,5.2037854],[2.1400001,-2.2894089,5.2037854],[2.2288792,1.7680224,5.179728],[1.9428494,-2.2691927,5.223567],[2.1204419,-2.2691927,5.223567]],"bolts":11} diff --git a/surfaces/blender/tests/live/kitbash_plates.py b/surfaces/blender/tests/live/kitbash_plates.py index fe3b326..8463e73 100644 --- a/surfaces/blender/tests/live/kitbash_plates.py +++ b/surfaces/blender/tests/live/kitbash_plates.py @@ -275,14 +275,14 @@ try: check("plates on the thigh are accepted and none is a rebuild", receipt["status"] == "accepted" and [row["rebuilt"] for row in report["plates"]] == [False], [receipt["status"], receipt["message"]]) R["reports"]["thigh"] = report bpy.context.view_layer.update() - proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report) + _, thigh_built = proven("a plate on the thigh, the frame the host's", THIGH, 1, "Thigh.", thigh, world(thigh), report) receipt, report = send("brokkr_kitbash.plates", host="Shin", prefix="Shin.", table=json.dumps(SHIN)) bpy.context.view_layer.update() shin_table, shin_built = proven("a plate on the shin, under the pin", SHIN, 1, "Shin.", shin, world(shin), report) guard = bpy.data.objects["Thigh.Guard"] check("a plate with a panel and its bolts has two fit children and two anchors, and the panel's child alone a bevel", sorted(c.name for c in guard.children) == ["Thigh.Guard.fit.gunmetal", "Thigh.Guard.fit.olive_light", "Thigh.Guard.mark.num", "Thigh.Guard.port.feed"] - and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == 8 * 8 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE") + and len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons) == len(thigh_built[0]["bolts"][1]) > 0 and bevel(bpy.data.objects["Shin.Guard.fit.olive_light"]) == (0.009, 20.0, 1, "ANGLE") and len(bpy.data.objects) == count + 10, [sorted(c.name for c in guard.children), len(bpy.data.objects["Thigh.Guard.fit.gunmetal"].data.polygons), len(bpy.data.objects) - count]) _, joints_after = send("brokkr_kitbash.joints", object_name="Thigh") check("roll-carries: joints lists the same rows with the plates as without", joints_before is not None and joints_after == joints_before, joints_after) diff --git a/surfaces/blender/tests/live/kitbash_plates.result.json b/surfaces/blender/tests/live/kitbash_plates.result.json index 73d80c8..be8856e 100644 --- a/surfaces/blender/tests/live/kitbash_plates.result.json +++ b/surfaces/blender/tests/live/kitbash_plates.result.json @@ -278,7 +278,7 @@ "carried": 1e-07, "moved": 2.1e-07, "ported": 3.9e-08, - "written": 8.5e-08 + "written": 8.4e-08 }, "reports": { "thigh": { @@ -289,7 +289,7 @@ "corners": 16, "facets": 10, "panels": 1, - "bolts": 8, + "bolts": 4, "anchors": [ "Thigh.Guard.port.feed", "Thigh.Guard.mark.num" diff --git a/surfaces/blender/tests/test_plate.py b/surfaces/blender/tests/test_plate.py index ad6c9ca..e331030 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 @@ -15,10 +15,13 @@ import importlib import inspect import json import math +import random 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 +92,273 @@ 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 clear(points, ring): + """How far the nearest edge of a ring (the segment, not its line) stands from each point.""" + ring, points = np.asarray(ring, dtype=np.float64), np.asarray(points, dtype=np.float64) + a, edge = ring[None, :, :], (np.roll(ring, -1, axis=0) - ring)[None, :, :] + along = np.clip(((points[:, None, :] - a) * edge).sum(axis=2) / (edge * edge).sum(axis=2), 0, 1) + return np.linalg.norm(points[:, None, :] - a - edge * along[:, :, None], axis=2).min(axis=1) + + +def within(point, ring): + """Whether a point stands inside a ring, convex or not: a ray to +x crosses its edges an odd number of times.""" + a, b = np.asarray(ring, dtype=np.float64), np.roll(np.asarray(ring, dtype=np.float64), -1, axis=0) + over = (a[:, 1] > point[1]) != (b[:, 1] > point[1]) + return bool(np.sum(a[over, 0] + (point[1] - a[over, 1]) * (b[over, 0] - a[over, 0]) / (b[over, 1] - a[over, 1]) > point[0]) % 2) + + +def blade_top(tip, length, rear): + """A blade's outline: its tip at the origin `tip` degrees wide, widest at 0.7 of its length, `rear` across its far end.""" + half = math.tan(math.radians(tip / 2)) * 0.7 * length + return [(0, 0), (0.7 * length, -half), (length, -rear / 2), (length, rear / 2), (0.7 * length, half)] + + +def blade(tip, length, rear, inset=0.11, bolt_r=0.03): + """A blade plate 0.4 thick on blade_top, clad on top.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[[x, y, z] for z in (0, 0.4) for x, y in blade_top(tip, length, rear)])) + + +def followed(made, ring, c): + """Whether a ring is its outline moved in by c, edges dropped or not: it stands inside the outline and does not + cross, c clear of every edge of it, and each of its edges runs along one of the outline's, c inside that edge's + line, in the outline's order.""" + made, ring = np.asarray(made, dtype=np.float64), np.asarray(ring, dtype=np.float64) + if not all(within(p, ring) for p in made) or plate._crosses(made) or float(clear(made, ring).min()) < c - 1e-9: + return False + ways = [(np.roll(r, -1, axis=0) - r) / np.linalg.norm(np.roll(r, -1, axis=0) - r, axis=1)[:, None] for r in (made, ring)] + along = [[j for j in range(len(ring)) if ways[0][i] @ ways[1][j] > 1 - 1e-9 and abs(float((made[i] - ring[j]) @ (-ways[1][j][1], ways[1][j][0])) - c) < 1e-9] + for i in range(len(made))] + took = [] + for found in along: # of two outline edges on one line, the next one round + if not found: + return False + took.append(next((j for j in found if took and j > took[-1]), found[0])) + return sum(took[i] < took[i - 1] for i in range(len(took))) == 1 + + +def sheet(top, inset=0.11, bolt_r=0.03): + """A sheet 0.3 thick under `top`, its top facets clad: points that stand a little off one plane make top facets + within MERGE of each other, which the hull makes one facet that need not be convex.""" + clad = {"mat": "c", "facets": [{"n": [0, 0, 1], "cos": 0.6}], "min_area": 0.01, "lifts": [0.045, 0.075], "inset": inset, "gap": 0.05, "split": 99, "seed": 1, "bolt_r": bolt_r} + return doc(row("Fin", clad=clad, points=[list(p) for p in top] + [[x, y, z - 0.3] for x, y, z in top])) + + +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 half-planes left out (the corner move returned whatever + its edges do); the forwards test read off the corners held at MITER and not off where the lines cross; the turn + test of the held corners removed; a ring that is not convex given to the half-planes; a right turn of a rounding + read as not convex; a half-plane left out; the ring of under three corners or of corners TIE apart returned.""" + + 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_a_sharp_corner_held_back_is_no_way_out_of_the_outline(self): + sliver = [[11, 1], [12, 1], [6, 3], [4, 3], [6, 2]] # two corners sharp: an edge goes at 0.3, all of it at 0.5 + kite = [[4, 1], [7, 0], [3, 2], [0, 3]] # held at MITER every edge runs forwards, and two corners stand outside + wedge = [[0, 1], [6, 1], [7, 3], [3, 2]] # every edge runs forwards where the lines cross; held, the ring turns right + for ring, c, corners in ((sliver, 0.3, 4), (sliver, 0.5, 0), (kite, 0.5, 0), (wedge, 0.5, 4)): + made = plate.inset2d(ring, c) + self.assertEqual(len(made), corners) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + self.assertLess(float(depths(corner_move(kite, 0.5)[0], kite).min()), -0.05) + self.assertLess(float(turns(corner_move(wedge, 0.5)[0]).min()), 0) + + def test_every_inset_of_a_convex_ring_stands_inside_it(self): + draw, rings_, held, dropped, empty = random.Random(7), 0, 0, 0, 0 + while rings_ < 3000: + at = sorted(draw.uniform(0, 2 * math.pi) for _ in range(draw.choice((3, 4, 5, 6, 7)))) + wide, tall = draw.uniform(0.15, 2.0), draw.uniform(0.02, 0.5) + ring = np.array([[wide * math.cos(u), tall * math.sin(u)] for u in at]) + if float(np.linalg.norm(np.roll(ring, -1, axis=0) - ring, axis=1).min()) < 0.005 or float(turns(ring).min()) < 1e-4: + continue + c, rings_ = draw.choice((0.01, 0.03, 0.1, 0.25)), rings_ + 1 + made, (moved, clamped) = plate.inset2d(ring, c), corner_move(ring, c) + if made.tobytes() == moved.tobytes(): + held += clamped + self.assertGreater(float(depths(made, ring).min()), 0) + self.assertGreater(float(turns(made).min()), 0) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12 if not clamped else math.inf) + else: + dropped, empty = dropped + (len(made) > 0), empty + (not len(made)) + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + self.assertEqual((held, dropped, empty), HELD) + + def test_an_outline_that_is_not_convex_is_followed_in(self): + tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] # a tab 0.4 wide on a 4 by 2 body + for c in (0.05, 0.15, 0.1999): + made = plate.inset2d(tab, c) + self.assertEqual(made.tobytes(), corner_move(tab, c)[0].tobytes()) + self.assertTrue(followed(made, tab, c)) + arm = [[0, 0], [4, 0], [4, 2], [0.4, 2], [0.4, 5], [0, 5]] # an arm 0.4 wide up the body's left side + self.assertEqual(len(plate.inset2d(arm, 0.1999)), 6) + for outline in (tab, arm): # the tab's end runs out at 0.2: its sides face each other and go, the body's top is one edge again + for c in (0.2001, 0.25, 0.9): + made = plate.inset2d(outline, c) + self.assertLess(apart2(made, [[c, c], [4 - c, c], [4 - c, 2 - c], [c, 2 - c]]), 1e-12) + self.assertTrue(len(made) == 4 and followed(made, outline, c)) + self.assertEqual(plate.inset2d(outline, 1.0001).shape, (0, 2)) + barb = [[0, 0], [6, 0], [2, 0.5], [0, 2]] # a sharp tip whose upper edge ends at a corner turning right + self.assertEqual(plate.inset2d(barb, 0.2).tobytes(), corner_move(barb, 0.2)[0].tobytes()) + made = plate.inset2d(barb, 0.3) # that edge has run out: its two neighbours bound a triangle + self.assertLess(apart2(made, half_planes([[0, 0], [8 / 3, 0], [0, 2]], 0.3)), 1e-12) + self.assertTrue(len(made) == 3 and followed(made, barb, 0.3)) + straight = [[0, 0], [3 * 0.3, 3 * 0.3 * 0.3], [3, 3 * 0.3], [3, 3 * 0.3 + 0.2], [0, 1]] # its second point is on a straight run + self.assertTrue(-1e-12 < float(turns(straight)[1]) < 0) # and turns right by a rounding: no corner that can reach an edge + made = plate.inset2d(straight, 0.15) # its short edge runs out; the point on the run stays a point on the run + self.assertTrue(len(made) == 4 and followed(made, straight, 0.15)) + self.assertLess(apart2(made[[0, 2, 3]], half_planes(straight, 0.15)), 1e-12) + + def test_an_outline_that_would_meet_itself_is_refused_at_half_its_neck(self): + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + for c in (0.05, 0.0999): + made = plate.inset2d(neck, c) + self.assertEqual(made.tobytes(), corner_move(neck, c)[0].tobytes()) + self.assertTrue(followed(made, neck, c)) + for c in (0.1001, 0.15, 0.3): + with self.assertRaises(plate.NotSimple) as caught: + plate.inset2d(neck, c) + self.assertEqual(str(caught.exception), f"moved in {c}, the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8") + hook = [[0, -2], [3, -2], [3, 5], [0, 5], [0, 2.2], [2, 1.5], [0, 0.8]] # a corner turning right, 1 from the far side + reach = 1 / (1 + math.hypot(2, 0.7) / 0.7) # it moves in 3.03 for the far side's 1: they meet at 0.2483 + self.assertTrue(followed(plate.inset2d(hook, reach - 1e-4), hook, reach - 1e-4)) + self.assertRaises(plate.NotSimple, plate.inset2d, hook, reach + 1e-4) + + def test_a_held_corner_steps_to_the_crossing_where_the_ring_first_loses_an_edge(self): + """The step kitbash.md states: c / MITER from the outline's corner while every edge has length, c over the sine + of half the corner from there on, and never out of the outline.""" + top, sine = blade_top(10.5, 2.43, 0.2), math.sin(math.radians(10.5 / 2)) + for c, corners, tip in ((0.05, 5, 0.05 / plate.MITER), (0.108, 5, 0.108 / plate.MITER), (0.109, 4, 0.109 / sine), (0.15, 4, 0.15 / sine)): + made = plate.inset2d(top, c) + self.assertEqual(len(made), corners) + self.assertLess(abs(float(np.linalg.norm(made, axis=1).min()) - tip), 1e-12) + self.assertGreater(float(depths(made, top).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) + reflex = held = dropped = empty = 0 + for ring, c, made in calls: + moved, clamped = corner_move(ring, c) + if float(turns(ring).min()) <= 0: # a slab's outline need not be convex: every corner moved, c clear of every edge + reflex += 1 + self.assertEqual(made.tobytes(), moved.tobytes()) + self.assertFalse(clamped) + self.assertGreater(float(clear(made, ring).min()), c - 1e-12) + self.assertTrue(all(within(p, ring) for p in made) and not plate._crosses(made)) + self.assertGreater(float((turns(made) * turns(ring)).min()), 0) + continue + if len(made): + self.assertGreater(float(depths(made, ring).min()), 0) # it stands inside its outline + self.assertGreater(float(turns(made).min()), 0) + if clamped and made.tobytes() == moved.tobytes(): + held += 1 # a sharp corner held at MITER: inside, turning left, not the half-planes + continue + self.assertLess(apart2(made, half_planes(ring, c)), 1e-12) + dropped, empty = dropped + (0 < len(made) < len(ring)), empty + (not len(made)) + self.assertEqual((len(calls), reflex, held, dropped, empty), (812, 6, 24, 37, 22)) + + @unittest.skipIf(np is None, "numpy is not installed") class CheckTests(unittest.TestCase): def refused(self, document, path): @@ -160,6 +430,21 @@ class CheckTests(unittest.TestCase): 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_an_outline_not_convex_is_refused_where_the_gap_or_the_taper_makes_it_meet_itself(self): + tab = [[0, 0], [4, 0], [4, 2], [2.2, 2], [2.2, 2.8], [1.8, 2.8], [1.8, 2], [0, 2]] + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] + meets = "the outline meets itself: the corner of the edges from points 1 and 2 reaches the edge from point 8" + for document, message in ((doc(row(slab=dict(SLAB, outline=neck, gap=0.15))), f"plates[0].slab.outline: moved in 0.15, {meets}"), + (doc(row(slab=dict(SLAB, outline=neck, gap=0.05, taper=0.06))), f"plates[0].slab.outline: moved in 0.06, {meets}")): + self.refused(document, message) + with self.assertRaises(plate.PlateError) as caught: # build refuses what check does, in the same words + plate.build(document) + self.assertEqual(str(caught.exception), message) + plate.check(doc(row(slab=dict(SLAB, outline=neck, gap=0.0999, taper=0.0)))) + for gap in (0.15, 0.25): # the tab is gone at 0.2: the slab is the body's + (entry,) = plate.build(plate.check(doc(row(slab=dict(SLAB, outline=tab, gap=gap, taper=0.0))))) + self.assertEqual(entry["report"]["corners"], 12 if gap < 0.2 else 8) + 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): @@ -187,6 +472,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 +664,161 @@ 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_three_near_heads_across_the_ring_start_are_one(self): + """Kills: the merge going on from the pair before in place of the first pair (it leaves two heads 1.9 r apart).""" + r = 0.03 + heads = np.array([[1.9, 0.9], [1.5, 40], [-18, 40], [-18, 9], [0, 0], [1.9, -0.9]]) * r # the last and the first 1.8 r apart, their middle 1.9 r from the one before + outline = corner_move(heads, -(0.05 + 3.2 * r))[0] + self.assertLess(apart2(plate.inset2d(plate.inset2d(outline, 0.05), 3.2 * r), heads), 1e-12) + bolts = plate._Mesh() + self.assertTrue(plate.panel(plate._Mesh(), bolts, [np.array([x, y, 0.0]) for x, y in outline], np.array([0.0, 0.0, 1.0]), 0.04, 0.05, r)) + made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] + self.assertLess(apart2(made, np.array([[1.5, 40], [-18, 40], [-18, 9], [0.95, 0]]) * r), 1e-12) + + def test_two_near_heads_that_are_not_neighbours_are_one(self): + """Kills: the merge reading neighbours in ring order only (it leaves the second and the fourth 1.8 r apart).""" + r = 0.06 + heads = np.array([[2.2, 0], [0, 0.9], [-2.2, 0], [0, -0.9]]) * r # neighbours 2.38 r apart, the second and the fourth 1.8 r + outline = corner_move(heads, -(0.05 + 3.2 * r))[0] + self.assertLess(apart2(plate.inset2d(plate.inset2d(outline, 0.05), 3.2 * r), heads), 1e-12) + bolts = plate._Mesh() + self.assertTrue(plate.panel(plate._Mesh(), bolts, [np.array([x, y, 0.0]) for x, y in outline], np.array([0.0, 0.0, 1.0]), 0.04, 0.05, r)) + made = bolts.done()[0].reshape(-1, 12, 3).mean(axis=1)[:, :2] + self.assertLess(apart2(made, np.array([[2.2, 0], [0, 0], [-2.2, 0]]) * r), 1e-12) + self.assertLess(float(np.abs(made[1]).max()), 1e-12) # the one made of two stands where the first of them stood in the ring + + def test_every_bolt_of_a_blade_plate_stands_on_it(self): + """Kills: the half-planes left out (10 of these blades then put a bolt off the plate, the worst 3.3 m).""" + entry = plate.build(blade(20, 1.5, 0.3), 1)[0] # its bolt ring is narrower than the bolts stand in: no ring, no bolts + self.assertEqual((entry["report"]["panels"], entry["report"]["bolts"]), (1, 0)) + bolted, least = 0, math.inf + for tip in (14, 16, 18, 20, 22, 25, 28, 32): + for length in (0.8, 1.2, 1.5, 2.0, 3.0): + for rear in (0.1, 0.2, 0.3, 0.4, 0.6): + entry = plate.build(blade(tip, length, rear), 1)[0] + V, faces = entry["solid"] + (top,) = [face for face in faces if all(V[k][2] > 0.3 for k in face)] + if entry["report"]["bolts"]: + bolted += 1 + least = min(least, float(depths(entry["bolts"][0].reshape(-1, 12, 3).mean(axis=1)[:, :2], V[top][:, :2]).min())) + self.assertEqual(bolted, 104) + self.assertGreater(least, 0.03) # a head's corners reach bolt_r: every head whole on its facet + + def test_no_two_bolt_heads_of_a_blade_plate_overlap(self): + """3,591 blades, tips of 8 to 44 degrees. Kills: the merge reading neighbours in ring order only (50 of them + then keep two heads under 2 bolt_r apart, the nearest 0.27).""" + bolted, heads, nearest = 0, 0, math.inf + for tip in range(8, 46, 2): + for length in (0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0): + for rear in (0.03, 0.06, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6, 0.8): + for inset in (0.05, 0.11, 0.2): + at = plate.build(blade(tip, length, rear, inset), 1)[0]["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + bolted, heads = bolted + (len(at) > 0), heads + len(at) + if len(at) > 1: + nearest = min(nearest, float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min())) + self.assertEqual((bolted, heads), (1857, 7446)) + self.assertGreaterEqual(nearest, 2 * 0.03) + + def test_a_facet_that_is_not_convex_is_built_as_check_says(self): + """Top facets within MERGE of each other are one facet, and that one need not be convex. Soul's table, then + 1,500 drawn like it. Kills: an inset that refuses such a facet (build then raises on 77 sheets check passed); + panel taking that refusal for the table's (the 3 rings that would meet themselves raise).""" + soul = [[0.46231115288947655, -0.7464122608740515, 0.005076090953713479], [0.48625943944459826, -0.5771679834143375, 0.006610213759068515], + [0.7933326463565815, 0.3201403232773634, 0.009341146944706617], [-0.06168868858561849, 0.6415607593647952, 0.006680572413020032], + [-0.5231073349097417, 0.9203597671588255, 0.00622360127002797], [0.8223018952005992, -0.9577282429612575, 0.0028711637754610976], + [0.7686109712617415, -0.6216304824437804, 0.007801596935861264]] + (entry,) = plate.build(plate.check(sheet(soul)), 1) + self.assertEqual(entry["report"], {"corners": 9, "facets": 8, "panels": 1, "bolts": 3}) + inset, calls = plate.inset2d, [] + + def spy(ring, c): + calls.append([np.array(ring, dtype=np.float64), c, None]) + calls[-1][2] = inset(ring, c) + return calls[-1][2] + draw, tally = random.Random(5), {"reflex": 0, "short": 0, "met": 0, "panels": 0, "bolts": 0} + with mock.patch.object(plate, "inset2d", spy): + for _ in range(1500): + top = [[draw.uniform(-1, 1), draw.uniform(-1, 1), draw.uniform(0, 0.012)] for _ in range(draw.randint(5, 9))] + del calls[:] + (entry,) = plate.build(plate.check(sheet(top, draw.choice((0.05, 0.11, 0.2)))), 1) + tally["panels"], tally["bolts"] = tally["panels"] + entry["report"]["panels"], tally["bolts"] + entry["report"]["bolts"] + at = entry["bolts"][0].reshape(-1, 12, 3).mean(axis=1) + self.assertTrue(len(at) < 2 or float((np.linalg.norm(at[:, None] - at[None], axis=2) + 9 * np.eye(len(at))).min()) >= 2 * 0.03) + for ring, c, made in calls: + if float(turns(ring).min()) < -plate.REFLEX: + tally["reflex"], tally["met"] = tally["reflex"] + 1, tally["met"] + (made is None) + if made is not None and len(made) != len(ring): + tally["short"] += 1 + self.assertTrue(not len(made) or followed(made, ring, c)) + self.assertEqual(tally, {"reflex": 519, "short": 84, "met": 2, "panels": 1991, "bolts": 5946}) + + def test_a_ring_that_would_meet_itself_is_left_out_and_not_refused(self): + """Kills: panel or prism letting NotSimple through (build would refuse what check passed).""" + neck = [[0, 0], [2, 0], [2, 0.9], [4, 0.9], [4, 0], [6, 0], [6, 2], [4, 2], [4, 1.1], [2, 1.1], [2, 2], [0, 2]] # two lobes, a neck 0.2 wide + facet, up = [np.array([x, y, 0.0]) for x, y in neck], np.array([0.0, 0.0, 1.0]) + self.assertRaises(plate.NotSimple, plate.inset2d, neck, 0.15) + panels, bolts = plate._Mesh(), plate._Mesh() + self.assertFalse(plate.panel(panels, bolts, facet, up, 0.04, 0.15, 0.03)) # the panel's outline would: no panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (0, 0)) + self.assertTrue(plate.panel(panels, bolts, facet, up, 0.04, 0.05, 0.03)) # its neck is 0.1 wide and the bolts stand 0.096 in: a bare panel + self.assertEqual((len(panels.verts), len(bolts.verts)), (36, 0)) + self.assertTrue(plate.panel(plate._Mesh(), bolts, facet, up, 0.04, 0.001, 0.03)) # a neck 0.198 wide: the bolts' ring keeps 0.006 of it, + self.assertEqual(len(bolts.verts), 12 * 10) # and its heads across each end of the neck are one: 10 of 12 + thin = np.array([[x, y if y in (0, 2) else 1 + (y - 1) * 0.15] for x, y in neck]) # a neck 0.03 wide: the rim, 0.02 in, would + mesh = plate._Mesh() + plate.prism(mesh, np.zeros(3), *np.eye(3), thin, 0.1, 0.02) + V = mesh.done()[0] + self.assertTrue(np.array_equal(V[24:, :2], thin) and np.array_equal(V[12:24, :2], thin)) + + 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 +946,73 @@ 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" +HELD = (816, 585, 1022) # of 3,000 drawn convex rings: sharp corners held at MITER, rings that lost an edge, rings left empty +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 +1032,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__":