From e9f53fc3a93dcb1417fd74525bc4122ed06c759b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 08:47:12 +0100 Subject: [PATCH] brokkr_kitbash.ribs: the standoff along the plate's normal, ribs that follow a crease, and the s1 Lows Fix batch h2 of cut-kit-ribs, against verdict aetheria-release:verdict:cut-kit-ribs.s1 and follow_up ribs-fold-at-crease. core.band replaces core.cornered and the rib's sweep: the rib is the band beside its section, each edge the section offset with mitred corners and clipped as a polygon offset is (core.away, the distance to a polyline less each segment's own distance). Inside a turn tighter than the rib reaches the edges cut the corner instead of folding, so a creased shell is ribbed and not refused; a section that leaves no room at all is refused by reason. Holes stand on the band's clipped centre line; a post that would end outside the rib inside such a turn is left out. The band does not depend on the section's direction, so the chain reversal (mutant N3, dead) is gone. standoff-oblique-sections: a segment's distance is the plate's thickness and the standoff over the cosine of the plate's lean out of the plane, plus half the rib's thickness times its tangent. Pinned on cones leaning 0, 30, 45 and 60 degrees and a hipped box (45 against 20): the rib comes the standoff from the plate, 5.3e-08 off, and is the analytic ring. negative-solidify-thickness: the sign is folded into the offset. planes-string-cap-below-64: planes 16000 characters, longerons 8000; 64 planes at full precision are taken. plate-window-unpinned: a recess 0.8 of the plate deep (N5) and a port in a cage whose far wall stands 3.5 plates behind (N13). figures-do-not-match: FIT is re-measured along the normal (0.0011, bound 0.002), Manifold is 26 times Exact, not a hundred. Sixteen mutants die on this tree (O1 O2 O3 S1 N5 N13 P1 C1 V1 M1 T1 D1 G1 A1 live or unit, L1 W1 unit). 496 unit tests; kitbash_ribs 41 checks. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 64 +++---- .../brokkr_kitbash/brokkr_actions.json | 8 +- surfaces/blender/brokkr_kitbash/core.py | 163 +++++++++++++++--- surfaces/blender/tests/live/kitbash_ribs.py | 145 ++++++++++++++-- .../tests/live/kitbash_ribs.result.json | 56 +++++- surfaces/blender/tests/test_kitbash.py | 116 +++++++++++-- 6 files changed, 453 insertions(+), 99 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index c566a12..26465a7 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -37,7 +37,7 @@ cut_many, apply) first refuses one Blender does not evaluate (evaluable). A repo receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said. ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where -the plate is open, with lightening holes, posts and longerons, all core.sweep. What it reads is the cage evaluated +the plate is open (core.band), with lightening holes, posts and longerons (core.sweep). What it reads is the cage evaluated whole (where the plate is) and with its Solidify, Bevel and Booleans off (the surface as designed); it never reads a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it is the request, kept as a record: nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole @@ -975,7 +975,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): object_name: bpy.props.StringProperty(name="Object", description="The cage: a mesh whose surface is the plate's designed face, usually subdivided and with one Solidify") ribs_name: bpy.props.StringProperty(name="Ribs", description="The new ribs object's name") planes: bpy.props.StringProperty(name="Planes", description="A JSON array of 1 to 64 planes, each {origin, normal} in the cage's own frame: a rib runs where each cuts the surface") - standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs") + standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs, along the plate's normal") depth: bpy.props.FloatProperty(name="Depth", default=0.09, min=0.005, max=2.0, description="How far a rib reaches inward from there") thickness: bpy.props.FloatProperty(name="Thickness", default=0.014, min=0.0005, max=1.0, description="A rib's thickness across its plane") step: bpy.props.FloatProperty(name="Step", default=0.01, min=0.001, max=1.0, description="Spacing of the points a section is followed by") @@ -1011,15 +1011,14 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): walls = [m for m in cage.modifiers if m.type == "SOLIDIFY" and m.show_viewport] if len(walls) > 1: raise Refused(f"{cage.name!r} has {len(walls)} Solidify modifiers ({', '.join(m.name for m in walls)}): its plate has one thickness, read from one; nothing changed.") - plate, offset = (abs(walls[0].thickness), walls[0].offset) if walls else (0.0, 0.0) + # a Solidify of negative thickness grows the other way: the same plate as its size with the offset turned over + plate, offset = (abs(walls[0].thickness), math.copysign(1.0, walls[0].thickness) * walls[0].offset) if walls else (0.0, 0.0) outer, inner = plate * (1.0 + offset) / 2.0, plate * (1.0 - offset) / 2.0 # the plate's two faces, out of and into the designed surface - near, mid = inner + self.standoff, inner + self.standoff + self.depth / 2.0 - web = np.array([(-self.thickness / 2, near), (self.thickness / 2, near), (self.thickness / 2, near + self.depth), (-self.thickness / 2, near + self.depth)]) whole = BVHTree.FromObject(cage, depsgraph) # the plate as it is cut: where a ray into it finds nothing, it is open shown = [m for m in cage.modifiers if m.type in SHELL_MODIFIERS and m.show_viewport] surface, made, drilled, sections, webs, rods, beams, samples, holes = None, [], [], [], [], [], [], 0, 0 try: - for modifier in shown: + for modifier in shown: # this tags the cage, and Blender evaluates it whole again after the call: one evaluation a call, and no cheaper way to the designed surface (docs/kitbash.md, Ribs from a shell) modifier.show_viewport = False _, designed = evaluated_of(context, cage) surface = bmesh.new() @@ -1044,55 +1043,59 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): if samples > SAMPLES_LIMIT: raise Refused(f"The sections are over {SAMPLES_LIMIT} points at step {self.step:.6g}: raise step, or give fewer planes; nothing changed.") P = core.resample(points, closed, self.step) - out = np.array([nearest.find_nearest(Vector(p))[1] for p in P], dtype=np.float64) + between = ((P + np.roll(P, -1, axis=0)) / 2.0)[:len(P) if closed else len(P) - 1] # the middle of each segment: a point of one facet, where a corner is a point of two + out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at], dtype=np.float64) for at in (P, between)) flat = out - normal * (out @ normal)[:, None] - if not (np.linalg.norm(flat, axis=1) > 1e-3).all(): + upright = np.sqrt(1.0 - np.minimum((facing @ normal) ** 2, 1.0)) # the cosine of how far the plate's normal leans out of the plane, a segment + if not (np.linalg.norm(flat, axis=1) > 1e-3).all() or not (upright > 1e-3).all(): raise Refused(f"{where} lies along {cage.name!r}'s surface where it meets it: a rib needs a plane that crosses the plate; nothing changed.") inward = -flat / np.linalg.norm(flat, axis=1)[:, None] + # The plate is `inner` thick and the rib stands `standoff` off it along the plate's own normal: along the plane, where + # the rib lies, both are longer by 1 / upright, and the rib's edge on the side the plate leans over is half a + # thickness nearer still. One distance for each segment of the section. + slope, back = 1.0 / upright, ((inner + self.standoff) + self.thickness / 2.0 * np.abs(facing @ normal)) / upright ahead = np.roll(P, -1, axis=0) - np.roll(P, 1, axis=0) if closed else np.gradient(P, axis=0) turn = np.cross(ahead, inward) @ normal # which side of the section its normals stand on: one sign all the way along if (turn > 0).any() and (turn < 0).any(): raise Refused(f"{where}: the normals of {cage.name!r} change sides along the section (some of its faces are flipped): " "recalculate its normals so they all face out of the plate; nothing changed.") - if turn[0] < 0: # every section runs the same way about its plane's normal, wherever its chain started - P, out, inward = P[::-1], out[::-1], inward[::-1] aside = np.roll(P, -1, axis=0) - P if closed else np.vstack([np.diff(P, axis=0), P[-2:-1] - P[-1:]]) # toward the next point; an open chain's last, toward the one before aside = aside / np.linalg.norm(aside, axis=1)[:, None] * NUDGE reach = LIFT + 1.25 * plate + 1e-4 opened = [whole.ray_cast(Vector(p + n * (outer + LIFT)), Vector(-n), reach)[0] is None for p, n in zip(P + aside, out)] lengths = np.linalg.norm(np.diff(np.vstack([P, P[:1]]) if closed else P, axis=0), axis=1) - row["lines"].append((P + inward * mid, closed)) + row["lines"].append((P + inward * (np.resize(back, len(P)) + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it for piece in core.spans(opened, lengths, closed, self.bridge, self.clearance): ring = closed and len(piece) == len(P) - piece = piece[core.cornered(P[piece], ring, near + self.depth)] # swept corner to corner - if len(piece) < 2: - continue try: - rib = core.sweep(P[piece], web, inward[piece], closed=ring) + rib = core.band(P[piece], ring, normal, inward[piece], back[piece if ring else piece[:-1]], self.depth, self.thickness) except core.KitError as error: raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None - centre = rib.V.reshape(len(piece), 4, 3).mean(axis=1) # the rib's mid-depth line, as swept - row["ribs"].append((centre, ring, P[piece], inward[piece])) + row["ribs"].append({"band": rib, "ring": ring, "P": P[piece], "inward": inward[piece], "back": back[piece if ring else piece[:-1]], "slope": slope[piece if ring else piece[:-1]]}) row["pieces"] += 1 row["length"] += float(np.linalg.norm(np.diff(np.vstack([P[piece], P[piece][:1]]) if ring else P[piece], axis=0), axis=1).sum()) - webs.append((index, rib)) + webs.append((index, rib.shell)) row["open"] += float(lengths.sum()) row["open"] = round(max(row["open"] - row["length"], 0.0), 6) sections.append(row) if not webs: raise Refused(f"No rib: the plate of {cage.name!r} is open along every section; nothing changed.") for row in sections: # posts stand on the kept runs only - for centre, ring, P, inward in row["ribs"] if self.posts > 0 else (): - for point, segment, fraction in along(P, ring, self.posts): - n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * fraction - n, up = n / np.linalg.norm(n), planes[row["plane"]]["normal"] - rods.append(core.sweep([point + n * (inner - outer) / 2.0, point + n * (near + 0.3 * self.depth)], core.circle(self.post_r, POST_SEGMENTS), up)) - rods.append(core.sweep([point + n * inner, point + n * (inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) + for rib in row["ribs"] if self.posts > 0 else (): + P, up = rib["P"], planes[row["plane"]]["normal"] + for point, segment, fraction in along(P, rib["ring"], self.posts): + n, back, slope = rib["inward"][segment] + (rib["inward"][(segment + 1) % len(P)] - rib["inward"][segment]) * fraction, rib["back"][segment], rib["slope"][segment] + n = n / np.linalg.norm(n) + foot = point + n * (back + 0.3 * self.depth) + if core.away(foot, P, rib["ring"])[0] < back: # inside a turn the rib was clipped at: a post there would end outside it + continue + rods.append(core.sweep([point + n * slope * (inner - outer) / 2.0, foot], core.circle(self.post_r, POST_SEGMENTS), up)) + rods.append(core.sweep([point + n * slope * inner, point + n * (slope * inner + self.post_r)], core.circle(2.4 * self.post_r, PAD_SEGMENTS), up)) for index, longeron in enumerate(longerons): where, stations, ups = f"longerons[{index}]", [], [] for row in sections: try: - hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib[0], rib[1], longeron["origin"], longeron["axis"], longeron["toward"])] + hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib["band"].centre, rib["ring"], longeron["origin"], longeron["axis"], longeron["toward"])] through = any(core.crossings(line, closed, longeron["origin"], longeron["axis"], longeron["toward"]) for line, closed in row["lines"]) except core.KitError as error: raise Refused(f"{where}: {error}; nothing changed.") from None @@ -1100,8 +1103,9 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"{where} " + (f"meets the ribs of planes[{row['plane']}] {len(hits)} times: its half-plane must cross them once" if hits else f"crosses planes[{row['plane']}] where the plate is open and there is no rib" if through else f"does not meet the ribs of planes[{row['plane']}]") + "; nothing changed.") - ((segment, point), (centre, ring, P, inward)), = hits - n = inward[segment] + (inward[(segment + 1) % len(P)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(P)] - centre[segment])) + ((segment, point), rib), = hits + centre, inward = rib["band"].centre, rib["inward"][rib["band"].at] + n = inward[segment] + (inward[(segment + 1) % len(centre)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(centre)] - centre[segment])) stations.append(point) ups.append(-n / np.linalg.norm(n)) # up toward the plate path = [stations[0] + (stations[0] - stations[1]) * 0.12] + stations + [stations[-1] + (stations[-1] - stations[-2]) * 0.12] @@ -1111,8 +1115,8 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): raise Refused(f"{where}: {error}; nothing changed.") from None for index in sorted({index for index, _ in webs}) if self.holes > 0 else (): # one Boolean a plane: a plane's webs never cross each other, two planes' do normal = planes[index]["normal"] - drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), inward[segment]) - for centre, ring, _, inward in sections[index]["ribs"] for point, segment, _ in along(centre, ring, self.holes)] + drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), rib["inward"][0]) + for rib in sections[index]["ribs"] for point, _, _ in along(rib["band"].centre, rib["ring"], self.holes)] # the centre line stands 0.5 of depth off both edges wherever it runs if not drills: continue pair = [] @@ -1121,7 +1125,7 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): made.append(pair[-1]) write_mesh(pair[-1].data, core.joined(shells)) context.scene.collection.objects.link(pair[0]) - modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, a hundred times sooner than Exact + modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, 26 times sooner than Exact (0.017 s against 0.44 s for the pod's 93 holes) modifier.object, modifier.operation = pair[1], "DIFFERENCE" modifier.solver = "MANIFOLD" drilled.append((index, len(drills), measured(pair[0].data)["volume"], pair[0])) diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index 8768e4b..d2906e9 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -569,7 +569,7 @@ }, { "name": "brokkr_kitbash.ribs", - "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face and reaching depth inward; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", + "doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, however it leans out of the plane) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's thickness is read from the cage's one Solidify. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -595,7 +595,7 @@ "type": "string", "required": true, "minLength": 2, - "maxLength": 8000, + "maxLength": 16000, "doc": "a JSON array of 1 to 64 planes, each {\"origin\": [x, y, z], \"normal\": [x, y, z]} in the cage's own frame; a rib runs where each cuts the surface" }, { @@ -604,7 +604,7 @@ "minimum": 0, "maximum": 2, "default": 0.09, - "doc": "metres between the plate's inner face and the ribs" + "doc": "metres between the plate's inner face and the ribs, along the plate's own normal" }, { "name": "depth", @@ -675,7 +675,7 @@ "type": "string", "default": "[]", "minLength": 2, - "maxLength": 4000, + "maxLength": 8000, "doc": "a JSON array of 0 to 16 longerons, each {\"origin\": [x, y, z], \"axis\": [x, y, z], \"toward\": [x, y, z]} in the cage's own frame: the half-plane from the line through origin along axis, on toward's side. The longeron runs through the rib of every plane, in the planes' order, where the half-plane crosses the rib's mid-depth line: exactly once a plane, and not in an opening" }, { diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 2cf3972..cce0f57 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -17,10 +17,12 @@ both kits declare the socket's type with the same match rule. surface_frame is t met a surface. closure_residual is how far two sockets stand from meeting as a pin, whatever the roll: what closes a loop the tree of connections cannot state. -The structure under an armor cage is swept, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes -an outline along a polyline with mitred joints (a rib, a longeron, a post are all one sweep), crossings finds where a -section line meets a half-plane, resample fills a section's points in, spans says which runs of a section keep -their frame where the plate over them is open, and cornered which of a run's points the frame is swept through. brokkr_kitbash.ribs is the bpy around them. +The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes +an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane, +offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what +clips it), crossings finds where a section line meets a half-plane, resample fills a section's points in, and spans +says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy +around them. A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll @@ -740,7 +742,7 @@ def crossings(points, closed: bool, origin, axis, toward) -> list: def resample(points, closed: bool, step: float) -> np.ndarray: """A polyline's own points with more between them, evenly along each segment, so that none stands over `step` from the next. A corner stays a corner: points spaced along the arc instead would cut each corner into two, a - step apart, and a section offset inward folds between them. A segment shorter than 1e-7 is dropped with its + step apart, and a band beside the section would be clipped at both. A segment shorter than 1e-7 is dropped with its first point. An open polyline keeps both ends; a closed one starts at its first point.""" points = np.asarray(points, dtype=np.float64) if not (finite(step) and step > 0) or len(points) < 2: @@ -754,27 +756,136 @@ def resample(points, closed: bool, step: float) -> np.ndarray: return np.array(made if closed else made + [loop[-1]]) -def cornered(points, closed: bool, reach: float) -> np.ndarray: - """Indices of the points a section's frame is swept through: those where the polyline turns, and an open one's - two ends. Points along a straight run add nothing to a sweep and would each stand a ring square to the run, - which a mitre at the next corner then folds over. For the same reason an open polyline's end is left out when - the corner beside it stands nearer than its mitre sets back, `reach` (how far the frame reaches to the inside) - times the tangent of half the turn there: the frame then ends at that corner. Fewer than 2 points left is none; a - closed polyline with no corner keeps every point.""" - points = np.asarray(points, dtype=np.float64) - count = len(points) - steps = (np.roll(points, -1, axis=0) - points)[:count if closed else count - 1] - steps = steps / np.linalg.norm(steps, axis=1)[:, None] - cosine = np.clip(np.einsum("ij,ij->i", np.roll(steps, 1, axis=0) if closed else steps[:-1], steps if closed else steps[1:]), -1.0, 1.0) - straight = cosine > 1.0 - 1e-12 - if closed: - return np.flatnonzero(~straight) if (~straight).sum() >= 3 else np.arange(count) - inner = (np.flatnonzero(~straight) + 1).tolist() - back = lambda corner: reach * math.sqrt((1.0 - cosine[corner - 1]) / max(1.0 + cosine[corner - 1], 1e-12)) + 1e-9 # noqa: E731 how far that corner's mitre sets the inside back - first = [] if inner and np.linalg.norm(points[inner[0]] - points[0]) <= back(inner[0]) else [0] - last = [] if inner and np.linalg.norm(points[inner[-1]] - points[-1]) <= back(inner[-1]) else [count - 1] - kept = first + inner + last - return np.array(kept if len(kept) >= 2 else [], dtype=np.int64) +AWAY_SPAN = 64 # points, and segments, that away takes at a time: a block of points skips the blocks of segments too far off to matter + + +def away(points, chain, closed: bool, less=0.0, limit: float = math.inf) -> np.ndarray: + """How far each point stands from a polyline: its least distance to any segment. With `less`, one length for + each segment, the least over the segments of the distance less that segment's length: 0 or more where the point + stands at least each segment's own length off it. A value over `limit` is not looked for and comes back as + `limit`: with one, a long polyline costs each point the segments near it and not all of them (the three edges + of a band on 20000 points: about 60 s without; the whole band 0.7 s with a limit of 0).""" + points, chain = np.asarray(points, dtype=np.float64).reshape(-1, 3), np.asarray(chain, dtype=np.float64) + a, b = (chain, np.roll(chain, -1, axis=0)) if closed else (chain[:-1], chain[1:]) + ab = b - a + square, less = np.maximum(np.einsum("ij,ij->i", ab, ab), 1e-300), np.broadcast_to(np.asarray(less, dtype=np.float64), (len(a),)) + starts = np.arange(0, len(a), AWAY_SPAN) + low, high = (np.array([side(np.vstack([a[j:j + AWAY_SPAN], b[j:j + AWAY_SPAN]]), axis=0) for j in starts]) for side in (np.min, np.max)) # each block of segments' box + most = np.maximum.reduceat(less, starts) + least = np.full(len(points), float(limit)) + for first in range(0, len(points), AWAY_SPAN): + block = points[first:first + AWAY_SPAN] + apart = np.linalg.norm(np.maximum(0.0, np.maximum(low - block.max(axis=0), block.min(axis=0) - high)), axis=1) - most # no segment of a block reads under this + near = np.concatenate([np.arange(j, min(j + AWAY_SPAN, len(a))) for j in starts[apart <= limit]] or [np.zeros(0, dtype=np.int64)]) + if len(near): + offset = block[:, None, :] - a[near][None] + offset = offset - np.clip(np.einsum("ksj,sj->ks", offset, ab[near]) / square[near], 0.0, 1.0)[:, :, None] * ab[near][None] + least[first:first + AWAY_SPAN] = np.minimum(least[first:first + AWAY_SPAN], (np.sqrt(np.einsum("ksj,ksj->ks", offset, offset)) - less[near][None]).min(axis=1)) + return least + + +class Band(NamedTuple): + """A band beside a polyline, as one closed shell, and the lines a frame is hung on it by.""" + shell: Swept + outer: np.ndarray # the band's edge next to the polyline + inner: np.ndarray # its far edge + centre: np.ndarray # the line midway between them: the polyline offset by back + depth / 2, clipped as the edges are + at: np.ndarray # for each point of centre, the index of the polyline's point it is offset from + + +def band(points, closed: bool, normal, inward, back, depth: float, thickness: float) -> Band: + """The band beside a polyline that lies in a plane: everything in that plane, on the side `inward` points to, + that stands from back to back + depth off the polyline, `thickness` across the plane; one closed shell, wound + outward. `normal` is the plane's unit normal; `inward` (one in-plane vector for each point) only says which + side; `back` is one distance, or one for each segment. + + Each edge is the polyline offset and then clipped, as a polygon offset is. A point's offset stands where its two + segments' offset lines meet, a mitre; where their distances differ and the lines meet beside one segment but + past the end of the other (two segments that are nearly one line), it stands the greater distance off both. An + offset point that stands nearer any segment than that segment's own distance is left out, and its neighbours + close the edge there. So inside a turn tighter than the band reaches the far edge cuts the corner, and the band + narrows instead of folding; between two kept points the cut is a chord, which leaves the true corner out by + less than the points' spacing. Points along a straight run with nothing clipped beside them are left out too: + they add no shape. + + Refuses, naming the point: fewer than 2 points (3 when closed), a segment shorter than 1e-9, a turn over + TURN_LIMIT; and a polyline that leaves an edge fewer than 2 points (3 when closed): it closes in on itself + nearer than the band reaches, everywhere.""" + P, normal, inward, back = (np.asarray(v, dtype=np.float64) for v in (points, normal, inward, back)) + count, least = len(P), 3 if closed else 2 + if P.ndim != 2 or P.shape[1] != 3 or count < least or inward.shape != P.shape or back.shape not in ((), (count if closed else count - 1,)) or not ( + np.isfinite(P).all() and np.isfinite(back).all() and (back >= 0).all() and depth > 0 and thickness > 0): + raise KitError(f"a band needs {least} points of three finite numbers, an inward for each, one distance of 0 or more or one for each segment, and a depth and thickness above 0; it has {count} points") + back = np.broadcast_to(back, (count if closed else count - 1,)) + steps = (np.roll(P, -1, axis=0) - P)[:count if closed else count - 1] + lengths = np.linalg.norm(steps, axis=1) + if (lengths < 1e-9).any(): + raise KitError(f"path point {int(np.argmax(lengths < 1e-9))}: the segment from it is shorter than 1e-9") + along = steps / lengths[:, None] + aside = np.cross(normal, along) # each segment's in-plane normal + into = lambda of: (np.roll(of, 1, axis=0), of) if closed else (np.concatenate([of[:1], of]), np.concatenate([of, of[-1:]])) # noqa: E731 a point's segment before and after + (before, after), (arriving, leaving) = into(aside), into(along) + cosine = np.clip(np.einsum("ij,ij->i", before, after), -1.0, 1.0) + if (cosine < math.cos(math.radians(TURN_LIMIT))).any(): + index = int(np.argmax(cosine < math.cos(math.radians(TURN_LIMIT)))) + raise KitError(f"path point {index}: the path turns {math.degrees(math.acos(cosine[index])):.1f} degrees there, over {TURN_LIMIT:g}") + side = 1.0 if np.einsum("ij,ij->", before + after, inward) > 0 else -1.0 + square = np.maximum(1.0 - cosine ** 2, 1e-18) + edges, valid, uneven = [], [], np.zeros(count, dtype=bool) + for further in (0.0, depth, depth / 2.0): + first, second = into(back + further) + even = (np.maximum(first, second) / (1.0 + cosine))[:, None] * (before + after) # the greater distance off both segments + met = ((first - cosine * second) / square)[:, None] * before + ((second - cosine * first) / square)[:, None] * after # first off one, second off the other + mitred = (first != second) & (np.einsum("ij,ij->i", met, arriving) * np.einsum("ij,ij->i", met, leaving) <= 0.0) # beside both segments, or past the ends of both + edges.append(P + side * np.where(mitred[:, None], met, even)) + valid.append(away(edges[-1], P, closed, back + further, limit=0.0) >= -1e-6 * np.maximum(first, second) - 1e-9) + uneven |= first != second + turns = (cosine < 1.0 - 1e-12) | uneven + if not closed: + turns[[0, -1]] = True + state = valid[0] * 4 + valid[1] * 2 + valid[2] + changes = (state != np.roll(state, 1)) | (state != np.roll(state, -1)) + if not closed: + changes[0], changes[-1] = state[0] != state[1], state[-1] != state[-2] + kept = np.flatnonzero((turns | changes) & (valid[0] | valid[1])) + reached = np.concatenate([[0.0], np.cumsum(lengths)]) + lines, maps = [], [] + for edge, ok in zip(edges, valid): # a clipped point takes the nearest kept one along the polyline + own = kept[ok[kept]] + if len(own) < least: + raise KitError(f"path point {int(np.argmin(valid[1]))}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches") + apart = np.linalg.norm(np.diff(edge[own], axis=0), axis=1) > 1e-9 # a point clipped exactly onto its neighbour is that neighbour + own = own[np.concatenate([[True], apart])] + if closed and np.linalg.norm(edge[own[0]] - edge[own[-1]]) <= 1e-9: + own = own[:-1] + after = np.searchsorted(reached[own], reached[kept]) # the kept point of this edge at or after each kept point, and the one before + pair = np.stack([after - 1, after]) % len(own) if closed else np.clip(np.stack([after - 1, after]), 0, len(own) - 1) + gap = np.abs(reached[own][pair] - reached[kept][None, :]) + lines.append((edge[own], own)) + maps.append(pair[np.argmin(np.minimum(gap, reached[-1] - gap) if closed else gap, axis=0), np.arange(len(kept))]) + ((outer, _), (inner, _), (centre, at)), (to_outer, to_inner, _) = lines, maps + half = normal * thickness / 2.0 + A, B = len(outer), len(inner) # vertices: outer low, outer high, inner low, inner high + faces = [] + for i, j in [(k, k + 1) for k in range(len(kept) - 1)] + ([(len(kept) - 1, 0)] if closed else []): + a0, a1, b0, b1 = to_outer[i], to_outer[j], 2 * A + to_inner[i], 2 * A + to_inner[j] + if a0 != a1: + faces.append((a0, a1, A + a1, A + a0)) + if b0 != b1: + faces.append((b0, B + b0, B + b1, b1)) + cap = ([a0] if a0 == a1 else [a0, a1]) + ([b1] if b0 == b1 else [b1, b0]) + if len(cap) > 2: + faces.append(tuple(A + v if v < 2 * A else B + v for v in cap)) + faces.append(tuple(cap[::-1])) + if not closed: + faces.append((to_outer[0], A + to_outer[0], 2 * A + B + to_inner[0], 2 * A + to_inner[0])) + faces.append((to_outer[-1], 2 * A + to_inner[-1], 2 * A + B + to_inner[-1], A + to_outer[-1])) + if side < 0: + faces = [face[::-1] for face in faces] + counts = np.array([len(face) for face in faces], dtype=np.int32) + shell = Swept(V=np.vstack([outer - half, outer + half, inner - half, inner + half]), faces=np.concatenate(faces).astype(np.int32), counts=counts, + smooth=np.zeros(len(counts), dtype=bool), sharp=NO_SHARP.astype(np.int32)) + return Band(shell=shell, outer=outer, inner=inner, centre=centre, at=at) def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list: diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 57a6e5e..3446c07 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash.ribs through run_intent: ribs that stand a standoff behind a -cage's plate and in their planes, that stop at a port, run behind a panel break and under a recess, that take their side -from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing +cage's plate along the plate's own normal, however it leans, and in their planes, that follow a crease tighter than they +reach, that stop at a port, run behind a panel break and under a recess, that take their side from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing ribs, and the refusals. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_ribs.py -- @@ -61,12 +61,24 @@ R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_ COUNT, SECTION = [0], ["setup"] STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014 SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS} -# Metres between where a rib vertex stands behind the plate's inner face, along its plane, and the standoff (its outer -# edge) or the standoff and depth (its inner edge). Shipped worst 0.0093 (the pod: the plate is 0.06 thick along its -# own normal, which leans up to 30 degrees out of a rib's plane, and the rib is set 0.06 back along the plane); -# least claimed mutant 0.065 (K12, the standoff taken from the outer face: the rib's outer edge is then inside the plate); -# separation 3.5 each side. -FIT = 0.018 +# Metres between the standoff and how near a rib's outer edge comes to the plate's inner face, at each point of the edge, +# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 0.0011 (a facet's rib +# is straight where the wall is curved); least claimed mutant 0.0036 (O2, the rib's half thickness, which a leaning plate +# comes nearer, left out); the geometric mean, separation 1.8 each side. O3 (only the plate's thickness laid off along +# its normal) reads 0.0067, O1 (both laid off along the plane, as before cut-kit-ribs.h2) 0.011, K12 (the standoff taken +# from the outer face) 0.06. +FIT = 0.002 +# The same on cages of flat facets, where it is exact: cones whose wall leans 0, 30, 45 and 60 degrees out of the plane, a +# cylinder whose Solidify is negative, a hipped box, and a crease. Shipped worst 5.3e-08 (float32 meshes); least claimed mutant 0.006 +# (O2 at 60 degrees); the geometric mean, separation 340 each side. O3 reads 0.026, O1 0.036, S1 (a negative +# thickness read as its size alone) 0.06. +STOOD = 1.8e-5 +# A cone's rib or a hipped box's, over the ring between the section's two offsets times the thickness, less 1. Shipped worst 2.1e-06; +# least claimed mutant 0.034 (O2); the geometric mean, separation 130 each side. +RING = 2.7e-4 +# A rib inside a crease, over the true clipped offset's area times the thickness, less 1: tests/test_kitbash.py CREASED, +# the same polyline. Shipped 0.0013; least claimed mutant 0.079 (C1, nothing clipped); separation 7.9 each side. +CREASED = 0.0099 # Metres a rib vertex stands off its plane beyond half the rib's thickness. Shipped worst 1.4e-07 (float32 meshes); # least claimed mutant 0.007 (KP, a rib twice as thick across its plane); separation 220 each side. PLANAR = 3.1e-5 @@ -186,6 +198,15 @@ def islands(bm): return found +def nearest_by_column(surface, V): + """The least distance from a BVH to the vertices that share an x and y (to 1e-5), for each such column.""" + found = {} + for v in V: + key = (round(float(v[0]), 5), round(float(v[1]), 5)) + found[key] = min(found.get(key, 1.0), surface.find_nearest(Vector(v))[3]) + return found + + def child_of(ribs, cage): return ribs is not None and ribs.parent == cage and np.array_equal(np.array(ribs.matrix_parent_inverse), np.eye(4)) and np.array_equal(np.array(ribs.matrix_basis), np.eye(4)) \ and np.abs(np.array(ribs.matrix_world) - np.array(cage.matrix_world)).max() < 1e-6 and len(ribs.modifiers) == 0 and len(ribs.data.materials) == 0 @@ -241,21 +262,103 @@ try: and [s["open"] > 0.25 for s in report["sections"]] == [False, False, True, False, False] and all(s["open"] == 0.0 for k, s in enumerate(report["sections"]) if k != 2) and (shape["faces"], shape["nonManifoldEdges"], shape["shells"]) == (report["faces"], 0, 5) and abs(shape["volume"] - report["volume"]) < 1e-8 and 0.5 < report["volume"] / (sum(s["length"] for s in report["sections"]) * DEPTH * THICKNESS) < 1.0, report) # a rib inside a curve is shorter than the section it follows - behind = True - for v in points(fit): + behind, V = True, points(fit) + for v in V: plane = min(HEIGHTS, key=lambda z: abs(v[2] - z)) reading("planar", abs(abs(v[2] - plane) - THICKNESS / 2)) on, normal, _, _ = designed.find_nearest(Vector((v[0], v[1], plane))) - out = Vector((normal.x, normal.y, 0.0)).normalized() - hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), out) # the inner face, outward of the vertex along its plane - if hit is None: # or the vertex is in the plate, and the inner face is behind it - hit, _, _, distance = inner.ray_cast(Vector((v[0], v[1], plane)), -out) - behind, distance = False, -distance if hit is not None else 1.0 behind = behind and (Vector((v[0], v[1], plane)) - on).dot(normal) < 0 - reading("fit", min(abs(distance - STANDOFF), abs(distance - STANDOFF - DEPTH))) - check("ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + for least in nearest_by_column(inner, V).values(): # a column: the vertices of one point of an edge, half a thickness either side of the plane + if least < STANDOFF + 0.4 * DEPTH: # the outer edge's; the inner edge's stand a depth further in + reading("fit", abs(least - STANDOFF)) + check("ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from", behind and R["readings"]["fit"] < FIT and R["readings"]["planar"] < PLANAR, R["readings"]) + # --- standoff-oblique-sections: cones, a negative Solidify, and a crease ---------------------------------------------------------- + section("ribs-on-leaning-plates") + SIDES = 24 + + def frustum(name, lean, at): + """A cone's wall from z = 0.3 to 0.7 that leans `lean` degrees from its axis, radius 0.6 at z = 0.5, normals outward, a wall of 0.06 inward.""" + rows = [[((0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.cos(a), (0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.sin(a), z) + for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))] for z in (0.3, 0.7)] + return mesh_object(name, rows[0] + rows[1], [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation(at), wall=0.06) + + def stood(cage, ribs, standoff=STANDOFF): + """How near the ribs come to the cage's plate as it is evaluated, less the standoff.""" + plate = tree(cage) + return reading("stood", abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff)) + + leaned = [] + for k, lean in enumerate((0, 30, 45, 60)): + cone = frustum(f"Cone{lean}", lean, (3.0 * k, 9.0, 0.0)) + receipt, report = send("brokkr_kitbash.ribs", object_name=cone.name, ribs_name=f"ConeRibs{lean}", planes=flat([0.5]), **SIZES) + ribs = bpy.data.objects.get(f"ConeRibs{lean}") + slope = math.tan(math.radians(lean)) * math.cos(math.pi / SIDES) # of a facet: the cone's own lean is its corners' + back = (0.06 + STANDOFF) * math.hypot(1.0, slope) + THICKNESS / 2 * slope # along the plane, to the rib's outer edge + outer = 0.6 * math.cos(math.pi / SIDES) - back # the inradius of the rib's outer edge, a regular polygon + ring = SIDES * math.tan(math.pi / SIDES) * (outer ** 2 - (outer - DEPTH) ** 2) * THICKNESS + readings = (stood(cone, ribs), reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0))) if ribs is not None else (1.0, 1.0) + leaned.append(receipt["status"] == "accepted" and child_of(ribs, cone) and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.06, 0) + and readings[0] < STOOD and readings[1] < RING) + check("standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets", + leaned == [True] * 4, [leaned, R["readings"]]) + # A hipped box: walls that lean 45 and 20 degrees meet at its four corners. No Solidify: Blender's even thickness is not even where a + # vertex's faces meet at unequal angles (a wall of 0.06 here is 0.057 and 0.066 thick), and this check is of the rib, against a plate that is exact. + hip = mesh_object("Hip", [(sx * (0.6 + (z - 0.5) * math.tan(math.radians(45))), sy * (0.5 + (z - 0.5) * math.tan(math.radians(20))), z) for z in (0.3, 0.7) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))], + [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)], Matrix.Translation((15.0, 9.0, 0.0))) + receipt, report = send("brokkr_kitbash.ribs", object_name="Hip", ribs_name="HipRibs", planes=flat([0.5]), **SIZES) + ribs = bpy.data.objects.get("HipRibs") + wide, deep = (0.6 - STANDOFF * math.hypot(1.0, math.tan(math.radians(lean))) - THICKNESS / 2 * math.tan(math.radians(lean)) for lean in (45, 20)) # the rib's outer edge, from the middle + ring = 4.0 * (wide * (deep - 0.1) - (wide - DEPTH) * (deep - 0.1 - DEPTH)) * THICKNESS + check("where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)", + receipt["status"] == "accepted" and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.0, 0) and stood(hip, ribs) < STOOD + and reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0)) < RING, [receipt["message"], report, R["readings"]]) + turned = frustum("Turned", 0, (12.0, 9.0, 0.0)) + turned.modifiers["Solidify"].thickness = -0.06 # the plate grows outward of the designed surface + bpy.context.view_layer.update() + grown = max(math.hypot(v.co.x, v.co.y) for v in turned.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.vertices) + receipt, report = send("brokkr_kitbash.ribs", object_name="Turned", ribs_name="TurnedRibs", planes=flat([0.5]), **SIZES) + check("negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face", + receipt["status"] == "accepted" and grown > 0.65 and report["thickness"] == 0.06 and stood(turned, bpy.data.objects["TurnedRibs"]) < STOOD, [receipt["message"], report, grown, R["readings"]]) + turn, facet, run = math.radians(49.4), 0.062, 0.3 # tests/test_kitbash.py test_a_band_follows_a_crease_tighter_than_it_reaches: the same section, in x and z + profile = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn)), (-facet / 2, 0.0), (facet / 2, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn))] + creased = mesh_object("Creased", [(x, y, z) for y in (-0.3, 0.3) for x, z in profile], [(k, k + 1, k + 5, k + 4) for k in range(3)], Matrix.Translation((0.0, 12.0, 0.0)), wall=0.06) + CREASE = {"object_name": "Creased", "planes": json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), "standoff": 0.03, "depth": 0.08, "thickness": THICKNESS} + receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseRibs", **CREASE) + ribs = bpy.data.objects.get("CreaseRibs") + near, far, apex = 0.06 + 0.03, 0.06 + 0.03 + 0.08, facet / 2 / math.cos(turn) + area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0) + V = points(ribs) if ribs is not None else np.zeros((1, 3)) + off = core.away(V * (1.0, 0.0, 1.0), [(x, 0.0, z) for x, z in profile], False) + check("ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches", + receipt["status"] == "accepted" and child_of(ribs, creased) and (report["ribs"], report["nonManifoldEdges"], report["sections"][0]["pieces"]) == (1, 0, 1) + and reading("creased", abs(measure(ribs.data)["volume"] / THICKNESS / area - 1.0)) < CREASED and stood(creased, ribs, 0.03) < STOOD + and float(off.min()) > near - 1e-6 and float(off.max()) < far + 1e-6, [receipt["message"], report, off.min(), off.max(), R["readings"]]) + receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseFrame", **CREASE, holes=0.1, posts=0.05) + check("the creased rib takes holes along its clipped centre line, cut clean, and posts", receipt["status"] == "accepted" and (report["holes"], report["posts"], report["nonManifoldEdges"]) == (3, 11, 0), + [receipt["message"], report]) # the centre line is 0.3 + 0.048 - 0.13 tan 49.4 = 0.196 a run: 0.39 holds three holes 0.1 apart; the section, 0.662, thirteen post stations, one each side of the facet clipped + angle = mesh_object("Angle", [(x, y, z) for y in (-0.3, 0.3) for x, z in ((-0.4, 0.0), (0.0, 0.0), (0.0, -0.4))], [(0, 1, 4, 3), (1, 2, 5, 4)], Matrix.Translation((3.0, 12.0, 0.0)), wall=0.05) + receipt, report = send("brokkr_kitbash.ribs", object_name="Angle", ribs_name="AngleRibs", planes=CREASE["planes"], **SIZES, posts=0.05) + check("inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)", + receipt["status"] == "accepted" and (report["ribs"], report["posts"], report["nonManifoldEdges"]) == (1, 12, 0) and abs(report["sections"][0]["length"] - 0.8) < 1e-6, [receipt["message"], report]) + + # --- plate-window-unpinned: how deep the ray that asks "is the plate here" looks --------------------------------------------------- + section("the-plate-window") + sunk = mesh_object("Sunk", [(-0.5, -0.2, 0.0), (0.5, -0.2, 0.0), (0.5, 0.2, 0.0), (-0.5, 0.2, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 15.0, 0.0)), wall=0.05) + send("brokkr_kitbash.cut_many", object_name="Sunk", cuts=json.dumps([{"name": "Deep", "part": "box", "params": "width=0.15; height=0.15; depth=0.04", "origin": [0.0, 0.0, 2.0], + "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])) + receipt, report = send("brokkr_kitbash.ribs", object_name="Sunk", ribs_name="SunkRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES) + check("a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", + receipt["status"] == "accepted" and [(s["pieces"], s["open"]) for s in report["sections"]] == [(1, 0.0)] and abs(report["sections"][0]["length"] - 1.0) < 1e-6, [receipt["message"], report]) + tube = [(0.09 * math.cos(a), 0.09 * math.sin(a), z) for z in (0.0, 0.6) for a in (2 * math.pi * (k + 0.5) / 16 for k in range(16))] + narrow = mesh_object("Narrow", tube, [(k, (k + 1) % 16, 16 + (k + 1) % 16, 16 + k) for k in range(16)], Matrix.Translation((3.0, 15.0, 0.0)), wall=0.04) + send("brokkr_kitbash.cut_many", object_name="Narrow", cuts=json.dumps([{"name": "Slot", "part": "box", "params": "width=0.06; height=0.2; depth=0.07", "origin": [2.0, 0.0, 0.3], "direction": [-1.0, 0.0, 0.0]}])) + receipt, report = send("brokkr_kitbash.ribs", object_name="Narrow", ribs_name="NarrowRibs", planes=flat([0.3]), standoff=0.005, depth=0.015, thickness=THICKNESS) + check("a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)", + receipt["status"] == "accepted" and [(s["chains"], s["pieces"]) for s in report["sections"]] == [(1, 1)] and 0.06 < report["sections"][0]["open"] < 0.06 + 4 * 0.02 + 2 * 0.01, + [receipt["message"], report]) + # --- ribs-stop-at-ports: a flat deck with a port, a panel break and a recess along one section ---------------------------------- section("ribs-stop-at-ports") deck = mesh_object("Deck", [(-0.8, -0.5, 0.0), (0.8, -0.5, 0.0), (0.8, 0.5, 0.0), (-0.8, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 5.0, 0.0)) @ Matrix.Rotation(0.4, 4, "Y"), wall=0.05) @@ -365,7 +468,11 @@ try: refused("a plane with no normal", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5]}])}, "planes[0] must be an object of origin and normal, each three numbers") refused("a plane whose normal has no length", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 0.0]}])}, "planes[0].normal has no direction") refused("17 longerons", {**POD, "longerons": json.dumps([BEAMS[0]] * 17)}, "longerons must be a JSON array of 0 to 16 objects") - refused("a fold: ribs deeper than the pod's top turns", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section folds there: the path turns tighter than the outline reaches") + refused("ribs deeper than the pod is wide", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth") + precise = json.dumps([{"origin": [0.012345678901234567, -0.012345678901234567, 0.3 + 0.012345678901234567 * k], "normal": [1.2345678901234567e-05, -1.2345678901234567e-05, 0.99999999987654321]} for k in range(64)]) + receipt, report = send("brokkr_kitbash.ribs", **{**POD, "ribs_name": "Sixtyfour", "planes": precise}) + check("planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken", len(precise) > 9000 and receipt["status"] == "accepted" and len(report["sections"]) == 64, + [len(precise), receipt["message"]]) refused("a cage that is not a mesh", {**POD, "object_name": "Nothing"}, "No mesh object named 'Nothing'") refused("a section too long for its step", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(64)]), "step": 0.002}, "The sections are over 20000 points at step 0.002") pod.scale = (1.0, 1.0, 1.01) @@ -382,7 +489,7 @@ try: bpy.context.view_layer.update() refused("a cage with two Solidifies", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "'Crate' has 2 Solidify modifiers (Solidify, Second)") crate.modifiers.remove(extra) - check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish) for m in o.modifiers), None) + check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish, hip, creased, angle, sunk, narrow) for m in o.modifiers), None) except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:]) finally: diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index ad6e146..c9d7f01 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -17,7 +17,47 @@ "detail": null }, { - "name": "ribs-fit-the-plate: every rib vertex stands the standoff, or the standoff and the depth, behind the plate's inner face along its plane, in its plane, on the side the normals face away from", + "name": "ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from", + "ok": true, + "detail": null + }, + { + "name": "standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets", + "ok": true, + "detail": null + }, + { + "name": "where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)", + "ok": true, + "detail": null + }, + { + "name": "negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face", + "ok": true, + "detail": null + }, + { + "name": "ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches", + "ok": true, + "detail": null + }, + { + "name": "the creased rib takes holes along its clipped centre line, cut clean, and posts", + "ok": true, + "detail": null + }, + { + "name": "inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)", + "ok": true, + "detail": null + }, + { + "name": "a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)", + "ok": true, + "detail": null + }, + { + "name": "a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)", "ok": true, "detail": null }, @@ -127,7 +167,12 @@ "detail": null }, { - "name": "refused, scene unchanged: a fold: ribs deeper than the pod's top turns", + "name": "refused, scene unchanged: ribs deeper than the pod is wide", + "ok": true, + "detail": null + }, + { + "name": "planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken", "ok": true, "detail": null }, @@ -165,10 +210,13 @@ "hostErrors": [], "readings": { "cleared": 0.031, - "fit": 0.0052, + "creased": 0.0013, + "fit": 0.0011, "holed": 2.7e-08, "planar": 1.4e-07, - "stationed": 5.2e-07 + "ring": 2.1e-06, + "stationed": 5.2e-07, + "stood": 5.3e-08 }, "ok": true } \ No newline at end of file diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 675748f..b1609eb 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1166,7 +1166,7 @@ class PoseTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class StructureTests(unittest.TestCase): - """core's sweep, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is + """core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is exact arithmetic, so each assertion is the built value and names the mutant it kills.""" SQUARE = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)] BENT = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (0.2, 1.4, 0.0)] @@ -1298,22 +1298,92 @@ class StructureTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "resample"): core.resample(*bad) - def test_a_frame_is_swept_corner_to_corner(self): - """cornered keeps the points where a section turns and an open one's ends: an end is left out when the corner - beside it is nearer than that corner's mitre sets the frame's inside back.""" - el = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.25, 0.0), (1.0, 0.5, 0.0)] # a right angle at index 2: its mitre sets back the reach itself - self.assertEqual(core.cornered(el, False, 0.25).tolist(), [0, 2, 4]) - self.assertEqual(core.cornered(el, False, 0.5).tolist(), [0, 2]) # the far end stands 0.5 from the corner: not beyond a set-back of 0.5 - self.assertEqual(core.cornered(el, False, 1.0).tolist(), []) # nor does the near one, and one point is no frame - self.assertEqual(core.cornered(el[:3], False, 9.0).tolist(), [0, 2]) # no corner: both ends, whatever the reach - shallow = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 + math.cos(0.2), math.sin(0.2), 0.0)] # a turn of 0.2 rad sets back reach * tan(0.1) - self.assertEqual(core.cornered(shallow, False, 9.9).tolist(), [0, 1, 2]) - self.assertEqual(core.cornered(shallow, False, 10.0).tolist(), []) # both ends within 10 * tan(0.1) = 1.003: one point is left, and is no frame + def test_away_is_the_least_distance_to_a_polyline(self): + el = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)] + self.assertEqual(core.away([(0.5, 0.25, 0.0), (2.0, 0.0, 0.0), (-3.0, 4.0, 0.0), (0.5, 0.5, 0.0)], el, False).tolist(), [0.25, 1.0, 5.0, 0.5]) + self.assertAlmostEqual(float(core.away((0.5, 0.75, 0.0), el, True)[0]), 0.25 / math.sqrt(2.0), places=15) # closed, the segment back to the start is nearest + turns = np.linspace(0.0, 6.0 * math.pi, 400) # a spiral of 399 segments, seven blocks of them, and points all over it: a limit changes no value under it + spiral = np.stack([turns * np.cos(turns), turns * np.sin(turns), np.zeros(400)], axis=1) + spots = np.random.default_rng(7).uniform(-20.0, 20.0, (500, 3)) * (1.0, 1.0, 0.0) + lengths = np.linspace(0.0, 2.0, 399) + for closed, less in ((False, 0.0), (True, 0.0), (False, lengths), (True, np.linspace(0.0, 2.0, 400))): + every = core.away(spots, spiral, closed, less) + for limit in (0.0, 1.5): + self.assertEqual(core.away(spots, spiral, closed, less, limit).tolist(), np.minimum(every, limit).tolist()) # mutant A1 (a block's own segments only) reads the limit where another turn is nearer + self.assertTrue((every < 0.0).any() or less is 0.0) + self.assertTrue((every > 1.5).any()) + + def test_a_band_stands_beside_a_polyline_on_the_side_it_is_told(self): + """band on a straight run and on a square: the built values. A straight run is built at its two ends only; the + side comes from `inward`, whichever way the polyline runs; inside a square the far edge is clipped to the + smaller square (the points within a set-back of a corner are left out) and the volume is the ring's.""" + line, up = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)], (0.0, 0.0, 1.0) + for path in (line, line[::-1]): + for side in (1.0, -1.0): + made = core.band(path, False, up, [(0.0, side, 0.0)] * 3, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(made.shell)) + self.assertAlmostEqual(signed_volume(made.shell), 1.0 * 0.2 * 0.05, places=15) + self.assertEqual((made.at.tolist(), len(made.shell.V), len(made.shell.counts)), ([0, 2], 8, 6)) + self.assertEqual(sorted(made.outer[:, 1].tolist() + made.centre[:, 1].tolist() + made.inner[:, 1].tolist()), sorted([0.1 * side, 0.2 * side, side * (0.1 + 0.2)] * 2)) + self.assertEqual(sorted(set(np.round(made.shell.V[:, 2], 12).tolist())), [-0.025, 0.025]) square = core.resample(self.SQUARE, True, 0.25) - self.assertEqual(core.cornered(square, True, 0.1).tolist(), [0, 4, 8, 12]) - round_ = [(math.cos(a), math.sin(a), 0.0) for a in np.linspace(0.0, 2.0 * math.pi, 12, endpoint=False)] - self.assertEqual(core.cornered(round_, True, 0.1).tolist(), list(range(12))) - self.assertEqual(core.cornered(core.resample(self.SQUARE[:2] + [(0.5, 1e-13, 0.0)], True, 0.25), True, 0.1).tolist()[:1], [0]) + middle = np.array([0.5, 0.5, 0.0]) + for path in (square, square[::-1]): + inside = core.band(path, True, up, middle - path, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(inside.shell)) + self.assertAlmostEqual(signed_volume(inside.shell), (0.8 ** 2 - 0.4 ** 2) * 0.05, places=15) + self.assertEqual((len(inside.outer), len(inside.inner)), (16, 8)) # 0.25 from a corner the far edge, set back 0.3, is clipped; the near one, set back 0.1, is not + outside = core.band(path, True, up, path - middle, 0.1, 0.2, 0.05) + self.assertTrue(closed_and_oriented(outside.shell)) + self.assertAlmostEqual(signed_volume(outside.shell), (1.6 ** 2 - 1.2 ** 2) * 0.05, places=14) + self.assertEqual((len(outside.outer), len(outside.inner)), (4, 4)) + el = core.resample([(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, 0.05) # a distance for each segment: 0.1 along x, 0.3 along y, inside the right angle + two = core.band(el, False, up, [(-1.0, -1.0, 0.0)] * len(el), [0.1] * 20 + [0.3] * 20, 0.2, 0.05) + self.assertTrue(closed_and_oriented(two.shell)) + self.assertAlmostEqual(signed_volume(two.shell), (0.2 * (0.7 + 0.5) / 2.0 + 0.2 * (0.9 + 0.7) / 2.0) * 0.05, places=15) # each edge's corner stands each leg's own distance off it + self.assertIn([-0.3, -0.1, 0.0], two.outer.round(12).tolist()) + self.assertIn([-0.5, -0.3, 0.0], two.inner.round(12).tolist()) + for edge, length in ((two.outer, 0.7 + 0.9), (two.centre, 0.6 + 0.8), (two.inner, 0.5 + 0.7)): + # an edge runs once along each leg: mutant L1 (the corner the greater distance off both legs) runs 0.2 past the corner and back, mutant V1 + # (clipped at a point's own distance) runs the first leg's edge on to 0.1 from the second; mutant W1 (no weld) has the corner twice + self.assertAlmostEqual(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).sum()), length, places=12) + self.assertGreater(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).min()), 1e-9) + self.assertEqual(core.away([(-0.3, -0.1, 0.0), (-0.3, -0.3, 0.0)], [(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, [0.1, 0.3]).round(12).tolist(), [0.0, 0.0]) + with self.assertRaisesRegex(core.KitError, "path point 0: the section leaves a rib no room"): + core.band(square, True, up, middle - square, 0.1, 0.45, 0.05) # 0.55 in from a square 1 wide: nothing is that far from its sides + with self.assertRaisesRegex(core.KitError, "path point 1: the path turns 160.0 degrees there, over 150"): + core.band([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 - math.cos(math.radians(20.0)), math.sin(math.radians(20.0)), 0.0)], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05) + with self.assertRaisesRegex(core.KitError, "path point 0: the segment from it is shorter than 1e-9"): + core.band([line[0], line[0], line[2]], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05) + for bad in ((line[:1], False), (line[:2], True)): + with self.assertRaisesRegex(core.KitError, "a band needs"): + core.band(bad[0], bad[1], up, [(0.0, 1.0, 0.0)] * len(bad[0]), 0.1, 0.2, 0.05) + + # What a band inside a crease holds, over the area of the true clipped offset, less 1. Bound by + # lodur:ruling:deterministic-bound-margin: shipped 0.0013 (each clipped corner is cut by a chord between points + # 0.01 apart); least claimed mutant 0.079 (C1, nothing clipped: both edges fold through the crease); separation 7.9. + CREASED = 0.0099 + + def test_a_band_follows_a_crease_tighter_than_it_reaches(self): + """ribs-fold-at-crease. Two runs of 0.3 that turn 49.4 degrees at each end of a facet of 0.062, as a creased + shell's section does, and a rib from 0.09 to 0.17 inside the turn: both of the facet's offsets are gone (each + end sets them back 0.041 and 0.078), so each edge is the two runs' offsets, met at one corner. No vertex + stands nearer the section than 0.09 or further than 0.17. Mutant C1 reads 0.079 and stands 0.07 off.""" + turn, facet, run, near, far = math.radians(49.4), 0.062, 0.3, 0.09, 0.17 + section = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn), 0.0), (-facet / 2, 0.0, 0.0), (facet / 2, 0.0, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn), 0.0)] + dense = core.resample(section, False, 0.01) + made = core.band(dense, False, (0.0, 0.0, 1.0), [(0.0, -1.0, 0.0)] * len(dense), near, far - near, 0.014) + self.assertTrue(closed_and_oriented(made.shell)) + apex = facet / 2 / math.cos(turn) # from each end of the facet to where the two runs' lines meet + area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0) + self.assertLess(abs(signed_volume(made.shell) / 0.014 / area - 1.0), self.CREASED) + off = core.away(made.shell.V * (1.0, 1.0, 0.0), section, False) + self.assertGreaterEqual(float(off.min()), near - 1e-15) + self.assertLessEqual(float(off.max()), far + 1e-15) + self.assertEqual((len(made.outer), len(made.centre), len(made.inner)), (12, 8, 4)) # the far edge: an end, the last point before the corner, the first after, an end; the centre line and the near edge also where the edges further in start and stop being clipped + middle = core.away(made.centre, section, False) + self.assertAlmostEqual(float(middle.min()), (near + far) / 2.0, places=15) # the centre line stands half a depth off both edges, so a hole of radius 0.3 of depth on it stays in the rib + self.assertAlmostEqual(float(middle.max()), (near + far) / 2.0, places=15) def test_spans_bridge_a_break_and_stand_clear_of_a_port(self): """spans. Twenty points 0.25 apart, a bridge of 1.25 and a clearance of 0.5. Mutants K5 (bridge ignored: the two-point break splits the run) and K6 @@ -1419,6 +1489,20 @@ class HostFileTests(unittest.TestCase): for row in self.document["actions"][4:]: self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"]) + def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self): + """planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of + them are 11.3 KB and 16 longerons 4.2 KB, each under its cap; the 65th and 17th are the action's to refuse.""" + host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] + long = [-1.2345678901234567e-05] * 3 + planes, longerons = json.dumps([{"origin": long, "normal": long}] * 64), json.dumps([{"origin": long, "axis": long, "toward": long}] * 16) + self.assertEqual((len(planes), len(longerons)), (11264, 4176)) + intent = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.ribs", "object_name": "Pod", + "ribs_name": "Ribs", "planes": planes, "longerons": longerons} + self.assertEqual(at.validate(intent, host)["planes"], planes) + for field, cap in (("planes", 16000), ("longerons", 8000)): + with self.assertRaisesRegex(Exception, f"{field} must have at most {cap} characters"): + at.validate({**intent, field: "[" + " " * cap}, host) + def test_the_pose_rows_take_scalars_inside_their_bounds(self): host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]] envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "object_name": "Strut"}