From c4717c92930f4076ab766a11cf0bc34afaa6e3d3 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 10:29:17 +0100 Subject: [PATCH] brokkr_kitbash.ribs: the rib's edge cut from the inner face offset inward, the plate's faces read from its Solidify, posts kept under the outer face The standoff held only where the plate's lean was constant across the rib's reach: laid off along the plane from each segment's own lean, it fell short under a tilted plane (0.007 of 0.04 on a 24-sided prism) and on a doubly curved wall (0.020 on a sphere), and at radius 0.6 with a standoff of 0.01 the rib stood through the inner face (finding cut-kit-ribs.s2.standoff-curved-and-tilted). - core.inset: the step that takes each vertex of a mesh behind every face it is a corner of, the mitre of its faces moved in. ribs offsets the plate's inner face by the standoff with it. - A rib's outer edge is where its plane cuts that offset surface: points along the section look square in for it, corners go where the offset faces meet, and points that measure nearer the plate than the standoff (the offset surface folded) are left out. core.band then lays off only the rib's half thickness and its depth. - The finished edge is measured against the inner face and moved in until no vertex is nearer than the standoff; a rib that cannot be stood off is refused. - The plate's two faces are read from the Solidify as Blender evaluates it, so a Solidify that is not even (Blender's default) gives the plate it makes, 0.0424 beside a right angle for 0.06 (finding solidify-default-unbounded). A Solidify whose faces cannot be read is refused. - A post starts inside the plate, deeper where it leans, and its pad lies flat on the inner face. - tests/live/kitbash_ribs.py: a tilted plane through a prism, spheres of radius 1 and 0.6 at 60 degrees, a box with the default Solidify, posts under the outer face, a shallow rib in a crease; bounds by lodur:ruling:deterministic-bound-margin, RING now set from L1 (finding ring-bound-misses-l1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 153 +++++++++++++++--- .../brokkr_kitbash/brokkr_actions.json | 2 +- surfaces/blender/brokkr_kitbash/core.py | 36 ++++- surfaces/blender/tests/live/kitbash_ribs.py | 121 +++++++++++--- .../tests/live/kitbash_ribs.result.json | 47 +++++- surfaces/blender/tests/test_kitbash.py | 24 ++- 6 files changed, 338 insertions(+), 45 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 26465a7..22b2c3d 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -895,6 +895,10 @@ SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surf LIFT = 0.01 # metres outside the plate's outer face that the ray asking "is the plate here" starts NUDGE = 1e-4 # metres along the section that ray is moved off its point: a section's corners lie on the cage's edges, and a ray along an edge can slip between two faces HOLE_SEGMENTS, POST_SEGMENTS, PAD_SEGMENTS = 16, 8, 12 +STANDOFF_CLIP = 1e-6 # of the standoff: a point of the offset surface that stands this much nearer the plate than the standoff is where the surface folded, and is left out +STANDOFF_HELD = 1e-7 # metres inside the standoff that a rib's edge may measure and hold it: what a float32 tree's distances are good to +STANDOFF_ROUNDS = 8 # times a rib's edge is measured against the plate and moved in by what it is short +POST_SUNK = 0.5 # of the plate's thickness: how far under the outer face a post starts # What a plane's lightening holes removed from its webs, over the holes' faceted area times the rib's thickness, less 1. # Bound by lodur:ruling:deterministic-bound-margin: shipped worst 2.9e-06 (tests/live/kitbash_ribs.py: thirteen planes # on a pod, a deck and an egg-crate, float32 meshes); least claimed bad cut 0.0066 (holes of radius 0.018 pitched 0.02, @@ -948,7 +952,7 @@ def along(points, closed: bool, pitch: float): than a pitch), evenly round a closed one: [(point, segment index, fraction along the segment)].""" loop = np.vstack([points, points[:1]]) if closed else points reach = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(loop, axis=0), axis=1))]) - count = int(reach[-1] / pitch + 1e-9) + count = int(reach[-1] / pitch + 1e-6) # a length that is a whole number of pitches but for a float32's rounding holds them all found = [] for at in (reach[-1] * np.arange(count) / max(count, 1) if closed else pitch / 2 + pitch * np.arange(count)): segment = min(int(np.searchsorted(reach, at, side="right")) - 1, len(loop) - 2) @@ -1025,6 +1029,34 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): surface.from_mesh(designed.to_mesh()) designed.to_mesh_clear() nearest = BVHTree.FromBMesh(surface) + at = np.array([v.co for v in surface.verts], dtype=np.float64).reshape(-1, 3) + polygons = [tuple(v.index for v in face.verts) for face in surface.faces] + inner_at = outer_at = at + if walls: # the plate's two faces as its Solidify makes them, whatever its thickness mode: a simple Solidify writes the surface's vertices twice, in the surface's order + walls[0].show_viewport = True + _, walled = evaluated_of(context, cage) + wall = walled.to_mesh() + both = np.zeros(3 * len(wall.vertices)) + wall.vertices.foreach_get("co", both) + walled.to_mesh_clear() + walls[0].show_viewport = False + if len(both) != 6 * len(at): + raise Refused(f"{cage.name!r}'s Solidify {walls[0].name!r} does not make the plate's two faces from the surface's own vertices ({len(both) // 3} vertices from {len(at)}): " + "ribs reads the plate from a simple Solidify with nothing after it but Bevel and Booleans; nothing changed.") + both = both.reshape(2, -1, 3).astype(np.float64) + out_of = [float(np.einsum("ij,ij->", face - at, np.array([v.normal for v in surface.verts]))) for face in both] # the inner face is the one further against the normals + inner_at, outer_at = (both[0], both[1]) if out_of[0] < out_of[1] else (both[1], both[0]) + skin = BVHTree.FromPolygons(inner_at.tolist(), polygons) # the plate's inner face: what the standoff is measured from + hide = BVHTree.FromPolygons(outer_at.tolist(), polygons) if self.posts > 0 else None # its outer face: what no post may stand through + # The inner face offset inward by the standoff, along its own faces' normals: a rib's outer edge is cut from this, so it + # stands the standoff off the plate at any tilt of its plane and any curvature of the wall. + offset = BVHTree.FromPolygons((inner_at + self.standoff * core.inset(inner_at, polygons)).tolist(), polygons) + clip = STANDOFF_CLIP * self.standoff + 1e-7 # and what a float32 tree's distances are good to + + def short(points) -> float: + """How far the nearest of some points comes inside the standoff: over 0, too near the plate.""" + return self.standoff - min(skin.find_nearest(Vector(point))[3] for point in points) + for index, plane in enumerate(planes): where, normal = f"planes[{index}]", plane["normal"] cut = surface.copy() @@ -1044,16 +1076,14 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): 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) 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)) + out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at_points], dtype=np.float64) for at_points in (P, between)) flat = out - normal * (out @ normal)[:, None] 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 + inward = -flat / np.linalg.norm(flat, axis=1)[:, None] # square in from the plate, along the plane + beside = (lambda of: np.maximum(of, np.roll(of, 1))) if closed else (lambda of: np.maximum(np.concatenate([of, of[-1:]]), np.concatenate([of[:1], of]))) # a point's greater of its two segments' + slope = beside(1.0 / 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(): @@ -1061,17 +1091,83 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): "recalculate its normals so they all face out of the plate; nothing changed.") 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 + # Where the offset surface stands behind each point of the section, square in along the plane: a point of the rib's + # edge. One that stands nearer the plate than the standoff landed where the offset surface has passed through itself, + # behind a corner of the section or inside a curve tighter than the standoff: it is left out. The rib's edge on + # the side the plate leans over is half a thickness nearer the plate than its middle, which the offset surface was + # cut at: along the plane that is `leaned`, from the lean of the offset face the point landed on. + edge, near, leaned, landed, steep = np.zeros_like(P), np.full(len(P), np.inf), np.zeros(len(P)), np.zeros_like(P), np.ones(len(P)) + for k, (p, n) in enumerate(zip(P, inward)): + for start in (p, p + aside[k]): # a ray along the offset surface's own rim can slip past it: an end of the section looks again from just inside + hit = offset.ray_cast(Vector(start - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * slope[k] + 2.0) + 1e-3) + if hit[0] is not None: + break + if hit[0] is not None: + tilt = min(abs(float(np.array(hit[1]) @ normal)), 1.0 - 1e-6) + steep[k] = 1.0 / math.sqrt(1.0 - tilt * tilt) # along the plane, over along the normal, where the point landed: the offset surface leans more than the plate where the wall is round + edge[k], near[k], landed[k], leaned[k] = p + n * (hit[3] - 1e-5), short([hit[0]]), hit[1], self.thickness / 2.0 * tilt * steep[k] # the point itself moved along its way: the tree's own point is a float32 + + def met(a, b): + """The edge's corner between two of its points that landed on different faces of the offset surface: where + those faces' lines in the plane meet. None where they do not meet between the two points, or meet nearer + the plate than the standoff (faces either side of a fold).""" + ways = np.stack([np.cross(normal, landed[a]), -np.cross(normal, landed[b])], axis=1) + (s, t), _, rank, _ = np.linalg.lstsq(ways, edge[b] - edge[a], rcond=None) + corner, apart = edge[a] + s * ways[:, 0], edge[b] - edge[a] + if (rank == 2 and np.linalg.norm(corner - (edge[b] - t * ways[:, 1])) < 1e-6 and 0.0 < (corner - edge[a]) @ apart < apart @ apart + and np.linalg.norm(corner - edge[a]) < 4.0 * np.linalg.norm(apart) + self.step and short([corner]) <= clip): + return corner + return None + 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 * (np.resize(back, len(P)) + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it + row["lines"].append((P + inward * ((inner + self.standoff) * slope + 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) - try: - 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 - 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]]}) + kept = piece[near[piece] <= clip] + if len(kept) < (3 if ring else 2): + raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.") + node = lambda k: [edge[k], inward[k], steep[k], leaned[k], False, ahead[k]] # noqa: E731 a point of the edge: where, which way in, its slope, its lean, whether it is a corner, and the section's way there + nodes = [] + for k in range(len(kept) if ring else len(kept) - 1): + a, b = kept[k], kept[(k + 1) % len(kept)] + nodes.append(node(a)) + corner = met(a, b) if np.abs(landed[a] - landed[b]).max() > 1e-6 else None # the rays only sample the edge: its corners are the offset surface's own + if corner is not None: + nodes.append([corner, (inward[a] + inward[b]) / np.linalg.norm(inward[a] + inward[b]), max(steep[a], steep[b]), max(leaned[a], leaned[b]), True, ahead[a] + ahead[b]]) + if not ring: + nodes.append(node(kept[-1])) + run = nodes[:1] + onward = lambda u, v: (v[0] - u[0]) @ v[5] > 1e-5 * np.linalg.norm(v[5]) # noqa: E731 v stands on from u the way the section runs, by more than a hundredth of a millimetre + for here in nodes[1:]: # an edge that steps back against its section has folded there: the point that did it is left out + if onward(run[-1], here): + run.append(here) + while ring and len(run) > 3 and not onward(run[-1], run[0]): + run.pop() + if len(run) < (3 if ring else 2): + raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.") + Q, into = (np.array([here[field] for here in run]) for field in (0, 1)) + # a segment's half thickness is laid off by its own wall's lean: beside a corner, the lean of its end that is no corner + back = np.array([v[3] if u[4] and not v[4] else u[3] if v[4] and not u[4] else max(u[3], v[3]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])]) + grade, more, gain, lack = np.array([max(u[2], v[2]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])]), 0.0, 1.0, 0.0 + for _ in range(STANDOFF_ROUNDS): + # What is left is of the second order (half a thickness laid off along the plane beside a curved or tilted + # wall, a chord across a facet): measured on the rib's own edge, and the edge moved in by what it is short. + try: + rib = core.band(Q, ring, normal, into, back + more * grade, self.depth, self.thickness) + except core.KitError as error: + raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None + before, lack = lack, short(rib.shell.V[:2 * len(rib.outer)]) + if lack <= STANDOFF_HELD: + break + if lack < before: # the last move closed this much of what was short: the next is sized by it (a steep wall gives back less than it is given) + gain = min(gain * before / (before - lack), 8.0) + more += 1.05 * gain * lack + STANDOFF_HELD + else: + raise Refused(f"{where}: a rib there cannot be stood {self.standoff:.6g} off the plate (it comes {lack:.3g} too near where the wall turns): lower standoff or thickness; nothing changed.") + row["ribs"].append({"band": rib, "ring": ring, "inward": into, "edge": Q, "back": back + more * grade, "section": P[piece], "into": inward[piece], + "slope": slope[piece]}) 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.shell)) @@ -1082,15 +1178,34 @@ class BROKKR_KITBASH_OT_ribs(PolishOperator): 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 rib in row["ribs"] if self.posts > 0 else (): - P, up = rib["P"], planes[row["plane"]]["normal"] + P, up = rib["section"], 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 = rib["into"][segment] + (rib["into"][(segment + 1) % len(P)] - rib["into"][segment]) * fraction 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 + grade = max(rib["slope"][segment], rib["slope"][(segment + 1) % len(P)]) + hit = offset.ray_cast(Vector(point - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * grade + 2.0) + 1e-3)[3] + if hit is None: 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)) + foot = point + n * (hit - 1e-5 + float(rib["back"].max()) + 0.3 * self.depth) + if short([foot]) > clip or core.away(foot, rib["edge"], rib["ring"], rib["back"])[0] < -1e-9: # inside a turn the rib was clipped at: a post there would end outside it + continue + # A post starts inside the plate, midway between its faces where it stands, and deeper where it leans: its end, + # a disc across its own line, must stay under the outer face. + (face, normal, _, _), under = nearest.find_nearest(Vector(point)), skin.find_nearest(Vector(point))[0] + top = np.array(hide.find_nearest(Vector(point))[0]) + normal, thick = np.array(normal), float(np.linalg.norm(top - np.array(under))) + line = foot - (top + np.array(under)) / 2.0 + line = line / np.linalg.norm(line) + proud = self.post_r * math.sqrt(max(0.0, 1.0 - float(line @ normal) ** 2)) # how far the end's rim stands out of its middle, toward the outer face + sunk = min(thick, max(thick * POST_SUNK, 1.5 * proud)) + if thick > 0.0 and proud >= sunk: + continue # a plate thinner than the post's end leans: no post there + start = top - normal * sunk + across = np.cross(normal, up) + pad = skin.ray_cast(Vector(start), Vector(foot - start), float(np.linalg.norm(foot - start)))[0] + pad = np.array(pad if pad is not None else under) + rods.append(core.sweep([start, foot], core.circle(self.post_r, POST_SEGMENTS), across)) + rods.append(core.sweep([pad, pad - normal * self.post_r], core.circle(2.4 * self.post_r, PAD_SEGMENTS), across)) for index, longeron in enumerate(longerons): where, stations, ups = f"longerons[{index}]", [], [] for row in sections: diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index d2906e9..f663d11 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 (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.", + "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, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) 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 two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. 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", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index cce0f57..6e3b6ef 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -20,7 +20,8 @@ whatever the roll: what closes a loop the tree of connections cannot state. 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 +clips it), inset is the step that offsets a mesh inward by its own faces (the surface a rib's edge is cut from), 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. @@ -756,6 +757,39 @@ def resample(points, closed: bool, step: float) -> np.ndarray: return np.array(made if closed else made + [loop[-1]]) +INSET_RANK = 2.5e-3 # of a vertex's face normals, as eigenvalues of their sum of squares: a direction they span by under 0.05 of the widest is not solved for + + +def inset(V, faces) -> np.ndarray: + """For each vertex of a mesh, the step that takes it one unit behind the plane of every face it is a corner of, + against the faces' normals (a face's normal is its winding's, counter-clockwise seen from outside): the mitre of + those planes moved in by 1. `V + d * inset(V, faces)`, with the same faces, is the surface offset inward by d. A + flat or smooth vertex steps along its normal; a crease's or a corner's steps to where its faces' offsets meet, + exactly where they meet in a point or a line. Where no step holds every face's distance (four faces that do not + share a point), the least-squares step is lengthened until the nearest face's plane stands 1 off: further than + asked from the others, never nearer. `faces` is a list of index tuples. A vertex of no face, or of faces that + fold back on each other, steps nowhere.""" + V = np.asarray(V, dtype=np.float64).reshape(-1, 3) + corners = np.fromiter((v for face in faces for v in face), dtype=np.int64) + counts = np.fromiter((len(face) for face in faces), dtype=np.int64, count=len(faces)) + owner, first = np.repeat(np.arange(len(faces)), counts), np.concatenate([[0], np.cumsum(counts)[:-1]]) + ahead = np.arange(len(corners)) + 1 + ahead[first + counts - 1] = first # the next corner round each face + normals = np.zeros((len(faces), 3)) + np.add.at(normals, owner, np.cross(V[corners], V[corners[ahead]])) # Newell: twice the face's area along its normal + size = np.linalg.norm(normals, axis=1) + normals = normals / np.maximum(size, 1e-300)[:, None] + n = normals[owner] * (size[owner] > 0)[:, None] # a corner's face normal; a face of no area asks nothing + squares, wanted = np.zeros((len(V), 3, 3)), np.zeros((len(V), 3)) + np.add.at(squares, corners, n[:, :, None] * n[:, None, :]) + np.add.at(wanted, corners, -n) + step = np.einsum("vij,vj->vi", np.linalg.pinv(squares, rcond=INSET_RANK, hermitian=True), wanted) + behind = np.full(len(V), np.inf) + np.minimum.at(behind, corners, np.where(size[owner] > 0, -np.einsum("ij,ij->i", n, step[corners]), np.inf)) # how far behind its nearest face's plane the step ends + held = np.isfinite(behind) & (behind > 1e-6) + return np.where(held[:, None], step / np.where(held, behind, 1.0)[:, None], 0.0) + + 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 diff --git a/surfaces/blender/tests/live/kitbash_ribs.py b/surfaces/blender/tests/live/kitbash_ribs.py index 3446c07..4793887 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.py +++ b/surfaces/blender/tests/live/kitbash_ribs.py @@ -62,23 +62,39 @@ COUNT, SECTION = [0], ["setup"] STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014 SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS} # 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 +# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 7.5e-05 (the edge is +# moved in by one distance for the whole rib, what its nearest vertex was short); least claimed mutant 0.00081 (O2, the +# rib's half thickness, which a leaning plate comes nearer, left out of the edge: the measure then moves the whole rib); +# the geometric mean, separation 3.3 each side. U1 reads 0.00017 and M2 0.00013 and die at STOOD and RING; S1 0.025. +FIT = 2.5e-4 # 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 +# cylinder whose Solidify is negative, a hipped box, a crease and a dish. Shipped worst 6.4e-08 (float32 meshes); least +# claimed mutant 0.0003 (O2 at 60 degrees); the geometric mean, separation 68 each side. U1 (every Solidify read as not +# even) reads 0.00051, V1 0.003, S1 (the plate's outer face taken for its inner) 0.032. +STOOD = 4.4e-6 # 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 +# least claimed mutant 1.8e-05 (L1, a corner of two distances never mitred); the geometric mean, separation 2.9 each side. +# M2 (the edge's corners left as chords) reads 0.00047, O2 0.0017. +RING = 6.1e-6 +# A rib inside a crease, over the true clipped offset's area times the thickness, less 1. Shipped 2.3e-07 (the edge's +# corner is where the offset faces meet); least claimed mutant 0.00051 (M2, a chord across it); the geometric mean, +# separation 47 each side. U2 reads 0.0014, U1 0.031, A2 (an end of the section that finds no offset surface) 0.051, X1 +# (nothing left out where the offset surface folded) 0.07. tests/test_kitbash.py CREASED is core.band's own, on the same polyline. +CREASED = 1.1e-5 +# Metres between the standoff and how near the rib comes to the plate where a plane tilted 64 degrees cuts a prism of 24 +# flat sides. Shipped 2.1e-05 (one move for the whole rib, 0.0006 along the plane); least claimed mutant 5.5e-05 (V1, an +# offset clipped at its own distance); the geometric mean, separation 1.6 each side. U1 reads 0.00014, O2 0.00032, E1 +# (the edge never measured against the plate and moved in) 0.00059, G1 0.037. Before cut-kit-ribs.h3 it read 0.007. +TILTED = 3.4e-5 +# The same on spheres of radius 1 and 0.6 cut 60 degrees off their middle, standoffs 0.04 and 0.01. Shipped worst 9.7e-08; +# least claimed mutant 5.9e-07 (U2, every Solidify read as even: an icosphere's faces meet at unequal angles); the +# geometric mean, separation 2.5 each side. C1 reads 1.5e-05, U1 5.6e-05, O2 0.00016, E1 0.0014, G1 0.024. Before +# cut-kit-ribs.h3 they read 0.020, and at radius 0.6 and standoff 0.01 the rib stood 0.006 through the inner face. +ROUND = 2.4e-7 +# The same on a box whose Solidify is not even (Blender's default). Shipped 8.3e-09; least claimed mutant 0.018 (U2, the +# plate read as its Solidify's thickness behind every face, as before cut-kit-ribs.h3); the geometric mean, separation +# 1500 each side. S1 reads 0.038. +UNEVEN = 1.2e-5 # 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 @@ -94,6 +110,11 @@ STATIONED = 3.3e-5 # Shipped 2.7e-08; least claimed mutant 22 (K11, each plane's Manifold Boolean taken over all five ribs' webs, which # cross, with the action's own check of the cut off); separation 28000 each side. HOLED = 7.7e-4 +# Metres under the plate's outer face that the nearest vertex of a frame stands: the least is the worst, and under 0 a post is +# through the plate. Shipped worst 0.0047 (the rim of a post's end on a cone leaning 60 degrees whose wall is 0.02); least +# claimed mutant 0.0015 (P2, every post started a tenth of the plate under its outer face); the geometric mean, +# separation 1.8 each side. P3 (a leaning post not started deeper) reads 0.00013; S1 and G1 put vertices outside: -0.01. +SUNK = 0.0027 def check(name, ok, detail=None): @@ -284,10 +305,18 @@ try: 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): + def stood(cage, ribs, standoff=STANDOFF, name="stood"): """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)) + return reading(name, abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff)) + + def under(cage, ribs): + """How far under the cage's outer face (its designed surface: every wall here grows inward) the frame's nearest vertex stands: under 0, a vertex is outside the plate.""" + outer, worst = tree(cage, ("SOLIDIFY", "BEVEL", "BOOLEAN")), 1.0 + for v in points(ribs): + on, normal, _, _ = outer.find_nearest(Vector(v)) + worst = min(worst, -(Vector(v) - on).dot(normal)) + return reading("sunk", worst, least=True) leaned = [] for k, lean in enumerate((0, 30, 45, 60)): @@ -336,6 +365,9 @@ try: 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) + _, shallow = send("brokkr_kitbash.ribs", ribs_name="CreaseShallow", **{**CREASE, "depth": 0.02}, posts=0.05) + check("a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)", + shallow is not None and (shallow["posts"], shallow["nonManifoldEdges"]) == (10, 0), shallow) 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) @@ -343,6 +375,47 @@ try: 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]) + # --- standoff-curved-and-tilted: the standoff where the plate's lean changes across the rib's reach -------------------------------- + section("standoff-curved-and-tilted") + prism = mesh_object("Prism", [(0.6 * math.cos(a), 0.6 * math.sin(a), z) for z in (-1.0, 2.0) for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))], + [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation((18.0, 9.0, 0.0)), wall=0.06) + receipt, report = send("brokkr_kitbash.ribs", object_name="Prism", ribs_name="PrismRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.9, 0.436]}]), **SIZES) + ribs = bpy.data.objects.get("PrismRibs") + check("a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)", + receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(prism, ribs, STANDOFF, "tilted") < TILTED, [receipt["message"], report, R["readings"]]) + + def ball(name, radius, at): + made = bmesh.new() + bmesh.ops.create_icosphere(made, subdivisions=5, radius=radius) + vertices, faces = [tuple(v.co) for v in made.verts], [tuple(v.index for v in f.verts) for f in made.faces] + made.free() + return mesh_object(name, vertices, faces, Matrix.Translation(at), wall=0.06) + + rounds = [] + for k, (radius, standoff, depth) in enumerate(((1.0, 0.04, 0.06), (1.0, 0.01, 0.06), (0.6, 0.01, 0.03))): + sphere = ball(f"Ball{k}", radius, (3.0 * k, 18.0, 0.0)) + ROUND_RIB = {"object_name": sphere.name, "planes": flat([radius * math.sin(math.radians(60))]), "standoff": standoff, "depth": depth, "thickness": THICKNESS} + receipt, report = send("brokkr_kitbash.ribs", ribs_name=f"BallRibs{k}", **ROUND_RIB) + _, posted = send("brokkr_kitbash.ribs", ribs_name=f"BallPosts{k}", **ROUND_RIB, posts=0.2) + ribs, frame = bpy.data.objects.get(f"BallRibs{k}"), bpy.data.objects.get(f"BallPosts{k}") + rounds.append(receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(sphere, ribs, standoff, "round") < ROUND + and posted is not None and posted["posts"] > 3 and under(sphere, frame) > SUNK) + check("spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it " + "(the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)", rounds == [True] * 3, [rounds, R["readings"]]) + ball("Ball3", 0.6, (9.0, 18.0, 0.0)) + refused("at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle", + {"object_name": "Ball3", "ribs_name": "BallRibs3", "planes": flat([0.6 * math.sin(math.radians(60))]), "standoff": 0.04, "depth": 0.03, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room") + tight = ball("Tight", 0.15, (15.0, 18.0, 0.0)) + refused("a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere", {"object_name": "Tight", "ribs_name": "TightRibs", "planes": flat([0.0]), "standoff": 0.12, + "depth": 0.02, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room") + plain = mesh_object("Plain", [(sx * 0.5, sy * 0.5, 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((21.0, 9.0, 0.0)), wall=0.06) + plain.modifiers["Solidify"].use_even_offset = False # Blender's default: each vertex 0.06 along its own normal, so the plate is 0.0424 thick beside a right angle + bpy.context.view_layer.update() + receipt, report = send("brokkr_kitbash.ribs", object_name="Plain", ribs_name="PlainRibs", planes=flat([0.5]), **SIZES) + check("solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)", + receipt["status"] == "accepted" and report["thickness"] == 0.06 and stood(plain, bpy.data.objects["PlainRibs"], STANDOFF, "uneven") < UNEVEN, [receipt["message"], report, R["readings"]]) + # --- 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) @@ -395,7 +468,7 @@ try: from_axis = np.hypot(points(ribs)[:, 0], points(ribs)[:, 2] - 1.0) if ribs is not None else np.zeros(1) check("ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness", receipt["status"] == "accepted" and up_facing and report["thickness"] == 0.0 and report["ribs"] == 1 and report["sections"][0]["open"] == 0.0 - and abs(float(from_axis.min()) - (1.0 + STANDOFF)) < 1e-3 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max()]) + and stood(dish, ribs) < STOOD and float(from_axis.min()) > 1.0 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max(), R["readings"]]) for polygon in list(dish.data.polygons)[:4]: polygon.flip() dish.data.update() @@ -440,6 +513,18 @@ try: and (report["ribs"], len(report["longerons"]), report["nonManifoldEdges"]) == (5, 4, 0) and report["posts"] > 40 and report["holes"] > 80 and all(len(r["stations"]) == 5 for r in report["longerons"]), [receipt["message"], report]) + # --- posts-under-the-plate ---------------------------------------------------------------------------------------------------------- + section("posts-under-the-plate") + receipt, report = send("brokkr_kitbash.ribs", object_name="Cone60", ribs_name="ConePosts", planes=flat([0.5]), **SIZES, posts=0.2) + thin = frustum("Thin", 60, (24.0, 9.0, 0.0)) + thin.modifiers["Solidify"].thickness = 0.02 # thinner than a post's end leans out of its middle, twice over + bpy.context.view_layer.update() + _, leaning = send("brokkr_kitbash.ribs", object_name="Thin", ribs_name="ThinPosts", planes=flat([0.5]), **SIZES, posts=0.2) + depths = [under(cage, bpy.data.objects[name]) for cage, name in ((deck, "DeckRibs"), (creased, "CreaseFrame"), (angle, "AngleRibs"), (pod, "Frame"), (bpy.data.objects["Cone60"], "ConePosts"), (thin, "ThinPosts"))] + check("posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: " + "a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)", receipt["status"] == "accepted" and report["posts"] > 10 and leaning is not None and leaning["posts"] > 10 and min(depths) > SUNK + and abs(depths[0] - 0.025) < 1e-6, [receipt["message"], depths, R["readings"]]) + # --- holes-manifold: an egg-crate of five ribs that cross --------------------------------------------------------------------- section("holes-manifold") crate = mesh_object("Crate", [(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, -5.0, 0.0)), wall=0.05) diff --git a/surfaces/blender/tests/live/kitbash_ribs.result.json b/surfaces/blender/tests/live/kitbash_ribs.result.json index c9d7f01..302a69f 100644 --- a/surfaces/blender/tests/live/kitbash_ribs.result.json +++ b/surfaces/blender/tests/live/kitbash_ribs.result.json @@ -41,6 +41,11 @@ "ok": true, "detail": null }, + { + "name": "a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)", + "ok": true, + "detail": null + }, { "name": "the creased rib takes holes along its clipped centre line, cut clean, and posts", "ok": true, @@ -51,6 +56,31 @@ "ok": true, "detail": null }, + { + "name": "a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)", + "ok": true, + "detail": null + }, + { + "name": "spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it (the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere", + "ok": true, + "detail": null + }, + { + "name": "solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)", + "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, @@ -116,6 +146,11 @@ "ok": true, "detail": null }, + { + "name": "posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)", + "ok": true, + "detail": null + }, { "name": "holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own", "ok": true, @@ -210,13 +245,17 @@ "hostErrors": [], "readings": { "cleared": 0.031, - "creased": 0.0013, - "fit": 0.0011, - "holed": 2.7e-08, + "creased": 2.3e-07, + "fit": 7.5e-05, + "holed": 5.5e-08, "planar": 1.4e-07, "ring": 2.1e-06, + "round": 9.7e-08, "stationed": 5.2e-07, - "stood": 5.3e-08 + "stood": 6.4e-08, + "sunk": 0.0047, + "tilted": 2.1e-05, + "uneven": 8.3e-09 }, "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 b1609eb..c03845a 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -1283,6 +1283,26 @@ class StructureTests(unittest.TestCase): with self.assertRaisesRegex(core.KitError, "runs along the axis"): core.crossings(chain, True, origin, axis, (0.0, 0.0, 2.0)) + def test_inset_steps_each_vertex_behind_every_face_it_is_a_corner_of(self): + """A flat vertex steps along its normal, a crease's to where its two faces' offsets meet, a corner's to where three do; four faces that share no + point are each held at least 1 off (mutant I1, a step along the mean normal, leaves a crease's faces cos 45 off).""" + cube = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)] + faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] # wound outward + self.assertTrue(np.allclose(core.inset(cube, faces), [[1.0 - 2.0 * v for v in corner] for corner in cube], atol=1e-12)) # every corner toward the middle, 1 behind each of its three faces + self.assertTrue(np.allclose(core.inset(cube, faces[:1]), [[0.0, 0.0, 1.0]] * 4 + [[0.0, 0.0, 0.0]] * 4, atol=1e-12)) # one face: along its normal's back; a vertex of no face, nowhere + self.assertTrue(np.allclose(core.inset(cube, faces[2:4])[[1, 5]], [[-1.0, 1.0, 0.0]] * 2, atol=1e-12)) # a right-angle crease: its mitre, root 2 long + lean = math.tan(math.radians(20.0)) + hip = [(sx * (1.0 + z), sy * (1.0 + z * lean), z) for z in (0.0, 1.0) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))] # walls that lean 45 and 20 degrees + walls = [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)] + step, normals = core.inset(hip, walls), [np.array(n) / np.linalg.norm(n) for n in ((1.0, 0.0, -1.0), (0.0, 1.0, -lean), (-1.0, 0.0, -1.0), (0.0, -1.0, -lean))] + for face, normal in zip(walls, normals): + self.assertTrue(np.allclose(step[list(face)] @ normal, -1.0, atol=1e-12)) # unequal leans: still exactly 1 behind both walls + spire = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 0.3), (0.4, 0.0, 0.0)] + sides = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 5, 4), (5, 0, 4)] # five faces round an apex that share no point once moved + behind = [-(core.inset(spire, sides)[4] @ (np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a])) / np.linalg.norm(np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a]))))) + for a, b, c in sides] + self.assertTrue(1.0 - 1e-9 < min(behind) < 1.0 + 1e-9 and max(behind) < 2.0, behind) # the nearest face 1 off, the others further, never nearer + def test_resample_keeps_every_corner_and_fills_between(self): """A corner stays a point of the chain, and no two points stand over the step apart.""" line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.5, 0.0)], False, 0.3) @@ -1561,7 +1581,7 @@ class OwnershipTests(unittest.TestCase): self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0]) bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]} self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"]) - self.assertEqual(source.count("evaluated_of("), 6) # its def, evaluable, boolean, apply, and ribs for the designed surface and for its holes + self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0]) place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0)) @@ -1579,7 +1599,7 @@ class OwnershipTests(unittest.TestCase): for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))): self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean self.assertEqual(body.count("place_cutters("), 0 if body is place else 1) - self.assertEqual(source.count("to_mesh("), 3) # boolean's report, and in ribs the designed surface and the holed webs + self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs def test_only_ribs_writes_kit_ribs(self): """kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to