From d1d0dc7605fcb10ba5eed34644a11519ee134c30 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 18:56:56 +0100 Subject: [PATCH 1/5] brokkr_kitbash: sharp lathe points; a flat profile is refused to a tolerance; pins for the lip and the apply clamp A lathe profile point may be [r, z, "sharp"]: Built.sharp lists the ring edges of the marked points in every copy, and write_mesh sets sharp_edge on exactly those edges. check_kit refuses any other third item, a fourth, and a mark at an open profile's end. The reducer's two cone rings are sharp. _lathe refuses a closing area at or below FLAT (5.1e-10) of the square of the profile's largest coordinate, so a constant-z profile is refused whatever its digits (shipped least 6.1e-3, float noise 4.3e-17). test_no_lathe_profile_crosses_itself walks every lathe of the kit at every corner of its params: the nozzle lip fix is pinned. kitbash_assembly.py gives the Gap cutter two brass faces and asks that each face keeps its own slot. kitbash.md: the reducer mates a fitting only from small_r 0.03, and Boolean cost as ratios plus the times read through the add-on. Takes the five Low findings of verdict cut-kit-shape-vocabulary.s1 (cut kit-joints). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 8 ++- surfaces/blender/brokkr_kitbash/core.py | 57 +++++++++++----- .../brokkr_kitbash/kits/mechanical.v0.json | 4 +- surfaces/blender/docs/kitbash.md | 36 +++++++--- surfaces/blender/tests/live/kitbash.py | 15 ++++ .../blender/tests/live/kitbash.result.json | 55 +++++++++++++++ .../blender/tests/live/kitbash_assembly.py | 7 ++ .../tests/live/kitbash_assembly.result.json | 5 ++ surfaces/blender/tests/test_kitbash.py | 68 ++++++++++++++++++- 9 files changed, 224 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 4b1ada6..5f77073 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -59,7 +59,8 @@ def kit_work(work): def write_mesh(mesh, built) -> None: - """The built part into an empty mesh datablock: vertices, n-gon faces, and flat shading on every face not marked smooth.""" + """The built part into an empty mesh datablock: vertices, n-gon faces, flat shading on every face not marked + smooth, and sharp_edge on exactly the edges built.sharp lists.""" mesh.vertices.add(len(built.V)) mesh.vertices.foreach_set("co", built.V.astype(np.float32).ravel()) mesh.loops.add(len(built.faces)) @@ -69,6 +70,11 @@ def write_mesh(mesh, built) -> None: sharp = mesh.attributes.get("sharp_face") or mesh.attributes.new("sharp_face", "BOOLEAN", "FACE") sharp.data.foreach_set("value", ~built.smooth) mesh.update(calc_edges=True) + ends = np.zeros(2 * len(mesh.edges), dtype=np.int32) + mesh.edges.foreach_get("vertices", ends) + key = lambda pairs: pairs.min(axis=1).astype(np.int64) * len(built.V) + pairs.max(axis=1) # noqa: E731 + crease = mesh.attributes.get("sharp_edge") or mesh.attributes.new("sharp_edge", "BOOLEAN", "EDGE") + crease.data.foreach_set("value", np.isin(key(ends.reshape(-1, 2)), key(built.sharp))) def sync_bevel(obj, width: float) -> None: diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 0df5aef..489bac0 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -3,14 +3,16 @@ numpy and the standard library only, no Blender: tests/test_kitbash.py runs this file as it is. A kit is data (kits/.v0.json beside this file). A part is a list of shapes (tube, box, lathe, and a repeat of one of them, a step apart or turned about an axis) whose numbers may be expressions over the part's params, and a list of -sockets, each a frame on one of the part's flat faces. An expression is parsed with ast.parse and walked against a +sockets, each a frame on one of the part's flat faces. A lathe profile point may be marked sharp: its ring of edges +is then a crease (Built.sharp). An expression is parsed with ast.parse and walked against a whitelist; nothing in a kit is ever run as Python. kit = load_kit("mechanical") - built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, shell_count, sockets + built = build(part(kit, "tank"), {"length": 1.2}) # Built: V, faces, counts, smooth, sharp, shell_count, sockets Two sockets mate through mate (the child's matrix under its parent), mate_refusal (what may mate) and residual -(how far a placed child stands from its mate). +(how far a placed child stands from its mate). 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. Every refusal is a KitError whose message names the kit, part and field. """ @@ -223,11 +225,15 @@ def _shape(shape: Any, names, where: str, inside_repeat: bool = False) -> dict: profile = shape["profile"] if not isinstance(profile, list) or len(profile) < least: raise KitError(f"{where} profile must be an array of at least {least} [r, z] points{' (it is a loop)' if made['loop'] else ''}") - made["profile"] = [] + made["profile"], made["sharp"] = [], [] for i, point in enumerate(profile): - if not isinstance(point, list) or len(point) != 2: - raise KitError(f"{where} profile[{i}] must be [r, z]: two numbers or expressions") - made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point)]) + if not isinstance(point, list) or len(point) not in (2, 3) or (len(point) == 3 and point[2] != "sharp"): + raise KitError(f"{where} profile[{i}] must be [r, z] or [r, z, \"sharp\"]: two numbers or expressions, and the mark") + if len(point) == 3 and not made["loop"] and i in (0, len(profile) - 1): + raise KitError(f"{where} profile[{i}] is marked sharp at an end of an open profile: an end is a flat cap or a pole, " + "and has no ring to crease") + made["profile"].append([parse(value, names, f"{where} profile[{i}][{c}]") for c, value in enumerate(point[:2])]) + made["sharp"].append(len(point) == 3) return made for key in ("r0", "r1", "length"): made[key] = parse(shape[key], names, f"{where} {key}") @@ -388,7 +394,9 @@ def resolve_params(part: dict, given: dict, base: dict | None = None) -> dict: class Built(NamedTuple): """A part at given params, in the part's frame, metres. Face i has counts[i] corners, listed in order in faces (quads, a lathe's triangles at a pole, and n-gon caps, wound outward); smooth[i] marks the walls to shade smooth; shape[i] is the index, - in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). Each socket is + in the part's shapes list, of the shape the face belongs to (every copy of a repeat shares one). sharp is an + (E, 2) array of vertex index pairs: the edges shaded as a crease, which are the rings of the lathe profile points + marked "sharp", in every copy. Each socket is {'name', 'type', 'size', 'matrix'} with matrix the 4x4 frame: column 2 the outward normal, column 1 up, column 0 = y cross z, column 3 the origin.""" V: np.ndarray @@ -396,6 +404,7 @@ class Built(NamedTuple): counts: np.ndarray smooth: np.ndarray shape: np.ndarray + sharp: np.ndarray shell_count: int sockets: list bevel: float @@ -448,14 +457,24 @@ def _tube(shape: dict, env): faces = np.concatenate([side.ravel(), k[::-1], n + k]) counts = np.concatenate([np.full(n, 4), [n, n]]) smooth = np.concatenate([np.full(n, shape["smooth"]), [False, False]]) - return V, faces, counts, smooth + return V, faces, counts, smooth, NO_SHARP + + +NO_SHARP = np.zeros((0, 2), dtype=np.int64) +# A lathe profile encloses nothing when its closing polygon's area is at most FLAT times the square of its largest +# coordinate. Shipped least 6.1e-3 (the tank's strap, over every lathe of the kit at each corner of its part's params +# and 16 draws); the largest a flat profile reads through float rounding 4.3e-17 (the 266 constant-z profiles among +# 3000 random ones of three decimals); FLAT is their geometric mean, separation 1.2e7 each side +# (lodur:ruling:deterministic-bound-margin). +FLAT = 5.1e-10 def _lathe(shape: dict, env): """A profile of [r, z] points revolved about +z, one ring per point. Open: an end on the axis (r exactly 0) is a pole and the band to it triangles; an end off the axis gets a flat n-gon cap. Loop: the last point joins the first. The profile is listed out along the bottom and up the outside (its closing polygon, down the axis for an - open one, has positive area in (r, z)), which makes every band and cap wind as a tube's.""" + open one, has positive area in (r, z)), which makes every band and cap wind as a tube's. The fifth array returned + is the ring edges of the points marked sharp.""" where = shape["where"] P = np.array([[r.value(env), z.value(env)] for r, z in shape["profile"]]) n = _whole(shape["segments"], env, SEGMENTS) @@ -470,7 +489,7 @@ def _lathe(shape: dict, env): ring = P if loop else np.vstack([P, [[0.0, P[last, 1]], [0.0, P[0, 1]]]]) after = np.roll(ring, -1, axis=0) area = 0.5 * float((ring[:, 0] * after[:, 1] - after[:, 0] * ring[:, 1]).sum()) - if not area > 0: + if not area > FLAT * float(np.abs(P).max()) ** 2: raise KitError(f"{where} profile: list it out along the bottom and up the outside; these points run the other way or enclose nothing " f"(signed area {area:.6g} in r, z)") angle = 2.0 * math.pi * np.arange(n) / n @@ -497,7 +516,8 @@ def _lathe(shape: dict, env): faces.append(start[end] + corners) counts.append([n]) smooth.append([False]) - return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool) + sharp = [np.column_stack([start[i] + k, start[i] + j]) for i in range(len(P)) if shape["sharp"][i]] # never an end (check_kit), so never a pole + return V, np.concatenate(faces), np.concatenate(counts), np.concatenate(smooth).astype(bool), np.concatenate(sharp) if sharp else NO_SHARP BOX_FACES = np.array([[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]) @@ -508,13 +528,13 @@ def _box(shape: dict, env): size = np.array([e.value(env) for e in shape["size"]]) if not (size > 0).all(): raise KitError(f"{shape['where']}: every size must be above 0, got {size.tolist()}") - return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool) + return BOX_SIGNS * size, BOX_FACES.ravel(), np.full(6, 4), np.zeros(6, dtype=bool), NO_SHARP def _placed(shape: dict, env): - V, faces, counts, smooth = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) + V, faces, counts, smooth, sharp = {"tube": _tube, "box": _box, "lathe": _lathe}[shape["shape"]](shape, env) rotation = _rotation([e.value(env) for e in shape["rot"]]) - return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth + return V @ rotation.T + np.array([e.value(env) for e in shape["at"]]), faces, counts, smooth, sharp def build(part: dict, params: dict | None = None) -> Built: @@ -527,13 +547,13 @@ def build(part: dict, params: dict | None = None) -> Built: for index, shape in enumerate(part["shapes"]): if shape["shape"] == "repeat": count = _whole(shape["count"], env, COPIES) - V, faces, counts, smooth = _placed(shape["of"], env) + V, faces, counts, smooth, sharp = _placed(shape["of"], env) if "step" in shape: step = np.array([e.value(env) for e in shape["step"]]) - made = [(V + k * step, faces, counts, smooth) for k in range(count)] + made = [(V + k * step, faces, counts, smooth, sharp) for k in range(count)] else: # copy k turned k/count of a turn, right-handed, about the axis through center axis, center = np.array(AXES[shape["around"]]), np.array([e.value(env) for e in shape["center"]]) - made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth) for k in range(count)] + made = [((V - center) @ _rotation(axis * (360.0 * k / count)).T + center, faces, counts, smooth, sharp) for k in range(count)] else: made = [_placed(shape, env)] for shell in made: @@ -560,6 +580,7 @@ def build(part: dict, params: dict | None = None) -> Built: counts=np.concatenate([s[2] for s in shells]).astype(np.int32), smooth=np.concatenate([s[3] for s in shells]).astype(bool), shape=np.concatenate([np.full(len(s[2]), o) for s, o in zip(shells, owner)]).astype(np.int32), + sharp=np.concatenate([s[4] + o for s, o in zip(shells, offsets)]).astype(np.int32), shell_count=len(shells), sockets=sockets, bevel=bevel, params=env) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index a09c1a1..2d170a9 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -285,8 +285,8 @@ "bevel": "0.15*flange_t", "shapes": [ {"shape": "lathe", "segments": "segments", "smooth": true, "profile": [ - ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)"], - ["small_r", "length-flange_t-0.15*(length-2*flange_t)"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, + ["1.35*big_r", 0], ["1.35*big_r", "flange_t"], ["big_r", "flange_t"], ["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"], + ["small_r", "length-flange_t-0.15*(length-2*flange_t)", "sharp"], ["small_r", "length-flange_t"], ["1.9*small_r", "length-flange_t"], ["1.9*small_r", "length"]]}, {"shape": "repeat", "count": 8, "around": "+z", "of": {"shape": "tube", "r0": "0.077*big_r", "r1": "0.077*big_r", "length": "1.35*flange_t", "segments": 6, "at": ["1.175*big_r", 0, "0.15*flange_t"]}}, {"shape": "repeat", "count": 4, "around": "+z", "of": diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 814e7da..8fc9341 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -72,7 +72,7 @@ then y, then z, about the shape's own origin) place it, rotation first; both def | --- | --- | --- | | `tube` | `r0`, `r1`, `length`, `segments`, `inner0`?, `inner1`?, `smooth`? | A frustum on +z from radius `r0` at z=0 to `r1` at z=`length`, with n-gon caps. Inner radii above 0 make it hollow (an inner wall and two flat end rings); they are both above 0 or both 0, and below the outer radius. `segments` is 3 to 128. `smooth` shades the walls smooth; caps stay flat. | | `box` | `size` | A box centred on its origin; every size above 0. | -| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. | +| `lathe` | `profile`, `segments`, `loop`?, `smooth`? | A profile of `[r, z]` points revolved about +z into one shell, a ring of `segments` (3 to 128) vertices per point. An open profile's end on the axis (`r` exactly 0) is a pole; an end off the axis gets a flat n-gon cap. With `loop` true the last point joins the first and there are no caps (a ring: 3 points or more). `smooth` shades the walls smooth; a band between two points of one `z` (an annulus) and the caps stay flat. A point written `[r, z, "sharp"]` is a crease. | | `repeat` | `count`, `of`, and `step` or `around` with `center`? | `count` copies (1 to 256) of one tube, box or lathe: at `k * step`, k from 0, or turned `k * 360 / count` degrees, right-handed, about the axis `around` (one of `+x -x +y -y +z -z`) through `center` (default the origin). Exactly one of `step` and `around`. A repeat cannot hold a repeat. | A lathe's profile is listed out along the bottom and up the outside, as this flanged stub is: a cap of radius 0.1 @@ -85,10 +85,24 @@ at z=0, the flange's rim, its top face, the pipe, and a cap of radius 0.05 at z= The rule behind "up the outside": the profile, closed down the axis from its last `z` to its first (a loop closes itself), has positive area in (r, z). A profile listed the other way is refused, and so are a negative `r`, an -`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A profile may turn -back down inside itself (a bell's inner wall); one that crosses itself is not caught, and builds a shell that is -not a solid. A turned part with many steps is one lathe, and so one shell, where a stack of tubes is one shell -each: a Boolean on it costs less ("Assembling parts"). +`r` of 0 anywhere but an open profile's two ends, and a point that repeats the one before it. A flat profile +(every point at one `z`) encloses nothing and is refused whatever its digits: the area must be above 5.1e-10 of +the square of the profile's largest coordinate, which float rounding does not reach and no real profile comes +near. A profile may turn back down inside itself (a bell's inner wall); one that crosses itself is not caught by +`core`, and builds a shell that is not a solid. For a shipped kit `test_no_lathe_profile_crosses_itself` catches +it, at every corner of the part's params. A turned part with many steps is one lathe, and so one shell, where a +stack of tubes is one shell each: a Boolean on it costs less ("Assembling parts"). + +Smooth shading rounds every bend of a smooth lathe, and the Bevel only cuts edges sharper than 30 degrees. Where +a turned part should show a hard line at a shallower bend (a cone leaving a neck), mark the point: + +```json +["big_r", "flange_t+0.15*(length-2*flange_t)", "sharp"] +``` + +The ring of edges at that point is then shaded as a crease (`Built.sharp`, written to the mesh's `sharp_edge` +attribute by `place_part` and `set_params`). The mark is per point and authored: no angle decides it. It is +refused at an open profile's two ends, which are a cap or a pole. No modifier or auto-smooth setting takes part. Shells may overlap (a pad that runs into a tank), and a part is then not one solid: reports give the shell count. @@ -159,9 +173,12 @@ cut's edges are bevelled with the rest. The modifier's object is the cutter; the always Exact with self-intersection on: a kit part is several overlapping closed shells, and without it the shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap and the barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that -overlap, so each turned body of the kit is one lathe: on Blender 5.3 a box cut from a part at its defaults takes -0.51 s for the tank (6 shells; 1.53 s when it was 20), 0.40 s for the nozzle (9 shells; 1.25 s at 24) and 0.24 s -for a pipe fitting (14 shells; 0.31 s at 19), each time the part is evaluated. Keep live booleans few and +overlap, so each turned body of the kit is one lathe. What carries from machine to machine is the ratio to the +same part built as a stack of tubes: 0.31 for the tank (6 shells against 20), 0.33 for the nozzle (9 against +24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its defaults, +placed through the add-on with its Bevel below the Boolean, evaluated in 0.55 s for the tank, 0.49 s for the +nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire (medians of four processes of +five evaluations); the part pays it each time it is evaluated. Keep live booleans few and `apply` them when the shape is settled. `boolean` evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter @@ -270,7 +287,8 @@ three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0. `2*radius` (0.16 to 0.6). So tanks, fittings and nozzles plumb together, and a ribbed cylinder takes a nozzle (throat 0.08 and up) or another ribbed cylinder face to face: its smallest flange is larger than the largest pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and -its `small` face `2*small_r` (0.048 to 0.14, the tank ports' and the fittings'), so a chamber hangs in a tank's +its `small` face `2*small_r` (0.048 to 0.14): a tank port over that whole range, and a fitting's face only from +`small_r` 0.03, the smallest pipe. So a chamber hangs in a tank's tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals `0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any part whose seat is no larger than theirs. diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 19d7920..22ec15c 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -100,6 +100,13 @@ for index, name in enumerate(names): flat = np.zeros(max(faces, 0), dtype=bool) if obj: obj.data.attributes["sharp_face"].data.foreach_get("value", flat) + crease = obj.data.attributes.get("sharp_edge") if obj else None + creased = np.zeros(len(obj.data.edges) if crease else 0, dtype=bool) + if crease: + crease.data.foreach_get("value", creased) + marked = sorted(tuple(sorted(edge.vertices)) for edge, on in zip(obj.data.edges, creased) if on) if crease else None + check(f"place_part {name}: sharp_edge is true on exactly core's sharp edges ({len(reference.sharp)})", + marked == sorted(tuple(sorted(pair)) for pair in reference.sharp.tolist()), [marked and len(marked), len(reference.sharp)]) bevel = obj.modifiers.get("Kit Bevel") if obj else None evaluated = len(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.polygons) if obj else -1 placed[name] = report @@ -117,6 +124,14 @@ for index, name in enumerate(names): check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- +reducer = bpy.data.objects["P_reducer"] +send("brokkr_kitbash.set_params", object_name="P_reducer", params="segments=12") +creased = np.zeros(len(reducer.data.edges), dtype=bool) +reducer.data.attributes["sharp_edge"].data.foreach_get("value", creased) +rings = [np.array([reducer.data.vertices[v].co[:] for edge, on in zip(reducer.data.edges, creased) if on for v in edge.vertices])] +check("the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + len(core.build(kit["parts"]["reducer"]).sharp) == 48 and int(creased.sum()) == 24 + and sorted(set(np.round(np.linalg.norm(rings[0][:, :2], axis=1), 5).tolist())) == [0.05, 0.12], int(creased.sum())) tank = bpy.data.objects["P_tank"] send("setObjectTransform", targetObjectName="P_tank", location=[1.0, 2.0, 3.0], rotationEuler=[0.3, -0.2, 0.5], scale=[1.0, 1.0, 1.0]) send("assignMaterial", targetObjectName="P_tank", materialName="Tank Paint", color=[0.35, 0.35, 0.35]) diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index d935e1d..9deceab 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -21,6 +21,11 @@ "ok": true, "detail": null }, + { + "name": "place_part nozzle: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part nozzle: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -36,6 +41,11 @@ "ok": true, "detail": null }, + { + "name": "place_part tank: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part tank: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -51,6 +61,11 @@ "ok": true, "detail": null }, + { + "name": "place_part ribbed_cylinder: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part ribbed_cylinder: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -66,6 +81,11 @@ "ok": true, "detail": null }, + { + "name": "place_part strut: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part strut: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -81,6 +101,11 @@ "ok": true, "detail": null }, + { + "name": "place_part actuator: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part actuator: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -96,6 +121,11 @@ "ok": true, "detail": null }, + { + "name": "place_part pipe_fitting: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part pipe_fitting: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -111,6 +141,11 @@ "ok": true, "detail": null }, + { + "name": "place_part radiator_stack: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part radiator_stack: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -126,6 +161,11 @@ "ok": true, "detail": null }, + { + "name": "place_part vent: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part vent: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -141,6 +181,11 @@ "ok": true, "detail": null }, + { + "name": "place_part plate: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, { "name": "place_part plate: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -156,6 +201,11 @@ "ok": true, "detail": null }, + { + "name": "place_part reducer: sharp_edge is true on exactly core's sharp edges (48)", + "ok": true, + "detail": null + }, { "name": "place_part reducer: core's faces, a valid mesh, core's flat faces, at the origin", "ok": true, @@ -176,6 +226,11 @@ "ok": true, "detail": null }, + { + "name": "the reducer's creases are its two cone rings, 24 edges each at 24 segments, and set_params writes them again: 12 each at 12", + "ok": true, + "detail": null + }, { "name": "set_params doubling the tank's length doubles its z extent", "ok": true, diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index a9f342e..8b5b3f7 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -491,6 +491,7 @@ send("createObject", objectType="MESH", name="Gap", location=[0.1, -12.0, 0.0], gap = bpy.data.objects["Gap"] gap.data.materials.append(None) # the cutter's faces are in an empty first slot gap.data.materials.append(bpy.data.materials["Boss Brass"]) +gap.data.polygons[0].material_index = gap.data.polygons[1].material_index = 1 # two of its faces are brass; the rest stay in the empty slot send("brokkr_kitbash.boolean", object_name="Gapped", cutter="Gap") receipt, baked = send("brokkr_kitbash.apply", object_name="Gapped") used = np.zeros(len(gapped.data.polygons), dtype=np.int32) @@ -498,6 +499,12 @@ gapped.data.polygons.foreach_get("material_index", used) check("apply leaves no face outside the material slots when a cutter's first slot is empty", receipt["status"] == "accepted" and len(used) > 44 and used.min() >= 0 and used.max() < len(gapped.data.materials) and not gapped.data.validate_material_indices() and not gapped.data.validate(verbose=False), [receipt["message"], int(used.min()), int(used.max()), [m and m.name for m in gapped.data.materials]]) +names = [m and m.name for m in gapped.data.materials] +brass = [p.index for p in gapped.data.polygons if "Boss Brass" in names and p.material_index == names.index("Boss Brass")] +far = [p.index for p in gapped.data.polygons if (gapped.matrix_world @ p.center).x < -0.05] # the plate's half the cutter does not reach +check("and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + names[0] == "Plate Paint" and 0 < len(brass) < len(used) and far and all(used[i] == 0 for i in far) + and all(abs((gapped.matrix_world @ gapped.data.polygons[i].center).x - 0.1) < 0.051 for i in brass), [names, len(brass), len(far), sorted(set(used.tolist()))]) R["ok"] = all(c["ok"] for c in R["checks"]) R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index e51d21b..6957612 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -395,6 +395,11 @@ "name": "apply leaves no face outside the material slots when a cutter's first slot is empty", "ok": true, "detail": null + }, + { + "name": "and each face keeps its own slot: the cutter's brass faces are brass, the faces from its empty slot and the plate's own are the plate's paint", + "ok": true, + "detail": null } ], "hostErrors": [], diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index a84645c..980679d 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -11,6 +11,7 @@ from __future__ import annotations import copy import importlib.util +import itertools import json import math import random @@ -319,7 +320,12 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 0]]), r"shape 0 \(lathe\) profile must be an array of at least 2 \[r, z\] points"), (lathe([[1, 0], [1, 1]], loop=True), r"profile must be an array of at least 3 \[r, z\] points \(it is a loop\)"), (lathe("round"), r"profile must be an array of at least 2"), - (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\]"), + (lathe([[1, 0], [1, 1, 0]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "soft"], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or \[r, z, \"sharp\"\]"), + (lathe([[1, 0], [1, 1, "sharp", 0], [0.5, 1]]), r"profile\[1\] must be \[r, z\] or"), + (lathe([[1, 0, "sharp"], [1, 1], [0.5, 1]]), r"profile\[0\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0.5, 1, "sharp"]]), r"profile\[2\] is marked sharp at an end of an open profile"), + (lathe([[1, 0], [1, 1], [0, 1.5, "sharp"]]), r"profile\[2\] is marked sharp at an end"), # a pole is an end (lathe([[1, 0], 1]), r"profile\[1\] must be \[r, z\]"), (lathe([[1, 0], [1, "q"]]), r"profile\[1\]\[1\]: 'q' names 'q'"), (lathe([[1, 0], [1, 1]], loop=1), r"loop must be true or false"), @@ -333,10 +339,34 @@ class ShapeTests(unittest.TestCase): (lathe([[1, 1], [1, 0]]), r"shape 0 \(lathe\) profile: list it out along the bottom and up the outside"), (lathe(ring[::-1], loop=True), r"profile: list it out along the bottom and up the outside"), (lathe([[0, 0], [0, 1]]), r"enclose nothing \(signed area 0 in r, z\)"), + # flat-profile. Mutant J10 (the tolerance back to 0): the first builds, on an area of 1.6e-17 that is float rounding + (lathe([[0.129, 0.686], [1.592, 0.686]]), r"enclose nothing \(signed area \S+e-17 in r, z\)"), + (lathe([[1.592, 0.686], [0.129, 0.686]]), r"enclose nothing \(signed area 0 in r, z\)"), + (lathe([[0.1, 0.3], [0.7, 0.3]]), r"enclose nothing \(signed area 0 in r, z\)"), (lathe([[1, 0], [1, 1]], segments=2), r"segments is 2\.0: it must be a whole number from 3 to 128")): with self.assertRaisesRegex(core.KitError, message): built(shapes) + def test_a_sharp_point_marks_its_ring_in_every_copy(self): + """sharp-points. Mutant J9 (a copy's pairs not offset by the vertices before it): every copy names the first's ring.""" + n = 8 + profile = [[0, 0], [0.5, 0.2, "sharp"], [0.5, 0.6], [0.3, 0.8, "sharp"], [0.3, 1.0]] # a pole first: its ring is one vertex + b = built([{"shape": "box", "size": [1, 1, 1]}, + {"shape": "repeat", "count": 3, "step": [2, 0, 0], "of": {"shape": "lathe", "profile": profile, "segments": n, "smooth": True}}]) + each = 1 + 4 * n + expected = [[8 + c * each + 1 + i * n + k, 8 + c * each + 1 + i * n + (k + 1) % n] for c in range(3) for i in (0, 2) for k in range(n)] + self.assertEqual(b.sharp.tolist(), expected) + self.assertEqual((b.sharp.dtype, b.sharp.shape, len(b.V)), (np.int32, (48, 2), 8 + 3 * each)) + radius = np.linalg.norm(b.V[b.sharp[:, 0]][:, :2] - np.repeat([[0, 0], [2, 0], [4, 0]], 2 * n, axis=0), axis=1) + self.assertTrue(np.allclose(radius, np.tile(np.repeat([0.5, 0.3], n), 3), atol=1e-12)) # each pair lies on its own copy's marked ring + plain = built([{"shape": "lathe", "profile": [point[:2] for point in profile], "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]) + self.assertEqual((plain.sharp.shape, plain.sharp.dtype), ((0, 2), np.int32)) + self.assertEqual(plain.V.tobytes(), built([{"shape": "lathe", "profile": profile, "segments": n}, {"shape": "tube", "r0": 1, "r1": 1, "length": 1, "segments": n}]).V.tobytes()) + ring = built([{"shape": "lathe", "loop": True, "segments": n, "profile": [[0.4, 0, "sharp"], [0.6, 0], [0.6, 0.2], [0.4, 0.2, "sharp"]]}]) # a loop has no end + self.assertEqual(ring.sharp.tolist(), [[i * n + k, i * n + (k + 1) % n] for i in (0, 3) for k in range(n)]) + thin = built([{"shape": "lathe", "profile": [[0.5, 0], [0.5, 1e-6]], "segments": n}]) # thin is not flat: 2e-6 of its extent squared + self.assertGreater(signed_volume(thin), 0.0) + def test_repeat_around_turns_copies_about_the_axis(self): """repeat-around. Mutants K5 (copy k turned k*360/(count+1)) and K6 (center ignored).""" box = {"shape": "box", "size": [0.2, 0.2, 0.2]} @@ -452,6 +482,42 @@ class MechanicalKitTests(unittest.TestCase): self.assertLess(socket_seat(b, socket), 1e-6, f"{name}.{socket['name']} {given}") self.assertGreater(socket["size"], 0.0) + def test_no_lathe_profile_crosses_itself(self): + """profile-simple: closed, outward and positive volume do not see a profile that crosses itself, and core does not + check it. Mutant J11 (the nozzle's lip min(2.5*wall, 0.08*length) to 0.2*length): crosses at length 0.25, wall 0.015.""" + def side(a, b, c): + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) + + def cross(a, b, c, d): # the two segments share a point (touching counts): their boxes overlap and each straddles the other's line + if any(max(min(a[x], b[x]), min(c[x], d[x])) > min(max(a[x], b[x]), max(c[x], d[x])) for x in (0, 1)): + return False # also what tells two stretches of one straight line apart (the bell between its hoops) + return side(a, b, c) * side(a, b, d) <= 0 and side(c, d, a) * side(c, d, b) <= 0 + + self.assertTrue(cross((0, 0), (2, 2), (0, 2), (2, 0)) and cross((0, 0), (2, 0), (1, 0), (1, 1)) and cross((0, 0), (2, 0), (1, 0), (3, 0))) + self.assertFalse(cross((0, 0), (2, 0), (0, 1), (2, 1)) or cross((0, 0), (1, 1), (2, 2), (3, 3)) or cross((0, 0), (2, 0), (3, -1), (3, 1))) + lathes = 0 + for name, part in self.kit["parts"].items(): + found = [s if s["shape"] == "lathe" else s["of"] for s in part["shapes"] if "lathe" in (s["shape"], s.get("of", {}).get("shape"))] + rng = random.Random(f"mechanical.{name}") + draws = [{p["name"]: p[key] for p in part["params"]} for key in ("default", "min", "max")] + for _ in range(16): + draws.append({p["name"]: rng.randint(p["min"], p["max"]) if p["type"] == "integer" else rng.uniform(p["min"], p["max"]) + for p in part["params"]}) + draws += [dict(zip([p["name"] for p in part["params"]], corner)) for corner in itertools.product(*[(p["min"], p["max"]) for p in part["params"]])] + for lathe in found: + lathes += 1 + for given in draws: + env = core.resolve_params(part, given) + points = [(r.value(env), z.value(env)) for r, z in lathe["profile"]] + segments = list(zip(points, points[1:] + points[:1] if lathe["loop"] else points[1:])) + count = len(segments) + for i in range(count): + for j in range(i + 2, count): + if lathe["loop"] and i == 0 and j == count - 1: + continue # neighbours round the loop + self.assertFalse(cross(*segments[i], *segments[j]), f"{name} profile segments {i} and {j} at {given}") + self.assertEqual(lathes, 6) + def test_extension_moves_the_rod_end_and_nothing_else(self): part = self.kit["parts"]["actuator"] short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5}) -- 2.47.3 From 8224125d1f34a8f0a0637cca1548b31bbe244174 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:02:38 +0100 Subject: [PATCH 2/5] brokkr_kitbash: pivot sockets on the pin axis, tank mount lugs, a bracket The strut's and actuator's end-face pivot sockets (z along the part) are gone. Each pin now carries a socket on each of its end faces, z along the pin and y along the part: end_a, end_a_back, end_b, end_b_back; base, base_back, rod_end, rod_end_back. Two pinned parts share the pin's axis and the connection's roll is the hinge angle. Scripts that attach by the old names still attach; where the part lands changes. The tank gains a mount lug on each side of each strap (shapes 4 and 5, sockets lug_a, lug_b, lug_a_back, lug_b_back); its other shapes and sockets build the same bytes. A bracket (part 11) seats a pin on a flat mount: its pivot face lies on its plate's centre plane, so a bracket turned half about its mount pins on the same plane facing the first. Every other part builds byte-identical V, faces, counts, smooth and shape against f329f56 (21 draws each). A box cut from the tank reads 502 ms at 6 shells and 507 ms at 10 (4 alternating processes of 5). Cut kit-joints. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_kitbash/kits/mechanical.v0.json | 53 ++++++++++--- surfaces/blender/docs/kitbash.md | 41 ++++++---- surfaces/blender/tests/live/kitbash.py | 10 +-- .../blender/tests/live/kitbash.result.json | 54 +++++++++++-- .../blender/tests/live/kitbash_assembly.py | 2 +- .../tests/live/kitbash_assembly.result.json | 14 ++-- surfaces/blender/tests/test_kitbash.py | 75 ++++++++++++++++--- 7 files changed, 196 insertions(+), 53 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json index 2d170a9..1da5a7b 100644 --- a/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json +++ b/surfaces/blender/brokkr_kitbash/kits/mechanical.v0.json @@ -47,7 +47,7 @@ }, { "name": "tank", - "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles and a mounting pad.", + "doc": "Pressure tank: elliptical domed ends with flanged ports, weld bands, two straps on saddle cradles, a mounting pad, and a mount lug on each side of each strap.", "params": [ {"name": "radius", "type": "number", "min": 0.12, "max": 0.35, "default": 0.22, "doc": "shell radius"}, {"name": "length", "type": "number", "min": 0.6, "max": 2.0, "default": 0.9, "doc": "port face to port face"}, @@ -67,12 +67,20 @@ "profile": [["0.97*radius", 0], ["1.035*radius", 0], ["1.035*radius", "0.1*radius"], ["0.97*radius", "0.1*radius"]]}}, {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": {"shape": "box", "size": ["1.3*radius", "0.55*radius", "0.1*radius"], "at": [0, "-0.85*radius", "0.49*radius+0.22*(length-0.98*radius)"]}}, - {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]} + {"shape": "box", "size": ["1.5*radius", "0.08*radius", "0.56*(length-0.98*radius)+0.3*radius"], "at": [0, "-1.14*radius", "length/2"]}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["0.1*radius", "0.35*radius", "0.3*radius"], "at": ["1.07*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"]}}, + {"shape": "repeat", "count": 2, "step": [0, 0, "0.56*(length-0.98*radius)"], "of": + {"shape": "box", "size": ["0.1*radius", "0.35*radius", "0.3*radius"], "at": ["-1.07*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"]}} ], "sockets": [ {"name": "port_a", "type": "flange", "size": "0.4*radius", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "port_b", "type": "flange", "size": "0.4*radius", "at": [0, 0, "length"], "z": "+z", "y": "+y"}, - {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"} + {"name": "saddle", "type": "mount", "size": "1.5*radius", "at": [0, "-1.18*radius", "length/2"], "z": "-y", "y": "+z"}, + {"name": "lug_a", "type": "mount", "size": "0.3*radius", "at": ["1.12*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"], "z": "+x", "y": "+z"}, + {"name": "lug_b", "type": "mount", "size": "0.3*radius", "at": ["1.12*radius", 0, "0.49*radius+0.78*(length-0.98*radius)"], "z": "+x", "y": "+z"}, + {"name": "lug_a_back", "type": "mount", "size": "0.3*radius", "at": ["-1.12*radius", 0, "0.49*radius+0.22*(length-0.98*radius)"], "z": "-x", "y": "+z"}, + {"name": "lug_b_back", "type": "mount", "size": "0.3*radius", "at": ["-1.12*radius", 0, "0.49*radius+0.78*(length-0.98*radius)"], "z": "-x", "y": "+z"} ] }, { @@ -107,7 +115,7 @@ }, { "name": "strut", - "doc": "Structural strut: an I-beam with web stiffeners between two pinned end blocks.", + "doc": "Structural strut: an I-beam with web stiffeners between two end blocks, each on a cross pin; a socket on each end face of each pin.", "params": [ {"name": "length", "type": "number", "min": 0.3, "max": 2.0, "default": 0.8, "doc": "end face to end face"}, {"name": "width", "type": "number", "min": 0.04, "max": 0.12, "default": 0.08, "doc": "flange width (x)"}, @@ -127,13 +135,15 @@ {"shape": "box", "size": ["0.9*width", "0.7*thickness", "0.08*width"], "at": [0, 0, "0.9*width+(length-1.8*width)/4"]}} ], "sockets": [ - {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, - {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, 0, "length"], "z": "+z", "y": "+y"} + {"name": "end_a", "type": "pivot", "size": "0.6*width", "at": [0, "0.85*thickness", "0.45*width"], "z": "+y", "y": "+z"}, + {"name": "end_a_back", "type": "pivot", "size": "0.6*width", "at": [0, "-0.85*thickness", "0.45*width"], "z": "-y", "y": "+z"}, + {"name": "end_b", "type": "pivot", "size": "0.6*width", "at": [0, "0.85*thickness", "length-0.45*width"], "z": "+y", "y": "+z"}, + {"name": "end_b_back", "type": "pivot", "size": "0.6*width", "at": [0, "-0.85*thickness", "length-0.45*width"], "z": "-y", "y": "+z"} ] }, { "name": "actuator", - "doc": "Tie-rod hydraulic cylinder: pinned base eye, square caps, barrel, ports, and a rod with its eye; extension moves rod_end.", + "doc": "Tie-rod hydraulic cylinder: base eye and rod eye each on a cross pin with a socket on each end face, square caps, barrel, ports; extension moves the rod eye.", "params": [ {"name": "body_r", "type": "number", "min": 0.05, "max": 0.12, "default": 0.06, "doc": "barrel radius"}, {"name": "body_len", "type": "number", "min": 0.2, "max": 1.0, "default": 0.4, "doc": "barrel length between caps"}, @@ -160,8 +170,10 @@ {"shape": "tube", "r0": "0.45*body_r", "r1": "0.45*body_r", "length": "1.3*body_r", "segments": "segments", "smooth": true, "rot": [-90, 0, 0], "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"]} ], "sockets": [ - {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, - {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, 0, "4.5*body_r+body_len+extension"], "z": "+z", "y": "+y"} + {"name": "base", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "0.8*body_r"], "z": "+y", "y": "+z"}, + {"name": "base_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "0.8*body_r"], "z": "-y", "y": "+z"}, + {"name": "rod_end", "type": "pivot", "size": "0.9*body_r", "at": [0, "0.65*body_r", "3.8*body_r+body_len+extension"], "z": "+y", "y": "+z"}, + {"name": "rod_end_back", "type": "pivot", "size": "0.9*body_r", "at": [0, "-0.65*body_r", "3.8*body_r+body_len+extension"], "z": "-y", "y": "+z"} ] }, { @@ -296,6 +308,29 @@ {"name": "big", "type": "flange", "size": "2*big_r", "at": [0, 0, 0], "z": "-z", "y": "+y"}, {"name": "small", "type": "flange", "size": "2*small_r", "at": [0, 0, "length"], "z": "+z", "y": "+y"} ] + }, + { + "name": "bracket", + "doc": "Lug bracket: a square foot plate and one ear carrying a pin. The ear's pin face lies on the plate's centre plane, so a second bracket turned half about its mount pins on the same plane, facing the first.", + "params": [ + {"name": "pin_r", "type": "number", "min": 0.012, "max": 0.054, "default": 0.027, "doc": "pin radius"}, + {"name": "height", "type": "number", "min": 0.08, "max": 0.3, "default": 0.1, "doc": "mount face to pin axis"}, + {"name": "width", "type": "number", "min": 0.03, "max": 0.3, "default": 0.09, "doc": "foot plate side"}, + {"name": "ear_t", "type": "number", "min": 0.006, "max": 0.04, "default": 0.014, "doc": "ear thickness (x)"}, + {"name": "segments", "type": "integer", "min": 8, "max": 48, "default": 24, "doc": "sides of the rounds"} + ], + "bevel": "0.12*min(ear_t,0.25*width)", + "shapes": [ + {"shape": "box", "size": ["width", "width", "0.2*min(width,height)"], "at": [0, 0, "0.1*min(width,height)"]}, + {"shape": "box", "size": ["ear_t", "2.6*pin_r", "height-0.2*min(width,height)"], "at": ["-0.5*ear_t", 0, "0.5*height+0.1*min(width,height)"]}, + {"shape": "tube", "r0": "1.3*pin_r", "r1": "1.3*pin_r", "length": "ear_t", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["-ear_t", 0, "height"]}, + {"shape": "tube", "r0": "pin_r", "r1": "pin_r", "length": "0.6*pin_r", "segments": "segments", "smooth": true, "rot": [0, 90, 0], "at": ["-ear_t-0.6*pin_r", 0, "height"]} + ], + "sockets": [ + {"name": "mount", "type": "mount", "size": "width", "at": [0, 0, 0], "z": "-z", "y": "+y"}, + {"name": "pivot", "type": "pivot", "size": "2*pin_r", "at": [0, 0, "height"], "z": "+x", "y": "+z"}, + {"name": "pivot_back", "type": "pivot", "size": "2*pin_r", "at": ["-ear_t-0.6*pin_r", 0, "height"], "z": "-x", "y": "+z"} + ] } ] } diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 8fc9341..1ba8a66 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -116,6 +116,11 @@ be compared when sockets are mated: `equal` (within 1 percent) or `fits` (the ch sits on a flat face of the part whose normal is its `z`; `test_kitbash` checks this for every part of a shipped kit at its default, smallest and largest params and at seeded draws between. +A pin joint is a socket whose `z` runs along the pin, with its origin on the pin's end face and its `y` along the +part. Two such sockets mate face to face on one pin axis, and the roll of the connection is then the hinge +angle: at 0 the two parts line up, side by side. A pin carries a socket on each of its end faces (`end_a` and +`end_a_back`), so a part can be pinned from either side, and by both at once. + ## Assembling parts **A connection** seats one socket of a child part on one socket of a parent part: the two origins together, the @@ -174,11 +179,12 @@ always Exact with self-intersection on: a kit part is several overlapping closed shells cancel where they overlap (the 1.8 m tank with a box cut through a cradle, the pad, a strap and the barrel keeps 0.251 m3 with self-intersection and 0.006 m3 without). The cost grows with the shells that overlap, so each turned body of the kit is one lathe. What carries from machine to machine is the ratio to the -same part built as a stack of tubes: 0.31 for the tank (6 shells against 20), 0.33 for the nozzle (9 against -24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its defaults, -placed through the add-on with its Bevel below the Boolean, evaluated in 0.55 s for the tank, 0.49 s for the -nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire (medians of four processes of -five evaluations); the part pays it each time it is evaluated. Keep live booleans few and +same part built as a stack of tubes: 0.31 for the tank's turned body (6 shells against 20), 0.33 for the nozzle +(9 against 24) and 0.81 for a pipe fitting (14 against 19). As absolute times, a box cut from a part at its +defaults, placed through the add-on with its Bevel below the Boolean, evaluated in 0.50 to 0.55 s for the tank +(two sessions), 0.49 s for the nozzle and 0.31 s for a pipe fitting on Blender 5.3 on the workstation Starfire +(medians of four processes of five evaluations). The tank's four lugs, shells 7 to 10, add 1 percent to a cut +that misses them and 4 percent to one through them. The part pays this each time it is evaluated. Keep live booleans few and `apply` them when the shape is settled. `boolean` evaluates the part once and reports `evaluated: {faces, volume, nonManifoldEdges}`; `report` never evaluates a modifier. The cutter is any other mesh object and is not changed: hide it with `setObjectVisibility`. A cutter @@ -264,21 +270,22 @@ file holds each report in `hostResult`. `tools/turntable_recipe.py` renders the ## The mechanical kit -`kits/mechanical.v0.json`: ten parts, each along +z, with socket types `flange` (equal), `mount` (fits) and +`kits/mechanical.v0.json`: eleven parts, each along +z, with socket types `flange` (equal), `mount` (fits) and `pivot` (equal). | part | params | sockets | | --- | --- | --- | | `nozzle` | `throat_r`, `exit_r`, `length`, `wall`, `segments` | `mount` (flange) | -| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount) | +| `tank` | `radius`, `length`, `segments` | `port_a`, `port_b` (flange), `saddle` (mount), `lug_a`, `lug_b`, `lug_a_back`, `lug_b_back` (mount): a lug on each side (+x, and -x for `_back`) of each strap | | `ribbed_cylinder` | `radius`, `length`, `ribs`, `rib_depth`, `rib_width`, `segments` | `end_a`, `end_b` (flange) | -| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_b` (pivot) | -| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `rod_end` (pivot); `rod_end` moves with `extension` | +| `strut` | `length`, `width`, `thickness`, `segments` | `end_a`, `end_a_back`, `end_b`, `end_b_back` (pivot): the two end faces of the pin at each end | +| `actuator` | `body_r`, `body_len`, `rod_r`, `extension`, `segments` | `base`, `base_back`, `rod_end`, `rod_end_back` (pivot); the rod end's two move with `extension` | | `pipe_fitting` | `pipe_r`, `run`, `branch`, `flange_r`, `flange_t`, `segments` | `a`, `b`, `c` (flange) | | `radiator_stack` | `fins`, `fin_w`, `fin_h`, `fin_t`, `pitch`, `segments` | `base` (mount) | | `vent` | `width`, `height`, `depth`, `slats`, `slat_t`, `tilt` | `back` (mount) | | `plate` | `width`, `height`, `thickness` | `back`, `front` (mount) | | `reducer` | `big_r`, `small_r`, `length`, `flange_t`, `segments` | `big`, `small` (flange) | +| `bracket` | `pin_r`, `height`, `width`, `ear_t`, `segments` | `mount` (mount), `pivot`, `pivot_back` (pivot) | `describe` gives the bounds and docs. @@ -289,9 +296,17 @@ three faces `2*pipe_r` (0.06 to 0.14), a nozzle's mount `2*throat_r` (0.08 to 0. pipe. A reducer joins the two: its `big` face is `2*big_r` (0.16 to 0.6, a ribbed cylinder's whole range) and its `small` face `2*small_r` (0.048 to 0.14): a tank port over that whole range, and a fitting's face only from `small_r` 0.03, the smallest pipe. So a chamber hangs in a tank's -tree as tank, tee, reducer, ribbed cylinder, nozzle. Struts and actuators pin together when `0.6*width` equals -`0.9*body_r`; both ends of each lie on its own axis, so pinned parts chain in a line. Mounts (`fits`) take any -part whose seat is no larger than theirs. +tree as tank, tee, reducer, ribbed cylinder, nozzle. Mounts (`fits`) take any part whose seat is no larger than +theirs. + +Pins: a strut's are `0.6*width` across (0.024 to 0.072), an actuator's `0.9*body_r` (0.045 to 0.108) and a +bracket's `2*pin_r` (0.024 to 0.108), so a bracket can be sized to either, and a strut pins to an actuator when +`0.6*width` equals `0.9*body_r`. Pinned parts hinge: the roll is the angle between them. A bracket is how a pin +meets a flat seat: its `mount` sits on a plate, a saddle or a tank lug (a lug seats a plate up to `0.3*radius` +wide), and its pin runs across the seat's up axis, so on a tank lug at roll 0 a leg swings in a plane through +the tank's axis. The bracket's `pivot` face lies on its plate's centre plane, so a bracket on a second lug of +the same side, turned half (roll 180), pins on the same plane facing the first. An actuator on one and a strut +on the other then lie in one plane and can meet at a pin: a braced leg. ## Adding a part or a kit @@ -305,7 +320,7 @@ python -m unittest discover -s surfaces/blender/tests -p "test_kitbash.py" -v 16 seeded draws, and checks that every shell is closed and wound outward, every socket frame is right-handed and seated on a face that faces its `z`, and no build passes 20000 faces. Choose param ranges so every combination builds: a `min` or `max` in an expression keeps a derived length positive where two params could cross. A new -part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_ten_parts_and_three_socket_types`. +part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`. `MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, `set_params` on assemblies, boolean and apply). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 22ec15c..94b812c 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -1,5 +1,5 @@ """Live proof, in a background Blender, that the brokkr_kitbash rows are admitted by Brokkr as host actions and that -the mechanical kit goes through run_intent: describe, place_part for all ten parts, setObjectTransform, +the mechanical kit goes through run_intent: describe, place_part for all eleven parts, setObjectTransform, assignMaterial, set_params, report, the refusals, and exportGltf. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash.py -- @@ -81,7 +81,7 @@ check("the eight kitbash rows load as host actions with no errors", not R["hostE kit = core.load_kit("mechanical") receipt, described = send("brokkr_kitbash.describe") names = [p["name"] for p in described["parts"]] if described else [] -check("describe lists ten parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 10 +check("describe lists eleven parts, whole, inside a receipt", receipt["status"] == "accepted" and names == list(kit["parts"]) and len(names) == 11 and "[truncated]" not in receipt["hostResult"], [names, len(receipt.get("hostResult") or "")]) receipt, one = send("brokkr_kitbash.describe", part="actuator") check("describe of one part gives its params and its sockets at default params", one and [p["name"] for p in one["parts"]] == ["actuator"] @@ -121,7 +121,7 @@ for index, name in enumerate(names): check(f"place_part {name}: kit, part and every resolved param stored on the object, sockets reported in the part frame", obj is not None and obj["kit_kit"] == "mechanical" and obj["kit_part"] == name and json.loads(obj["kit_params"]) == reference.params == report["params"] and report["sockets"] == core.socket_rows(reference.sockets), report) -check("ten parts are ten mesh objects", len(bpy.data.objects) == 10 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) +check("eleven parts are eleven mesh objects", len(bpy.data.objects) == 11 and all(o.type == "MESH" for o in bpy.data.objects), len(bpy.data.objects)) # --- set_params keeps what is not derived -------------------------------------------------------------------------------- reducer = bpy.data.objects["P_reducer"] @@ -240,7 +240,7 @@ receipt, alone = send("brokkr_kitbash.set_params", object_name="P_vent", params= check("with the duplicate gone the vent's mesh is its own again and set_params rebuilds it", receipt["status"] == "accepted" and alone and alone["params"]["slats"] == 9 and len(bpy.data.objects["P_vent"].data.polygons) == len(core.build(kit["parts"]["vent"], {"slats": 9}).counts), receipt["message"]) receipt, whole = send("brokkr_kitbash.report") -check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 10, receipt["message"]) +check("with scale back at 1 every part reports again", receipt["status"] == "accepted" and whole and len(whole["parts"]) == 11, receipt["message"]) # --- export --------------------------------------------------------------------------------------------------------------- receipt, _ = send("exportGltf", filepath="kit.glb", extras=False, yUp=True, applyModifiers=True, selection=[f"P_{n}" for n in names]) @@ -249,7 +249,7 @@ meshes = -1 if glb.is_file(): blob = glb.read_bytes() meshes = len(json.loads(blob[20:20 + int.from_bytes(blob[12:16], "little")]).get("meshes", [])) -check("exportGltf of all ten parts succeeds", receipt["status"] == "accepted" and meshes == 10, [receipt["message"], meshes]) +check("exportGltf of all eleven parts succeeds", receipt["status"] == "accepted" and meshes == 11, [receipt["message"], meshes]) R["placed"] = {name: {"faces": report["faces"], "shells": report["shells"], "bevel": report["bevel"], "sockets": [s["name"] for s in report["sockets"]]} for name, report in placed.items() if report} diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 9deceab..7b0de47 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -7,7 +7,7 @@ "detail": null }, { - "name": "describe lists ten parts, whole, inside a receipt", + "name": "describe lists eleven parts, whole, inside a receipt", "ok": true, "detail": null }, @@ -222,7 +222,27 @@ "detail": null }, { - "name": "ten parts are ten mesh objects", + "name": "place_part bracket: sharp_edge is true on exactly core's sharp edges (0)", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: core's faces, a valid mesh, core's flat faces, at the origin", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: a Bevel of the part's width, 2 segments, angle 30, that evaluates", + "ok": true, + "detail": null + }, + { + "name": "place_part bracket: kit, part and every resolved param stored on the object, sockets reported in the part frame", + "ok": true, + "detail": null + }, + { + "name": "eleven parts are eleven mesh objects", "ok": true, "detail": null }, @@ -372,7 +392,7 @@ "detail": null }, { - "name": "exportGltf of all ten parts succeeds", + "name": "exportGltf of all eleven parts succeeds", "ok": true, "detail": null } @@ -405,13 +425,17 @@ ] }, "tank": { - "faces": 764, - "shells": 6, + "faces": 788, + "shells": 10, "bevel": 0.00176, "sockets": [ "port_a", "port_b", - "saddle" + "saddle", + "lug_a", + "lug_b", + "lug_a_back", + "lug_b_back" ] }, "ribbed_cylinder": { @@ -429,7 +453,9 @@ "bevel": 0.0015, "sockets": [ "end_a", - "end_b" + "end_a_back", + "end_b", + "end_b_back" ] }, "actuator": { @@ -438,7 +464,9 @@ "bevel": 0.0024, "sockets": [ "base", - "rod_end" + "base_back", + "rod_end", + "rod_end_back" ] }, "pipe_fitting": { @@ -484,6 +512,16 @@ "big", "small" ] + }, + "bracket": { + "faces": 64, + "shells": 4, + "bevel": 0.00168, + "sockets": [ + "mount", + "pivot", + "pivot_back" + ] } }, "ok": true diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 8b5b3f7..184a4d2 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -272,7 +272,7 @@ receipt, report = send("brokkr_kitbash.set_params", object_name="Ram", params="e back = frame(ram, "base")[:3, 3] - base[:3, 3] check("extending an actuator that hangs by its rod seats it again: the rod end stays, the body backs off by the travel", reading("seated", seated(ram, "rod_end", strut, "end_b", 0.0)) < SEATED and receipt["status"] == "accepted" and held(report) - and reading("carried", np.abs(back - base[:3, 2] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) + and reading("carried", np.abs(back + base[:3, 1] * 0.35).max()) < CARRIED, [receipt["message"], connection("Ram"), back.tolist()]) # a pivot's y is the part's axis tip = frame(strut, "end_b") receipt, report = send("brokkr_kitbash.set_params", object_name="Lift", params="extension=0.6") check("extending the actuator above moves the strut on its rod and the ram below with it", receipt["status"] == "accepted" diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index 6957612..df36b95 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -404,22 +404,22 @@ ], "hostErrors": [], "readings": { - "carried": 2.7e-07, + "carried": 2.6e-07, "cut": 0.25, "kept": 1.5e-08, "nudged": 0.00032, - "roll": 6.3e-06, - "seated": 1.5e-07 + "roll": 6.6e-06, + "seated": 2.1e-07 }, "tank": { "raw": { - "faces": 764, - "volume": 0.264485537, + "faces": 788, + "volume": 0.264932753, "nonManifoldEdges": 0 }, "cut": { - "faces": 2250, - "volume": 0.250847643, + "faces": 2566, + "volume": 0.251287573, "nonManifoldEdges": 0 } }, diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 980679d..05da9e8 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -445,21 +445,27 @@ class ParamTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy is not installed") class MechanicalKitTests(unittest.TestCase): - PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer"] + PARTS = ["nozzle", "tank", "ribbed_cylinder", "strut", "actuator", "pipe_fitting", "radiator_stack", "vent", "plate", "reducer", "bracket"] @classmethod def setUpClass(cls): cls.kit = core.load_kit("mechanical") - def test_the_kit_is_the_ten_parts_and_three_socket_types(self): + def test_the_kit_is_the_eleven_parts_and_three_socket_types(self): self.assertEqual(list(self.kit["parts"]), self.PARTS) self.assertEqual({k: v["match"] for k, v in self.kit["socketTypes"].items()}, {"flange": "equal", "mount": "fits", "pivot": "equal"}) self.assertEqual({name: [(s["name"], s["type"]) for s in part["sockets"]] for name, part in self.kit["parts"].items()}, { - "nozzle": [("mount", "flange")], "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount")], - "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], "strut": [("end_a", "pivot"), ("end_b", "pivot")], - "actuator": [("base", "pivot"), ("rod_end", "pivot")], "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], + "nozzle": [("mount", "flange")], + "tank": [("port_a", "flange"), ("port_b", "flange"), ("saddle", "mount"), ("lug_a", "mount"), ("lug_b", "mount"), ("lug_a_back", "mount"), ("lug_b_back", "mount")], + "ribbed_cylinder": [("end_a", "flange"), ("end_b", "flange")], + "strut": [("end_a", "pivot"), ("end_a_back", "pivot"), ("end_b", "pivot"), ("end_b_back", "pivot")], + "actuator": [("base", "pivot"), ("base_back", "pivot"), ("rod_end", "pivot"), ("rod_end_back", "pivot")], + "pipe_fitting": [("a", "flange"), ("b", "flange"), ("c", "flange")], "radiator_stack": [("base", "mount")], "vent": [("back", "mount")], "plate": [("back", "mount"), ("front", "mount")], - "reducer": [("big", "flange"), ("small", "flange")]}) + "reducer": [("big", "flange"), ("small", "flange")], "bracket": [("mount", "mount"), ("pivot", "pivot"), ("pivot_back", "pivot")]}) + tank = core.build(self.kit["parts"]["tank"]) + self.assertEqual(sorted(set(tank.shape.tolist())), [0, 1, 2, 3, 4, 5]) # the straps stay shape 1; the lugs are appended as 4 and 5 + self.assertEqual((int((tank.shape == 1).sum()), int((tank.shape >= 4).sum())), (2 * 4 * 24, 4 * 6)) def test_every_part_holds_everywhere(self): """kit-parts-hold-everywhere. Mutant M8 (flip one socket's z in the kit): no face at that origin faces it.""" @@ -520,9 +526,14 @@ class MechanicalKitTests(unittest.TestCase): def test_extension_moves_the_rod_end_and_nothing_else(self): part = self.kit["parts"]["actuator"] - short, long = core.build(part, {"extension": 0.0}), core.build(part, {"extension": 0.5}) - self.assertEqual(short.sockets[0]["matrix"].tolist(), long.sockets[0]["matrix"].tolist()) - self.assertAlmostEqual(long.sockets[1]["matrix"][2, 3] - short.sockets[1]["matrix"][2, 3], 0.5, places=12) + short, long = ({s["name"]: s["matrix"] for s in core.build(part, {"extension": e}).sockets} for e in (0.0, 0.5)) + for name in ("base", "base_back"): + self.assertEqual(short[name].tolist(), long[name].tolist()) + for name in ("rod_end", "rod_end_back"): + moved = long[name] - short[name] + self.assertAlmostEqual(moved[2, 3], 0.5, places=12) # along the part's z + moved[2, 3] = 0.0 + self.assertEqual(float(np.abs(moved).max()), 0.0) def test_builds_are_deterministic(self): """build-deterministic.""" @@ -591,6 +602,50 @@ class MateTests(unittest.TestCase): self.assertLess(worst["roll"], self.ROLL) self.assertLess(worst["residual"], self.RESIDUAL) + def test_a_pin_hinges_at_its_roll(self): + """pin-hinge. A pivot's z runs along its pin and its y along the part, so two pinned members share the pin's axis + and stand the roll apart about it; at roll 0 they line up. Mutant J2 (the strut's end_b with y -z): half a turn off. + Bounds are MateTests' own: the readings are the same arithmetic.""" + parts = self.kit["parts"] + strut, ram = core.build(parts["strut"], {"width": 0.09}), core.build(parts["actuator"], {"body_r": 0.06}) + worst = {"origin": 0.0, "normal": 0.0, "angle": 0.0} + for parent_name in ("end_a", "end_a_back", "end_b", "end_b_back"): + for child_name in ("base", "base_back", "rod_end", "rod_end_back"): + sp, sc = core.joint(parts["strut"], strut, parent_name, parts["actuator"], ram, child_name) + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc)) + self.assertEqual((abs(sp["matrix"][1, 2]), sp["matrix"][2, 1], abs(sc["matrix"][1, 2]), sc["matrix"][2, 1]), (1.0, 1.0, 1.0, 1.0)) # z the pin (the part's y), y the part's z + for roll in (0.0, 37.0, -90.0, 150.0): + child = core.mate(sp, sc, roll) # the strut stands at the identity + pin, there = sp["matrix"][:3, 2], child @ sc["matrix"] + read = math.degrees(math.atan2(np.cross([0.0, 0.0, 1.0], child[:3, 2]) @ pin, child[2, 2])) # the ram's +z from the strut's, about the pin + worst["origin"] = max(worst["origin"], float(np.abs(sp["matrix"][:3, 3] - there[:3, 3]).max())) + worst["normal"] = max(worst["normal"], float(np.abs(pin + there[:3, 2]).max())) + worst["angle"] = max(worst["angle"], abs((read - roll + 180.0) % 360.0 - 180.0)) + self.assertLess(worst["origin"], self.ORIGIN) + self.assertLess(worst["normal"], self.NORMAL) + self.assertLess(worst["angle"], self.ROLL) + + def test_a_bracket_turned_half_pins_on_its_own_plane(self): + """bracket-half-turn. A bracket seated on a lug at roll 0 and one seated there at roll 180 put their pivots at one + point with normals opposed, because the pivot face lies on the mount's centre plane; so brackets on two lugs, one + turned half, face each other across one plane and a brace between them closes. Mutant J1 (the pivot face at + x = -ear_t): the two origins stand 2*ear_t apart. Mutant J13 (a lug socket's z flipped) dies in kit-holds.""" + parts = self.kit["parts"] + tank = core.build(parts["tank"], {"radius": 0.3}) + for given in ({}, {"width": 0.03, "height": 0.3, "ear_t": 0.04, "pin_r": 0.054}): + bracket = core.build(parts["bracket"], given) + for lug in ("lug_a", "lug_b", "lug_a_back", "lug_b_back"): + sp, sc = core.joint(parts["tank"], tank, lug, parts["bracket"], bracket, "mount") + self.assertIsNone(core.mate_refusal(self.kit["socketTypes"], sp, sc)) + pivot = next(s["matrix"] for s in bracket.sockets if s["name"] == "pivot") + straight, turned = core.mate(sp, sc, 0.0) @ pivot, core.mate(sp, sc, 180.0) @ pivot + self.assertLess(float(np.abs(straight[:3, 3] - turned[:3, 3]).max()), self.ORIGIN) + self.assertLess(float(np.abs(straight[:3, 2] + turned[:3, 2]).max()), self.NORMAL) + self.assertLess(max(abs(float(straight[:3, 2] @ sp["matrix"][:3, k])) for k in (1, 2)), self.NORMAL) # the pin runs across the tank: a leg swings in a plane through its axis + self.assertAlmostEqual(float((straight[:3, 3] - sp["matrix"][:3, 3]) @ sp["matrix"][:3, 2]), bracket.params["height"], places=12) + with_default_tank = core.joint(parts["tank"], core.build(parts["tank"]), "lug_a", parts["bracket"], core.build(parts["bracket"]), "mount") + self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], *with_default_tank)) # a lug seats a plate up to 0.3 of the tank's radius + def test_residual_is_how_far_the_child_stands_from_its_mate(self): sp, sc = self.sockets(*self.PAIRS[0]) world = np.eye(4) @@ -664,7 +719,7 @@ class MateTests(unittest.TestCase): other = {**parts["pipe_fitting"], "kit": "hydraulic"} with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' is of kit 'hydraulic' and part 'tank' of kit 'mechanical'.*do not mate"): core.joint(parts["tank"], tank, "port_b", other, fitting, "a") - with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle"): + with self.assertRaisesRegex(core.KitError, "part 'tank' has no socket 'port_c'; its sockets: port_a, port_b, saddle, lug_a, lug_b, lug_a_back, lug_b_back"): core.joint(parts["tank"], tank, "port_c", parts["pipe_fitting"], fitting, "a") with self.assertRaisesRegex(core.KitError, "part 'pipe_fitting' has no socket 'd'; its sockets: a, b, c"): core.joint(parts["tank"], tank, "port_b", parts["pipe_fitting"], fitting, "d") -- 2.47.3 From 3ae142555cd74b9626be7545619e2756372f1117 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:10:08 +0100 Subject: [PATCH 3/5] brokkr_kitbash: close states a loop's closing joint and never moves anything Connections stay a tree owned by the child. A loop is closed by a closure: the closing part's kit_close_socket, kit_close_to (an object pointer) and kit_close_to_socket. brokkr_kitbash.close writes them only when the two sockets already meet (core.closure_residual within HELD, any roll) and writes nothing else; detach clears them, and now also accepts a part that states only a closure. Reports derive a closure's residual and holds each time. attach's inline occupancy scan is gone: occupant() is the one rule for attach and close, and counts closures at both ends. set_params refuses a change after which a closure's two sockets may no longer mate, checking closures before connections so the refusal names the closure, and otherwise only reports: its report lists every closure in the scene as closures [{part, to, holds}]. kitbash_assembly.py builds a braced leg on a tank's two lugs with rolls from the law of cosines and closes it; test_a_brace_closes_on_a_leg does the same in numpy (2.2e-16). Cut kit-joints. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 171 +++++++++++++++--- .../brokkr_kitbash/brokkr_actions.json | 45 ++++- surfaces/blender/brokkr_kitbash/core.py | 9 + surfaces/blender/docs/kitbash.md | 63 ++++++- surfaces/blender/tests/live/kitbash.py | 4 +- .../blender/tests/live/kitbash.result.json | 3 +- .../blender/tests/live/kitbash_assembly.py | 130 ++++++++++++- .../tests/live/kitbash_assembly.result.json | 142 ++++++++++++++- surfaces/blender/tests/test_kitbash.py | 72 +++++++- 9 files changed, 592 insertions(+), 47 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 5f77073..4e9c72b 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -19,6 +19,11 @@ belongs to its Boolean modifier on the target (the modifier's object is the cutt says apply replaced the mesh with the evaluated one: the params then only place the part's sockets. Placing a loose part, hiding a cutter, materials and export are Brokkr's own rows (setObjectTransform, setObjectVisibility, assignMaterial, exportGltf). + +Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties +on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close +writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here +solves a loop: a closure never places a part, and a report says how far its two sockets stand apart. """ bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0), "category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."} @@ -41,7 +46,8 @@ from . import core KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params" SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked" -HELD = 1e-5 # a connection holds when its residual is at most this (as RIGID) +CLOSE, CLOSE_TO, CLOSE_TO_SOCKET = "kit_close_socket", "kit_close_to", "kit_close_to_socket" +HELD = 1e-5 # a connection or a closure holds when its residual is at most this (as RIGID) BEVEL = "Kit Bevel" BOOLEAN = "Kit Boolean " # a Boolean modifier's name is this and its cutter's name: a label, the cutter is modifier.object BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0) @@ -129,10 +135,49 @@ def attached(obj) -> list: return [child for child in obj.children if SOCKET in child] -def mated(parent, parent_part, parent_built, child, child_part, child_built, stated): +def closure(obj): + """The closure a part states, (its socket, the other part or None, the other part's socket), or None. The + other part is a pointer: it follows a rename and reads None once the part is deleted. close, set_params, + detach and every report read it here.""" + if CLOSE not in obj: + return None + other = obj.get(CLOSE_TO) + return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) else None, str(obj.get(CLOSE_TO_SOCKET, "")) + + +def closing_on(part) -> list: + """The parts whose closure names this one.""" + return [obj for obj in bpy.data.objects if CLOSE in obj and obj.get(CLOSE_TO) == part] + + +def occupant(part, socket: str): + """The name of what holds a socket of a part, or None: a child attached there, the parent the part itself is + attached by, the part its own closure closes on, or a part whose closure names it there. The one occupancy + rule, for attach and close.""" + for child in attached(part): + if child.get(PARENT_SOCKET) == socket: + return child.name + if part.get(SOCKET) == socket: + return part.parent.name if part.parent else part.name + if part.get(CLOSE) == socket: + return closure(part)[1].name if closure(part)[1] else part.name + for other in closing_on(part): + if other.get(CLOSE_TO_SOCKET) == socket: + return other.name + return None + + +def free(part, socket: str) -> None: + holder = occupant(part, socket) + if holder is not None: + raise Refused(f"Socket {socket!r} of {part.name!r} is occupied (by {holder!r}); nothing changed.") + + +def mated(parent, parent_part, parent_built, child, child_part, child_built, stated, how="on"): """(parent socket, child socket) of the connection `stated` between two built parts, or a refusal that names it: a roll that is not a number, parts of two kits, a socket name a part does not have, or sockets - core.mate_refusal will not mate.""" + core.mate_refusal will not mate. A closure is checked here too (how "closing on"), the part it names as the + parent.""" if stated[2] is None: raise Refused(f"{child.name!r} on {parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.") try: @@ -141,7 +186,7 @@ def mated(parent, parent_part, parent_built, child, child_part, child_built, sta except core.KitError as error: refusal = str(error) if refusal: - raise Refused(f"{child.name!r} on {parent.name!r}: {refusal}; nothing changed.") + raise Refused(f"{child.name!r} {how} {parent.name!r}: {refusal}; nothing changed.") return sockets @@ -173,12 +218,55 @@ def connection_report(obj, part, built): return row +def closure_report(obj, part, built): + """None for a part that states no closure, else what it states and whether it holds: the other part is a kit + part of the same kit, both sockets exist, and the two stand within HELD of meeting (core.closure_residual). + `to` is null when the other part is gone or is not a part of this kit. Derived at each report; stored nowhere.""" + stated = closure(obj) + if stated is None: + return None + row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False} + try: + if stated[1] is None: + return row + other_part, other_built = built_part(stated[1]) + if other_part["kit"] != part["kit"]: + return row + row["to"] = stated[1].name + there, here = core.joint(other_part, other_built, stated[2], part, built, stated[0]) + except (Refused, core.KitError): + return row + row["residual"] = round(core.closure_residual(stated[1].matrix_world, there, obj.matrix_world, here), 9) + row["holds"] = bool(row["residual"] <= HELD) + return row + + +def scene_closures(context, report: dict) -> list: + """Every closure stated in the scene as {part, to, holds}, by part name, for a set_params report: a change of + params can open a closure anywhere below the part. Rows are left out, and counted in closuresOmitted, once + the report would pass what a receipt carries.""" + rows, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 + for obj in sorted((o for o in context.scene.objects if o.type == "MESH" and CLOSE in o), key=lambda o: o.name): + try: + found = closure_report(obj, *built_part(obj)) + except (Refused, core.KitError): + found = {"to": None, "holds": False} + row = {"part": obj.name, "to": found["to"], "holds": found["holds"]} + size += len(json.dumps(row, separators=(",", ":"))) + 1 + if size > REPORT_LIMIT: + report["closuresOmitted"] = report.get("closuresOmitted", 0) + 1 + else: + rows.append(row) + return rows + + def part_report(obj, part, built) -> dict: """A part as the scene has it. Reads stored properties and matrices only: no modifier is evaluated.""" return {"object": obj.name, "kit": part["kit"], "part": part["name"], "params": built.params, "faces": len(obj.data.polygons), "shells": built.shell_count, "bevel": round(built.bevel, 6), "sockets": core.socket_rows(built.sockets, np.array(obj.matrix_world)), - "connection": connection_report(obj, part, built), "baked": bool(obj.get(BAKED, False))} + "connection": connection_report(obj, part, built), "closure": closure_report(obj, part, built), + "baked": bool(obj.get(BAKED, False))} def own_mesh(obj, doing: str) -> None: @@ -258,7 +346,7 @@ class BROKKR_KITBASH_OT_place_part(PolishOperator): class BROKKR_KITBASH_OT_set_params(PolishOperator): """Change params of a placed kit part and rebuild its mesh in place: its modifiers and material slots stay, each shape keeps its faces' material, the Bevel width follows, and its connection and those of the parts - attached to it are seated again on the moved sockets""" + attached to it are seated again on the moved sockets; a closure is never seated, only reported""" bl_idname = "brokkr_kitbash.set_params" bl_label = "Set Kit Part Params" object_name: bpy.props.StringProperty(name="Object") @@ -273,6 +361,11 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): "place_part a new part to change them; nothing changed.") own_mesh(obj, "rebuilding") built = core.build(part, core.resolve_params(part, core.parse_params(self.params), stored)) + closing = closure(obj) # a closure this part is an end of must still be one its new sockets may make; where they stand is only reported + if closing is not None and closing[1] is not None: + mated(closing[1], *built_part(closing[1]), obj, part, built, (closing[0], closing[2], 0.0), "closing on") + for other in closing_on(obj): + mated(obj, part, built, other, *built_part(other), (closure(other)[0], closure(other)[2], 0.0), "closing on") seats, stated = [], link(obj) # every connection this part is an end of, checked against its new sockets before anything is written if stated is not None: if obj.parent is None: @@ -298,7 +391,9 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): seat(seated, basis) if seats: context.view_layer.update() - return part_report(obj, part, built) + report = part_report(obj, part, built) + report["closures"] = scene_closures(context, report) + return report class BROKKR_KITBASH_OT_attach(PolishOperator): @@ -330,14 +425,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): ancestor = ancestor.parent stated = (self.socket, self.parent_socket, float(self.roll)) sockets = mated(parent, parent_part, parent_built, child, part, built, stated) - users = [c.name for c in attached(parent) if c.get(PARENT_SOCKET) == self.parent_socket] - if parent.get(SOCKET) == self.parent_socket: - users.append(parent.parent.name if parent.parent else parent.name) - if users: - raise Refused(f"Socket {self.parent_socket!r} of {parent.name!r} is occupied (by {users[0]!r}); nothing changed.") - users = [c.name for c in attached(child) if c.get(PARENT_SOCKET) == self.socket] - if users: - raise Refused(f"Socket {self.socket!r} of {child.name!r} is occupied (by {users[0]!r}); nothing changed.") + free(parent, self.parent_socket) + free(child, self.socket) child.parent = parent seat(child, core.mate(*sockets, stated[2])) child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated @@ -346,8 +435,8 @@ class BROKKR_KITBASH_OT_attach(PolishOperator): class BROKKR_KITBASH_OT_detach(PolishOperator): - """Clear a kit part's connection: it stays where it stands in the world, loses its parent, and the parts - attached to it stay attached to it""" + """Clear a kit part's connection and the closure it states: it stays where it stands in the world, loses its + parent, and the parts attached to it stay attached to it""" bl_idname = "brokkr_kitbash.detach" bl_label = "Detach Kit Part" object_name: bpy.props.StringProperty(name="Object") @@ -355,18 +444,50 @@ class BROKKR_KITBASH_OT_detach(PolishOperator): @kit_work def work(self, context): obj = mesh_object(self.object_name) - if SOCKET not in obj: - raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property); nothing changed.") + if SOCKET not in obj and CLOSE not in obj: + raise Refused(f"{obj.name!r} is not attached (it has no {SOCKET} property) and states no closure; nothing changed.") part, built = built_part(obj) - world = obj.matrix_world.copy() - obj.parent = None - obj.matrix_world = world - for key in (SOCKET, PARENT_SOCKET, ROLL): + if SOCKET in obj: + world = obj.matrix_world.copy() + obj.parent = None + obj.matrix_world = world + for key in (SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET): if key in obj: del obj[key] return part_report(obj, part, built) +class BROKKR_KITBASH_OT_close(PolishOperator): + """State that a socket of a kit part meets a socket of another part of its kit, closing a loop the tree of + connections cannot: accepted only when the two already meet, origins together and normals opposed, and it + moves nothing""" + bl_idname = "brokkr_kitbash.close" + bl_label = "Close Kit Loop" + object_name: bpy.props.StringProperty(name="Object", description="The closing part: it states the closure") + socket: bpy.props.StringProperty(name="Socket", description="The closing part's socket") + other_name: bpy.props.StringProperty(name="Other", description="The part it closes on") + other_socket: bpy.props.StringProperty(name="Other Socket") + + @kit_work + def work(self, context): + obj, other = mesh_object(self.object_name), mesh_object(self.other_name) + part, built = built_part(obj) + other_part, other_built = built_part(other) + if obj == other: + raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") + if closure(obj) is not None: + raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") + there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") + free(other, self.other_socket) + free(obj, self.socket) + apart = core.closure_residual(other.matrix_world, there, obj.matrix_world, here) + if apart > HELD: + raise Refused(f"Socket {self.socket!r} of {obj.name!r} and socket {self.other_socket!r} of {other.name!r} stand {apart:.6g} m apart: " + "place them so they meet (attach with the roll that closes the loop); nothing changed.") + obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket + return part_report(obj, part, built) + + class BROKKR_KITBASH_OT_boolean(PolishOperator): """Cut a kit part with another mesh object through a live Boolean modifier (Exact, with self-intersection: kit parts are overlapping shells) placed above the Bevel; evaluates the part once and reports the result""" @@ -453,7 +574,7 @@ class BROKKR_KITBASH_OT_describe(PolishOperator): class BROKKR_KITBASH_OT_report(PolishOperator): """Report placed kit parts as the scene has them: kit, part, params, faces, shells, each socket's world frame, - the connection and whether it holds, and whether the part is baked""" + the connection and the closure and whether each holds, and whether the part is baked""" bl_idname = "brokkr_kitbash.report" bl_label = "Report Kit Parts" bl_options = {"REGISTER"} @@ -467,7 +588,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator): classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report, - BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) + BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_apply) def register(): diff --git a/surfaces/blender/brokkr_kitbash/brokkr_actions.json b/surfaces/blender/brokkr_kitbash/brokkr_actions.json index e75ec1b..6bd1ba7 100644 --- a/surfaces/blender/brokkr_kitbash/brokkr_actions.json +++ b/surfaces/blender/brokkr_kitbash/brokkr_actions.json @@ -160,7 +160,7 @@ }, { "name": "brokkr_kitbash.detach", - "doc": "Clear a kit part's connection: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", + "doc": "Clear a kit part's connection and the closure it states: it keeps its place in the world and loses its parent; parts attached to it stay attached to it.", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", @@ -174,6 +174,49 @@ } ] }, + { + "name": "brokkr_kitbash.close", + "doc": "Close a loop: state that a socket of a kit part meets a socket of another part of its kit, where attach cannot (the part already has its parent). Accepted only when the two sockets already meet, origins together and normals opposed, any roll; it moves nothing. Attach the parts with the rolls that make them meet first; brokkr_kitbash.report shows the closure and whether it holds.", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "object_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the closing part: it states the closure, one at most" + }, + { + "name": "socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "the closing part's socket" + }, + { + "name": "other_name", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "the part it closes on" + }, + { + "name": "other_socket", + "type": "string", + "required": true, + "chars": "id", + "minLength": 1, + "maxLength": 32, + "doc": "that part's socket" + } + ] + }, { "name": "brokkr_kitbash.boolean", "doc": "Cut a kit part with another mesh object through a live Boolean modifier (Exact, self-intersection on) above its Bevel. Evaluates the part once, about a second: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.", diff --git a/surfaces/blender/brokkr_kitbash/core.py b/surfaces/blender/brokkr_kitbash/core.py index 489bac0..3f7c3cf 100644 --- a/surfaces/blender/brokkr_kitbash/core.py +++ b/surfaces/blender/brokkr_kitbash/core.py @@ -621,6 +621,15 @@ def residual(parent_world, parent_socket: dict, child_world, child_socket: dict, return float(np.abs(wanted - np.asarray(child_world, dtype=np.float64) @ child_socket["matrix"]).max()) +def closure_residual(world_a, socket_a: dict, world_b, socket_b: dict) -> float: + """How far two sockets of two placed parts stand from meeting as a pin: the larger of the largest difference + between their origins (metres) and the largest entry of the sum of their normals (0 when opposed). Roll is not + read: a closure is a pin, free about its axis.""" + a = np.asarray(world_a, dtype=np.float64) @ socket_a["matrix"] + b = np.asarray(world_b, dtype=np.float64) @ socket_b["matrix"] + return float(max(np.abs(a[:3, 3] - b[:3, 3]).max(), np.abs(a[:3, 2] + b[:3, 2]).max())) + + EQUAL, SLACK = 0.01, 1e-9 # 'equal' sizes may differ by 1 percent of the larger; SLACK keeps a size at the limit inside it diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index 1ba8a66..bee7098 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -6,7 +6,7 @@ actuators, housings and plumbing an agent assembles offline under a hand-fit arm add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish` and `brokkr_rig`: it imports the polish package's operator base, `Refused` and `mesh_object`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_kitbash` refuses to register without it. `brokkr_actions.json` beside -its `__init__.py` lists the eight operators agents may run. Every action writes a JSON report to +its `__init__.py` lists the nine operators agents may run. Every action writes a JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. Who owns what: @@ -27,6 +27,9 @@ Who owns what: - A connection between two parts belongs to the child: its parent pointer and its `kit_socket`, `kit_parent_socket` and `kit_roll` properties. Where the child stands is derived from them ("Assembling parts"). +- A closure, the joint that closes a loop, belongs to the closing part: its `kit_close_socket`, `kit_close_to` + and `kit_close_to_socket` properties. Only `close` writes them and only `detach` clears them. A closure places + nothing: whether it holds is derived at each report. - A boolean belongs to its Boolean modifier on the part that is cut. `kit_baked` says `apply` replaced the part's mesh with the evaluated one. @@ -143,11 +146,54 @@ refuses, changing nothing: - a child that has a parent (`detach` it; `setObjectParent` with an empty parent clears a parent it was not attached to); - a parent that is the child, or is below it (a loop); -- an occupied socket: one a child is already attached to, or the one the part itself is attached by; +- an occupied socket: one a child is already attached to, the one the part itself is attached by, or one a + closure holds, at either end; - a part that is not a kit part, or is scaled in the world. -A part may carry a child on every socket but the one it hangs by, so assemblies are trees: tank, then a tee on -its port, then a nozzle on each free flange of the tee. +A part may carry a child on every socket but the one it hangs by. Connections are a tree: tank, then a tee on +its port, then a nozzle on each free flange of the tee. Nothing moves a part but `attach` and `set_params`, +through that tree. + +**A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace +hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the +hull, leg and brace are then a loop. The closing part owns it, one at most, as three ID properties: +`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename +and reads empty once that part is deleted) and `kit_close_to_socket`. A spanning tree plus loop-closing +constraints is how closed chains are usually stated (Featherstone, Rigid Body Dynamics Algorithms, ch. 8; +MuJoCo's `connect` equality on its kinematic tree). + +`close` writes those three properties and nothing else. It never moves a part: it is accepted only when the two +sockets already meet, origins together and normals opposed within 1e-5, at any roll (a closure is a pin). It +refuses, changing nothing: a part that is not a kit part or is scaled, a part closing on itself, two sockets +that may not mate (the part it names counts as the parent), an occupied socket at either end, a part that +already states a closure, and two sockets that do not meet, saying how far apart they stand. + +Making them meet is the caller's work, and nothing in the add-on solves a loop. For two members pinned in one +plane it is a triangle. With `a` and `b` the two members' pin-to-pin lengths and `d` the distance between the +two fixed pins, the angle at the first fixed pin between the line to the second and the first member is + +```text +acos((a*a + d*d - b*b) / (2*a*d)) +``` + +which gives the point where the free pins meet. Each member's roll is then the angle, about its fixed pin's +`z`, from that socket's `y` to the direction of the meeting point. `report` gives every socket's world frame to +read these from. + +A part's report carries `closure`: `null`, or + +```json +{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true} +``` + +`residual` is the larger of the largest difference between the two origins and the largest entry of the sum of +the two normals; `holds` is true when it is at most 1e-5. `to` is `null`, and `holds` false, when the other part +is gone or is not a part of this kit. A closure is never seated. `set_params` on either end refuses a change +after which the two sockets may no longer mate (a pin of another size), naming the closure. A change that only +moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report +of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, so the caller sees which +ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding. +`detach` clears the closing part's closure together with its connection. **`set_params` keeps an assembly together.** Sockets move with params (an actuator's `rod_end` with `extension`, a tank's `port_b` with `length`). After the rebuild `set_params` writes the derived `matrix_basis` of the part @@ -219,10 +265,11 @@ vertices overflow. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | -| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection, and a baked part. | -| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection` and `baked`. Changes nothing and evaluates no modifier. | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}` (with `closuresOmitted`, a count, if they would not fit a receipt). | +| `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `baked`. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there. Reports the child. | -| `brokkr_kitbash.detach` | `object_name` | Clears the part's connection; it stays where it stands. Refuses a part that is not attached. | +| `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | +| `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. | | `brokkr_kitbash.boolean` | `object_name`, `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds a live Exact Boolean above the Bevel. Refuses a cutter that is the part, is not a mesh, or already cuts it. Reports the part, `booleans: [{cutter, operation}]` and `evaluated`. | | `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the part and clears its modifiers. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. | @@ -323,4 +370,4 @@ builds: a `min` or `max` in an expression keeps a derived length positive where part of `mechanical` also joins the part and socket list in `test_the_kit_is_the_eleven_parts_and_three_socket_types`. `MateTests` covers the mate arithmetic and what may mate. The operators are exercised in a real Blender by `tests/live/kitbash.py` (placing and re-parameterising) and `tests/live/kitbash_assembly.py` (attach, detach, -`set_params` on assemblies, boolean and apply). +`set_params` on assemblies, a braced leg closed by `close`, boolean and apply). diff --git a/surfaces/blender/tests/live/kitbash.py b/surfaces/blender/tests/live/kitbash.py index 94b812c..b4be991 100644 --- a/surfaces/blender/tests/live/kitbash.py +++ b/surfaces/blender/tests/live/kitbash.py @@ -73,9 +73,9 @@ def extent(obj, axis=2): return float(co[:, axis].max() - co[:, axis].min()) -check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"] +check("the nine kitbash rows load as host actions with no errors", not R["hostErrors"] and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "apply")], [R["hostErrors"], R["hostRows"]]) # --- describe --------------------------------------------------------------------------------------------------------- kit = core.load_kit("mechanical") diff --git a/surfaces/blender/tests/live/kitbash.result.json b/surfaces/blender/tests/live/kitbash.result.json index 7b0de47..765c5af 100644 --- a/surfaces/blender/tests/live/kitbash.result.json +++ b/surfaces/blender/tests/live/kitbash.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the eight kitbash rows load as host actions with no errors", + "name": "the nine kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -412,6 +412,7 @@ "brokkr_kitbash.report", "brokkr_kitbash.attach", "brokkr_kitbash.detach", + "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply" ], diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 184a4d2..27341a9 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -1,6 +1,6 @@ """Live proof, in a background Blender, of brokkr_kitbash assembly through run_intent: attach and its refusals, -set_params seating a part and the parts attached to it again, drift and how it is cleared, a roll that is not a -number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part +set_params seating a part and the parts attached to it again, a braced leg closed by close and what set_params, +attach and detach then do, drift and how it is cleared, a roll that is not a number, detach, boolean (Exact, self-intersection on, above the Bevel), and apply with its material slots. Not part of the unittest run: it needs Blender. blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_assembly.py -- @@ -17,6 +17,7 @@ import importlib.util import json import math import os +import re import sys import tempfile import types @@ -174,8 +175,8 @@ def evaluated(obj): rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")] -check("the eight kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( - "place_part", "set_params", "describe", "report", "attach", "detach", "boolean", "apply")], [R["hostErrors"], rows]) +check("the nine kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in ( + "place_part", "set_params", "describe", "report", "attach", "detach", "close", "boolean", "apply")], [R["hostErrors"], rows]) # --- attach ------------------------------------------------------------------------------------------------------------- tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088 @@ -229,7 +230,7 @@ refused("a child that is not a kit part", "brokkr_kitbash.attach", {"object_name "'Plain' is not a kit part") refused("a parent that is not a kit part", "brokkr_kitbash.attach", {"object_name": "Spare", "socket": "mount", "parent_name": "Plain", "parent_socket": "b"}, "'Plain' is not a kit part") -refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached") +refused("detach of a part that is not attached", "brokkr_kitbash.detach", {"object_name": "Spare"}, "'Spare' is not attached (it has no kit_socket property) and states no closure") send("brokkr_kitbash.detach", object_name="Tee") send("setObjectTransform", targetObjectName="Tee", location=[-2.0, 0.5, 1.0], rotationEuler=[1.1, 0.4, -0.7]) refused("a child socket one of its own children is on", "brokkr_kitbash.attach", {"object_name": "Tee", "socket": "c", "parent_name": "Tank", "parent_socket": "port_b"}, @@ -281,6 +282,125 @@ check("extending the actuator above moves the strut on its rod and the ram below and reading("carried", np.abs(frame(strut, "end_b")[:3, 3] - tip[:3, 3] - np.array(lift.matrix_world)[:3, 2] * 0.45).max()) < CARRIED, [receipt["message"], connection("Strut"), connection("Ram")]) +# --- a closure: a brace from a second bracket closes on the leg's rod pin ------------------------------------------------------------ +hull = place("Hull", "tank", "radius=0.3; length=1.2", location=[6.0, 0.0, 2.0], rotation=[0.0, math.pi, 0.4]) # lug size 0.09 +upper, lower = place("Upper", "bracket"), place("Lower", "bracket") # pin 0.054, plate 0.09 +send("brokkr_kitbash.attach", object_name="Upper", socket="mount", parent_name="Hull", parent_socket="lug_b") +send("brokkr_kitbash.attach", object_name="Lower", socket="mount", parent_name="Hull", parent_socket="lug_a", roll=180.0) # turned half: its pin face looks back at Upper's +leg, brace, tie = place("Leg", "actuator"), place("Brace", "strut", "width=0.09; length=1.1"), place("Tie", "strut", "width=0.09") +p1, p2 = frame(upper, "pivot"), frame(lower, "pivot") +check("a bracket turned half on the next lug pins on the first one's plane, facing it", abs((p2[:3, 3] - p1[:3, 3]) @ p1[:3, 2]) < SEATED + and np.abs(p1[:3, 2] + p2[:3, 2]).max() < SEATED, [p1.tolist(), p2.tolist()]) +span = {name: core.build(kit["parts"][part], given) for name, part, given in (("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": 1.1}))} +a = next(s for s in span["leg"].sockets if s["name"] == "rod_end")["matrix"][2, 3] - next(s for s in span["leg"].sockets if s["name"] == "base")["matrix"][2, 3] +b = next(s for s in span["brace"].sockets if s["name"] == "end_b")["matrix"][2, 3] - next(s for s in span["brace"].sockets if s["name"] == "end_a")["matrix"][2, 3] +d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) +corner = math.acos((a * a + d * d - b * b) / (2 * a * d)) # the law of cosines: the angle at the upper pin between the hull and the leg +knee = p1[:3, 3] + a * (math.cos(corner) * (p2[:3, 3] - p1[:3, 3]) / d + math.sin(corner) * frame(hull, "lug_b")[:3, 2]) + + +def roll_to(pin, toward): + """The roll that points a pinned member's axis (its socket's y) from this pin toward a point in the pin's plane.""" + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + + +def closure_of(name): + receipt, report = send("brokkr_kitbash.report", object_name=name) + return report["parts"][0]["closure"] if report else {"error": receipt["message"]} + + +def without_closures(state): + return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] + + +CLOSING = {"object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} +send("brokkr_kitbash.attach", object_name="Leg", socket="base", parent_name="Upper", parent_socket="pivot", roll=roll_to(p1, knee)) +send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee) + 1.0) +apart = core.closure_residual(np.array(leg.matrix_world), next(s for s in span["leg"].sockets if s["name"] == "rod_end"), + np.array(brace.matrix_world), next(s for s in span["brace"].sockets if s["name"] == "end_b")) +state = scene_state() +receipt, _ = send("brokkr_kitbash.close", **CLOSING) +named = re.search(r"Socket 'end_b' of 'Brace' and socket 'rod_end' of 'Leg' stand (\S+) m apart: place them so they meet", str(receipt["message"])) +check("refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", receipt["status"] != "accepted" + and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) +send("brokkr_kitbash.detach", object_name="Brace") +send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) +state = scene_state() +receipt, report = send("brokkr_kitbash.close", **CLOSING) +check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" + and reading("seated", seated(brace, "end_b", leg, "rod_end")) < SEATED and without_closures(scene_state()) == without_closures(state) + and (brace["kit_close_socket"], brace["kit_close_to"], brace["kit_close_to_socket"]) == ("end_b", leg, "rod_end") + and sorted(k for k in brace.keys() if k.startswith("kit_close")) == ["kit_close_socket", "kit_close_to", "kit_close_to_socket"] + and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) +check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" + and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} + and reading("closed", report["closure"]["residual"]) <= 1e-5 and held(report) and closure_of("Brace") == report["closure"] + and closure_of("Leg") is None, report) +refused("a second closure on a part that states one", "brokkr_kitbash.close", + {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") +refused("close on a socket a closure holds", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") +refused("close on the closing socket itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Brace", "other_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") +refused("close on a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "base"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") +refused("close by a socket a part is attached by", "brokkr_kitbash.close", {"object_name": "Leg", "socket": "base", "other_name": "Tie", "other_socket": "end_a"}, + "Socket 'base' of 'Leg' is occupied (by 'Upper')") +refused("attach onto a socket a closure holds", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Leg", "parent_socket": "rod_end"}, + "Socket 'rod_end' of 'Leg' is occupied (by 'Brace')") +refused("attach onto the closing socket", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Brace", "parent_socket": "end_b"}, + "Socket 'end_b' of 'Brace' is occupied (by 'Leg')") +refused("close of a part on itself", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Tie", "other_socket": "end_b"}, "'Tie' cannot close on itself") +refused("close of sockets that may not mate", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Hull", "other_socket": "lug_a_back"}, + "'Tie' closing on 'Hull': socket 'end_a' (pivot, size 0.054) and parent socket 'lug_a_back' (mount, size 0.09) are of different types") +refused("close of two sockets that are apart", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "m apart: place them so they meet") +refused("close on a mesh that is not a kit part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Plain", "other_socket": "a"}, "'Plain' is not a kit part") +refused("close of a socket the part does not have", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_c", "other_name": "Leg", "other_socket": "rod_end_back"}, + "part 'strut' has no socket 'end_c'") +was = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +found = closure_of("Brace") +check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None + and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) + and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") +check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_of("Brace")["holds"] is True, [report and report.get("closures"), closure_of("Brace")]) +refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") +refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, + "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.06) and parent socket 'rod_end' (pivot, size 0.054)") +receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") +check("set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"]["holds"] is False + and held(report) and 0.1 / math.sqrt(3) - 1e-5 <= report["closure"]["residual"] <= 0.1 + 1e-5, [receipt["message"], report and report["closure"]]) +send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") +before = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.detach", object_name="Brace") +check("detach clears the brace's closure with its connection, and it stays where it stood", receipt["status"] == "accepted" and report and report["closure"] is None + and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None + and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) +receipt, report = send("brokkr_kitbash.close", **CLOSING) +check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) +leg.name = "Shin" +found = closure_of("Brace") +check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) +leg.name = "Leg" +send("brokkr_kitbash.detach", object_name="Leg") +bpy.data.objects.remove(leg) +found = closure_of("Brace") +receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") +check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found == {**found, "to": None, "residual": None, "holds": False} + and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) +before = np.array(brace.matrix_world) +receipt, report = send("brokkr_kitbash.detach", object_name="Brace") +check("detach of a part that states only a closure clears it and leaves the part where it stood", receipt["status"] == "accepted" and report["closure"] is None + and not [k for k in brace.keys() if k.startswith("kit_close")] and np.array_equal(np.array(brace.matrix_world), before), [receipt["message"], dict(brace.items())]) +receipt, report = send("brokkr_kitbash.attach", object_name="Tie", socket="end_a", parent_name="Brace", parent_socket="end_b") +check("and the socket the closure held is free again", receipt["status"] == "accepted" and held(report), receipt["message"]) + # --- drift and detach --------------------------------------------------------------------------------------------------------- send("setObjectTransform", targetObjectName="Nozzle", location=[0.25, 0.0, 0.0]) found = connection("Nozzle") or {} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index df36b95..ad7a3a7 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -2,7 +2,7 @@ "blender": "5.3.0", "checks": [ { - "name": "the eight kitbash rows load as host actions with no errors", + "name": "the nine kitbash rows load as host actions with no errors", "ok": true, "detail": null }, @@ -141,6 +141,141 @@ "ok": true, "detail": null }, + { + "name": "a bracket turned half on the next lug pins on the first one's plane, facing it", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a brace that stands 1 degree off, naming how far apart the two sockets are", + "ok": true, + "detail": null + }, + { + "name": "close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", + "ok": true, + "detail": null + }, + { + "name": "close reports the part: its closure holds, and its connection still does", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: a second closure on a part that states one", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a socket a closure holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on the closing socket itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a socket a part is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close by a socket a part is attached by", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach onto a socket a closure holds", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: attach onto the closing socket", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a part on itself", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of sockets that may not mate", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of two sockets that are apart", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close on a mesh that is not a kit part", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close of a socket the part does not have", + "ok": true, + "detail": null + }, + { + "name": "set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", + "ok": true, + "detail": null + }, + { + "name": "and with the rod back the closure holds again: it is read from where the parts stand, not stored", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the part a closure names, to a size its pin no longer mates", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: set_params on the closing part, to a size its pin no longer mates", + "ok": true, + "detail": null + }, + { + "name": "set_params on the closing part that keeps its pin size is accepted and lists its own closure: a brace 0.1 shorter stops 0.1 short of the rod pin", + "ok": true, + "detail": null + }, + { + "name": "detach clears the brace's closure with its connection, and it stays where it stood", + "ok": true, + "detail": null + }, + { + "name": "a loose part that meets a socket may state a closure too", + "ok": true, + "detail": null + }, + { + "name": "a closure follows its other part through a rename", + "ok": true, + "detail": null + }, + { + "name": "a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", + "ok": true, + "detail": null + }, + { + "name": "detach of a part that states only a closure clears it and leaves the part where it stood", + "ok": true, + "detail": null + }, + { + "name": "and the socket the closure held is free again", + "ok": true, + "detail": null + }, { "name": "setObjectTransform on an attached child shows in its report: holds false, with the residual", "ok": true, @@ -405,11 +540,12 @@ "hostErrors": [], "readings": { "carried": 2.6e-07, + "closed": 3.9e-07, "cut": 0.25, - "kept": 1.5e-08, + "kept": 6e-08, "nudged": 0.00032, "roll": 6.6e-06, - "seated": 2.1e-07 + "seated": 3.9e-07 }, "tank": { "raw": { diff --git a/surfaces/blender/tests/test_kitbash.py b/surfaces/blender/tests/test_kitbash.py index 05da9e8..7300431 100644 --- a/surfaces/blender/tests/test_kitbash.py +++ b/surfaces/blender/tests/test_kitbash.py @@ -646,6 +646,52 @@ class MateTests(unittest.TestCase): with_default_tank = core.joint(parts["tank"], core.build(parts["tank"]), "lug_a", parts["bracket"], core.build(parts["bracket"]), "mount") self.assertIn("it is larger", core.mate_refusal(self.kit["socketTypes"], *with_default_tank)) # a lug seats a plate up to 0.3 of the tank's radius + CLOSED = 2.5e-9 # shipped 2.2e-16; least mutant 0.028 (J1, the bracket's pivot face 2*ear_t off its centre plane); separation 1.1e7 + + def brace(self, length, turned=180.0, off=0.0): + """(leg world, its rod_end, brace world, its end_b) of a braced leg on a tank's +x lugs: a bracket on lug_b + carries an actuator by its base, a bracket on lug_a at roll `turned` carries a strut of this length by end_a, + and the two rolls are solved by the law of cosines so the strut's end_b meets the rod's pin.""" + parts = self.kit["parts"] + built = {name: core.build(parts[part], given) for name, part, given in ( + ("tank", "tank", {"radius": 0.3, "length": 1.2}), ("bracket", "bracket", {}), ("leg", "actuator", {}), ("brace", "strut", {"width": 0.09, "length": length}))} + socket = lambda name, key: next(s for s in built[name].sockets if s["name"] == key) # noqa: E731 + upper = core.mate(socket("tank", "lug_b"), socket("bracket", "mount"), 0.0) + lower = core.mate(socket("tank", "lug_a"), socket("bracket", "mount"), turned) + p1, p2 = upper @ socket("bracket", "pivot")["matrix"], lower @ socket("bracket", "pivot")["matrix"] + a = socket("leg", "rod_end")["matrix"][2, 3] - socket("leg", "base")["matrix"][2, 3] # pin to pin along the leg + b = socket("brace", "end_b")["matrix"][2, 3] - socket("brace", "end_a")["matrix"][2, 3] + d = float(np.linalg.norm(p2[:3, 3] - p1[:3, 3])) + along, out = (p2[:3, 3] - p1[:3, 3]) / d, np.array([1.0, 0.0, 0.0]) # down the tank, and away from it + angle = math.acos((a * a + d * d - b * b) / (2 * a * d)) # at the upper pin, between the tank and the leg + knee = p1[:3, 3] + a * (math.cos(angle) * along + math.sin(angle) * out) + + def roll_to(pin, toward): # the roll that points a pinned member's axis (its socket's y) from this pin toward a point + toward = (toward - pin[:3, 3]) / np.linalg.norm(toward - pin[:3, 3]) + return math.degrees(math.atan2(np.cross(pin[:3, 1], toward) @ pin[:3, 2], pin[:3, 1] @ toward)) + + leg = upper @ core.mate(socket("bracket", "pivot"), socket("leg", "base"), roll_to(p1, knee)) + strut = lower @ core.mate(socket("bracket", "pivot"), socket("brace", "end_a"), roll_to(p2, knee) + off) + return leg, socket("leg", "rod_end"), strut, socket("brace", "end_b") + + def test_a_brace_closes_on_a_leg(self): + """closure. A tree states the leg and the brace; the brace's far pin meets the leg's only by the rolls. Mutants J1 + (the bracket's pivot face at x = -ear_t: the turned bracket pins 2*ear_t off the plane), J3 (closure_residual + drops the normal term: a bracket not turned reads 0) and J2.""" + worst = 0.0 + for length in (0.9, 1.1, 1.3): + worst = max(worst, core.closure_residual(*self.brace(length))) + self.assertAlmostEqual(core.closure_residual(*self.brace(length, turned=0.0)), 2.0, places=9) # not turned: the two pin faces look the same way + chord = 2 * (length - 0.081) * math.sin(math.radians(0.5)) # the brace swung 1 degree off: its far pin moves this far, and the residual is the move's largest entry + self.assertTrue(chord / math.sqrt(3) - 1e-12 <= core.closure_residual(*self.brace(length, off=1.0)) <= chord + 1e-12) + self.assertLess(worst, self.CLOSED) + leg, rod_end, strut, end_b = self.brace(1.1) + turned = strut @ core._roll(0.0) + turned[:3, :3] = strut[:3, :3] @ np.linalg.inv(end_b["matrix"][:3, :3]) @ core._rotation((0.0, 0.0, 77.0)) @ end_b["matrix"][:3, :3] + turned[:3, 3] += (strut @ end_b["matrix"])[:3, 3] - (turned @ end_b["matrix"])[:3, 3] + self.assertLess(core.closure_residual(leg, rod_end, turned, end_b), self.CLOSED) # a closure is a pin: any turn about it still meets + self.assertGreater(core.residual(leg, rod_end, turned, end_b, 0.0), 0.5) + def test_residual_is_how_far_the_child_stands_from_its_mate(self): sp, sc = self.sockets(*self.PAIRS[0]) world = np.eye(4) @@ -726,7 +772,7 @@ class MateTests(unittest.TestCase): ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report", - "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] + "brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.close", "brokkr_kitbash.boolean", "brokkr_kitbash.apply"] class HostFileTests(unittest.TestCase): @@ -767,10 +813,14 @@ class HostFileTests(unittest.TestCase): self.assertEqual(at.validate(attach, host)["roll"], 0) self.assertEqual(at.validate({**attach, "roll": -360}, host)["roll"], -360) boolean = {**envelope, "action": "brokkr_kitbash.boolean", "object_name": "Tank", "cutter": "Box"} + close = {**envelope, "action": "brokkr_kitbash.close", "object_name": "Brace", "socket": "end_b", "other_name": "Leg", "other_socket": "rod_end"} + self.assertEqual(at.validate(close, host)["other_socket"], "rod_end") self.assertEqual(at.validate(boolean, host)["operation"], "DIFFERENCE") for bad in ({**attach, "roll": 360.5}, {**attach, "socket": "a b"}, {**attach, "parent_socket": ""}, {**attach, "matrix": [1, 0, 0]}, {**boolean, "operation": "SLICE"}, {**boolean, "solver": "EXACT"}, {**boolean, "cutter": ""}, - {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}): + {**envelope, "action": "brokkr_kitbash.apply"}, {**envelope, "action": "brokkr_kitbash.detach", "object_name": "x" * 64}, + {**close, "socket": "end b"}, {**close, "other_socket": "x" * 33}, {**close, "other_name": ""}, {**close, "roll": 10}, + {k: v for k, v in close.items() if k != "other_socket"}): with self.assertRaises(at.IntentInvalid, msg=str(bad)): at.validate(bad, host) for row in self.document["actions"][4:]: @@ -819,6 +869,24 @@ class OwnershipTests(unittest.TestCase): self.assertEqual(writes, [" child[SOCKET], child[PARENT_SOCKET], child[ROLL] = stated"]) self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_attach")[1].split("class BROKKR_KITBASH_OT_")[0]) + def test_only_close_writes_a_closure(self): + """A closure is the closing part's three properties: close assigns them, detach deletes them, nothing else does + either, and close assigns nothing that places a part (mutant J4: close seats the part).""" + source = self.sources()["__init__.py"] + bodies = {body.split("(")[0]: body for body in source.split("class BROKKR_KITBASH_OT_")[1:]} + keys = r"(?:CLOSE|CLOSE_TO|CLOSE_TO_SOCKET|\"kit_close_\w+\")" + assigned = re.findall(rf"[^\n]*\[{keys}\][^\n=]*=(?!=)[^\n]*", source) + self.assertEqual(assigned, [" obj[CLOSE], obj[CLOSE_TO], obj[CLOSE_TO_SOCKET] = self.socket, other, self.other_socket"]) + self.assertIn(assigned[0], bodies["close"]) + deleted = re.findall(r"[^\n]*\(SOCKET, PARENT_SOCKET, ROLL, CLOSE, CLOSE_TO, CLOSE_TO_SOCKET\)[^\n]*\n[^\n]*\n\s*del obj\[key\]", source) + self.assertEqual((len(deleted), source.count("del obj["), "del obj[key]" in bodies["detach"]), (1, 1, True)) + self.assertEqual(source.count("CLOSE_TO]"), 1) # the one subscript write above; every read goes through .get + placing = r"matrix_basis|matrix_world\s*=(?!=)|matrix_parent_inverse|\.parent\s*=(?!=)|\bseat\(|\.location|\.rotation" + self.assertIsNone(re.search(placing, bodies["close"])) + for text in ("child.matrix_basis = basis", "obj.matrix_world = world", "obj.parent = other", "seat(obj, basis)"): + self.assertIsNotNone(re.search(placing, text)) + self.assertIsNotNone(re.search(placing, bodies["attach"])) + def test_the_patterns_bite(self): planted = ("value = eval(text)", "from brokkr_bridge import x", 'modifier.solver = "MANIFOLD"', "cutter.hide_render = True", 'obj["kit_parent"] = parent.name', 'obj.modifiers.new("Turn", "SCREW")') -- 2.47.3 From dc8dcdb0c3f1edee14aa33ec8a04fe7a1f992ffc Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 19:17:56 +0100 Subject: [PATCH 4/5] kitbash_assembly.py: a closure check that finds no closure fails by name instead of raising Mutant J5 (occupant ignores closures) ended the script on an AttributeError before any check printed; it now dies on the three occupancy refusals. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/kitbash_assembly.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index 27341a9..bd1d656 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -310,6 +310,10 @@ def closure_of(name): return report["parts"][0]["closure"] if report else {"error": receipt["message"]} +def closure_row(name): + return closure_of(name) or {} + + def without_closures(state): return {name: (*row[:3], {k: v for k, v in row[3].items() if not k.startswith("kit_close")}, *row[4:]) for name, row in state[0].items()}, state[1] @@ -360,14 +364,14 @@ refused("close of a socket the part does not have", "brokkr_kitbash.close", {"ob "part 'strut' has no socket 'end_c'") was = np.array(brace.matrix_world) receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") -found = closure_of("Brace") +found = closure_row("Brace") check("set_params that moves the leg's rod pin is accepted and moves no brace: the closure reads holds false with the rod's travel, here and in the report's closures", receipt["status"] == "accepted" and report and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": False}] and report["closure"] is None and found["holds"] is False and 0.05 < found["residual"] <= 0.15 + 1e-5 and np.array_equal(np.array(brace.matrix_world), was) and holds("Brace", "Lower", "end_a", "pivot", connection("Brace")["roll"])[0], [receipt["message"], report and report.get("closures"), found]) receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" - and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_of("Brace")["holds"] is True, [report and report.get("closures"), closure_of("Brace")]) + and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, @@ -383,16 +387,16 @@ check("detach clears the brace's closure with its connection, and it stays where and report["connection"] is None and not [k for k in brace.keys() if k.startswith(("kit_close", "kit_socket", "kit_parent", "kit_roll"))] and brace.parent is None and reading("kept", np.abs(np.array(brace.matrix_world) - before).max()) < KEPT, [receipt["message"], dict(brace.items())]) receipt, report = send("brokkr_kitbash.close", **CLOSING) -check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) +check("a loose part that meets a socket may state a closure too", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True and report["connection"] is None, receipt["message"]) leg.name = "Shin" -found = closure_of("Brace") +found = closure_row("Brace") check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) leg.name = "Leg" send("brokkr_kitbash.detach", object_name="Leg") bpy.data.objects.remove(leg) -found = closure_of("Brace") +found = closure_row("Brace") receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") -check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found == {**found, "to": None, "residual": None, "holds": False} +check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} and found.get("toSocket") == "rod_end" and receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": None, "holds": False}], [found, receipt["message"]]) before = np.array(brace.matrix_world) receipt, report = send("brokkr_kitbash.detach", object_name="Brace") -- 2.47.3 From 13ba0d05ac85655fe76ba15f14024710353ce5ea Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 20:15:01 +0100 Subject: [PATCH 5/5] brokkr_kitbash: a closure on a deleted, unlinked, scaled or doubly held part reads broken, with a reason Fixes the findings of verdict cut-kit-joints.s1. closure() reads the other part as gone when the pointer is empty or the object is in no collection: the pointer itself keeps a part deleted with the Delete operator in the file as an orphan, and the closure read it as holding. close refuses a part in no collection, and an orphaned closing part holds no socket. A closure's report gains reason, null when it holds: the other part is gone (to null); it cannot be read against (scaled by hand, not a kit part, of another kit; to names it); another part's closure names the same socket, as a duplicated closing part leaves, and then neither holds; or the sockets stand apart. set_params lists the closures its own part is an end of first, then the broken, then the rest, and leaves rows off the end when a receipt is full. It reads each kit file once per report: 3.9 s to 0.39 s at 150 closures, 12.8 s to 1.16 s at 450 (the cost was linear, two kit parses a closure). kitbash_assembly.py: close of a brace moved 3.2e-4 is refused, a receipt with room for one row keeps the opened closure and counts the other, and the unlink, Delete, scale and duplicate cases. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_kitbash/__init__.py | 106 +++++++++++------- surfaces/blender/docs/kitbash.md | 21 ++-- .../blender/tests/live/kitbash_assembly.py | 77 ++++++++++++- .../tests/live/kitbash_assembly.result.json | 61 ++++++++++ 4 files changed, 215 insertions(+), 50 deletions(-) diff --git a/surfaces/blender/brokkr_kitbash/__init__.py b/surfaces/blender/brokkr_kitbash/__init__.py index 4e9c72b..8edb244 100644 --- a/surfaces/blender/brokkr_kitbash/__init__.py +++ b/surfaces/blender/brokkr_kitbash/__init__.py @@ -95,9 +95,10 @@ def sync_bevel(obj, width: float) -> None: RIGID = 1e-5 # how far a world matrix's 3x3 may stand from a rotation -def kit_part_of(obj): +def kit_part_of(obj, kits=None): """(part, stored params) of a placed part, read from its ID properties. Refuses a part whose world transform is - not rigid: its socket frames would not be frames, and its size would have a second owner.""" + not rigid: its socket frames would not be frames, and its size would have a second owner. `kits` is a dict one + call may pass to read each kit file once while it reads many parts; nothing keeps it between calls.""" if PART not in obj: raise Refused(f"{obj.name!r} is not a kit part (it has no {PART} property); place_part makes one.") turn = np.array(obj.matrix_world)[:3, :3] @@ -111,12 +112,15 @@ def kit_part_of(obj): stored = None if not isinstance(stored, dict): raise Refused(f"{obj.name!r} has a {PARAMS} property that is not a JSON object.") - return core.part(core.load_kit(str(obj.get(KIT, ""))), str(obj[PART])), stored + name, kits = str(obj.get(KIT, "")), {} if kits is None else kits + if name not in kits: + kits[name] = core.load_kit(name) + return core.part(kits[name], str(obj[PART])), stored -def built_part(obj): +def built_part(obj, kits=None): """(part, the part built at the object's stored params): where its sockets are, baked or not.""" - part, stored = kit_part_of(obj) + part, stored = kit_part_of(obj, kits) return part, core.build(part, stored) @@ -137,17 +141,27 @@ def attached(obj) -> list: def closure(obj): """The closure a part states, (its socket, the other part or None, the other part's socket), or None. The - other part is a pointer: it follows a rename and reads None once the part is deleted. close, set_params, - detach and every report read it here.""" + other part is a pointer: it follows a rename. It reads None once the part is gone, which is when the pointer is + empty or the object is in no collection: the pointer itself keeps a deleted object in the file as an orphan. + close, set_params, detach and every report read it here.""" if CLOSE not in obj: return None other = obj.get(CLOSE_TO) - return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) else None, str(obj.get(CLOSE_TO_SOCKET, "")) + return str(obj[CLOSE]), other if isinstance(other, bpy.types.Object) and other.users_collection else None, str(obj.get(CLOSE_TO_SOCKET, "")) + + +def closers() -> dict: + """{(part, socket): [the parts in the scene whose closure names that socket]}, from one pass over the objects.""" + found = {} + for obj in bpy.data.objects: + if CLOSE in obj and obj.users_collection and closure(obj)[1] is not None: + found.setdefault((closure(obj)[1], closure(obj)[2]), []).append(obj) + return found def closing_on(part) -> list: """The parts whose closure names this one.""" - return [obj for obj in bpy.data.objects if CLOSE in obj and obj.get(CLOSE_TO) == part] + return [obj for (other, _), found in closers().items() if other == part for obj in found] def occupant(part, socket: str): @@ -161,9 +175,8 @@ def occupant(part, socket: str): return part.parent.name if part.parent else part.name if part.get(CLOSE) == socket: return closure(part)[1].name if closure(part)[1] else part.name - for other in closing_on(part): - if other.get(CLOSE_TO_SOCKET) == socket: - return other.name + for other in closers().get((part, socket), []): + return other.name return None @@ -218,46 +231,56 @@ def connection_report(obj, part, built): return row -def closure_report(obj, part, built): - """None for a part that states no closure, else what it states and whether it holds: the other part is a kit - part of the same kit, both sockets exist, and the two stand within HELD of meeting (core.closure_residual). - `to` is null when the other part is gone or is not a part of this kit. Derived at each report; stored nowhere.""" +def closure_report(obj, part, built, held=None, kits=None): + """None for a part that states no closure, else what it states, whether it holds and, when it does not, why + not: the other part is gone (`to` null); it is not a part this one can be read against (not a kit part, of + another kit, scaled, or without that socket); another part's closure names the same socket (a duplicated + closing part); or the two sockets stand more than HELD from meeting (core.closure_residual). Derived at each + report; stored nowhere. `held` is closers() and `kits` kit_part_of's, for a caller that reports many.""" stated = closure(obj) if stated is None: return None - row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False} + row = {"to": None, "socket": stated[0], "toSocket": stated[2], "residual": None, "holds": False, "reason": None} + if stated[1] is None: + row["reason"] = "the part it closed on is gone: deleted, or in no collection" + return row + row["to"] = stated[1].name try: - if stated[1] is None: - return row - other_part, other_built = built_part(stated[1]) - if other_part["kit"] != part["kit"]: - return row - row["to"] = stated[1].name + other_part, other_built = built_part(stated[1], kits) there, here = core.joint(other_part, other_built, stated[2], part, built, stated[0]) - except (Refused, core.KitError): + except (Refused, core.KitError) as error: + row["reason"] = str(error) return row row["residual"] = round(core.closure_residual(stated[1].matrix_world, there, obj.matrix_world, here), 9) - row["holds"] = bool(row["residual"] <= HELD) + rivals = [o.name for o in (closers() if held is None else held).get((stated[1], stated[2]), []) if o != obj] + if rivals: + row["reason"] = f"socket {stated[2]!r} of {stated[1].name!r} is also closed on by {rivals[0]!r}: one of them was copied; detach one" + elif row["residual"] > HELD: + row["reason"] = f"the two sockets stand {row['residual']:.6g} m apart" + row["holds"] = row["reason"] is None return row -def scene_closures(context, report: dict) -> list: - """Every closure stated in the scene as {part, to, holds}, by part name, for a set_params report: a change of - params can open a closure anywhere below the part. Rows are left out, and counted in closuresOmitted, once - the report would pass what a receipt carries.""" - rows, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 - for obj in sorted((o for o in context.scene.objects if o.type == "MESH" and CLOSE in o), key=lambda o: o.name): +def scene_closures(context, report: dict, ends=()) -> list: + """Every closure stated in the scene as {part, to, holds}, for a set_params report: a change of params can open + a closure anywhere below the part. The closures `ends` are parts of come first, then those that do not hold, + then the rest, each by name; rows that would take the report past what a receipt carries are left off the end + and counted in closuresOmitted.""" + held, kits, rows = closers(), {}, [] + for obj in (o for o in context.scene.objects if o.type == "MESH" and CLOSE in o): try: - found = closure_report(obj, *built_part(obj)) - except (Refused, core.KitError): - found = {"to": None, "holds": False} - row = {"part": obj.name, "to": found["to"], "holds": found["holds"]} + found = closure_report(obj, *built_part(obj, kits), held, kits) + except (Refused, core.KitError): # the closing part itself cannot be read (scaled) + found = {"to": closure(obj)[1].name if closure(obj)[1] else None, "holds": False} + rows.append((obj not in ends and closure(obj)[1] not in ends, found["holds"], obj.name, {"part": obj.name, "to": found["to"], "holds": found["holds"]})) + kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 40 + for *_, row in sorted(rows, key=lambda r: r[:3]): size += len(json.dumps(row, separators=(",", ":"))) + 1 if size > REPORT_LIMIT: - report["closuresOmitted"] = report.get("closuresOmitted", 0) + 1 - else: - rows.append(row) - return rows + report["closuresOmitted"] = len(rows) - len(kept) + break + kept.append(row) + return kept def part_report(obj, part, built) -> dict: @@ -392,7 +415,7 @@ class BROKKR_KITBASH_OT_set_params(PolishOperator): if seats: context.view_layer.update() report = part_report(obj, part, built) - report["closures"] = scene_closures(context, report) + report["closures"] = scene_closures(context, report, (obj,)) return report @@ -475,6 +498,9 @@ class BROKKR_KITBASH_OT_close(PolishOperator): other_part, other_built = built_part(other) if obj == other: raise Refused(f"{obj.name!r} cannot close on itself; nothing changed.") + for gone in (obj, other): + if not gone.users_collection: + raise Refused(f"{gone.name!r} is in no collection (a deleted object something still points to): a closure is between parts in the scene; nothing changed.") if closure(obj) is not None: raise Refused(f"{obj.name!r} already states a closure (its socket {closure(obj)[0]!r}): a part states one, and detach clears it; nothing changed.") there, here = mated(other, other_part, other_built, obj, part, built, (self.socket, self.other_socket, 0.0), "closing on") diff --git a/surfaces/blender/docs/kitbash.md b/surfaces/blender/docs/kitbash.md index bee7098..b46d57a 100644 --- a/surfaces/blender/docs/kitbash.md +++ b/surfaces/blender/docs/kitbash.md @@ -157,14 +157,15 @@ through that tree. **A closure** states the one thing a tree cannot: that a part's second socket also meets something. A brace hangs from its own bracket by one pin (a connection); its other pin meets the leg's rod (a closure), and the hull, leg and brace are then a loop. The closing part owns it, one at most, as three ID properties: -`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename -and reads empty once that part is deleted) and `kit_close_to_socket`. A spanning tree plus loop-closing +`kit_close_socket` (its own socket), `kit_close_to` (the other part, held as a pointer, so it follows a rename) +and `kit_close_to_socket`. The pointer keeps a deleted part in the file as an orphan, so a part counts as gone +when the pointer is empty or the object is in no collection. A spanning tree plus loop-closing constraints is how closed chains are usually stated (Featherstone, Rigid Body Dynamics Algorithms, ch. 8; MuJoCo's `connect` equality on its kinematic tree). `close` writes those three properties and nothing else. It never moves a part: it is accepted only when the two sockets already meet, origins together and normals opposed within 1e-5, at any roll (a closure is a pin). It -refuses, changing nothing: a part that is not a kit part or is scaled, a part closing on itself, two sockets +refuses, changing nothing: a part that is not a kit part, is scaled or is in no collection, a part closing on itself, two sockets that may not mate (the part it names counts as the parent), an occupied socket at either end, a part that already states a closure, and two sockets that do not meet, saying how far apart they stand. @@ -183,15 +184,19 @@ read these from. A part's report carries `closure`: `null`, or ```json -{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true} +{"to": "Leg", "socket": "end_b", "toSocket": "rod_end", "residual": 3.9e-07, "holds": true, "reason": null} ``` `residual` is the larger of the largest difference between the two origins and the largest entry of the sum of -the two normals; `holds` is true when it is at most 1e-5. `to` is `null`, and `holds` false, when the other part -is gone or is not a part of this kit. A closure is never seated. `set_params` on either end refuses a change +the two normals; `holds` is true when it is at most 1e-5 and nothing below applies. When it does not hold, +`reason` says why in a sentence: the other part is gone (`to` is then `null`); the other part cannot be read +against (not a kit part, of another kit, scaled by hand, or without that socket; `residual` is then `null`); +another part's closure names the same socket, which a duplicated closing part leaves behind and which makes +both read not held until one is detached; or the two sockets stand apart. A closure is never seated. `set_params` on either end refuses a change after which the two sockets may no longer mate (a pin of another size), naming the closure. A change that only moves a socket (an actuator's `extension` under a closed brace) is accepted and opens the closure: the report -of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, so the caller sees which +of `set_params` lists every closure in the scene as `closures: [{part, to, holds}]`, those its own part is an +end of first, then those that do not hold, then the rest, so the caller sees which ones it opened and can solve the rolls again, `detach` and `attach` the members, and find the closure holding. `detach` clears the closing part's closure together with its connection. @@ -265,7 +270,7 @@ vertices overflow. | --- | --- | --- | | `brokkr_kitbash.describe` | `kit` (default `mechanical`), `part` (default: all) | Parts with their params (type, min, max, default, doc) and sockets in the part frame at default params. Changes nothing. | | `brokkr_kitbash.place_part` | `kit`, `part`, `object_name`, `params` | A new mesh object at the origin: the part's mesh, a `Kit Bevel` modifier when the part has a bevel, and the three ID properties. Refuses a name an object already has. | -| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}` (with `closuresOmitted`, a count, if they would not fit a receipt). | +| `brokkr_kitbash.set_params` | `object_name`, `params` | Overlays `params` on the stored ones and rebuilds the mesh in the same datablock: modifiers and material slots stay, and the Bevel width follows. Per-face materials are carried by shape: each shape of the part keeps the material most of its faces had, whatever the new face count. Seats the part and the parts attached to it again; refuses a change that breaks a connection or a closure's mate, and a baked part. Reports the part and `closures`, every closure in the scene as `{part, to, holds}`: its own first, then the broken, then the rest; rows that would not fit a receipt are left off the end and counted in `closuresOmitted`. Each closure in the scene adds a few milliseconds (both its parts are built again to find their sockets). | | `brokkr_kitbash.report` | `object_name` (default: every kit part) | Each part as the scene has it: kit, part, params, faces, shells, each socket's world frame, `connection`, `closure` and `baked`. Changes nothing and evaluates no modifier. | | `brokkr_kitbash.attach` | `object_name` (the child), `socket`, `parent_name`, `parent_socket`, `roll` (degrees, -360 to 360, default 0) | Seats the child's socket on the parent's and parents it there. Reports the child. | | `brokkr_kitbash.detach` | `object_name` | Clears the part's connection and the closure it states; it stays where it stands. Refuses a part that has neither. | diff --git a/surfaces/blender/tests/live/kitbash_assembly.py b/surfaces/blender/tests/live/kitbash_assembly.py index bd1d656..d5a4a00 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.py +++ b/surfaces/blender/tests/live/kitbash_assembly.py @@ -26,6 +26,7 @@ from pathlib import Path import bmesh import bpy import numpy as np +from mathutils import Matrix SURFACE = Path(__file__).resolve().parents[2] sys.path.insert(0, str(SURFACE / "tools")) @@ -330,6 +331,16 @@ check("refused, scene unchanged: close of a brace that stands 1 degree off, nami and named and abs(float(named.group(1)) - apart) < 1e-5 and 0.01 < apart < 0.02 and scene_state() == state, [receipt["message"], apart]) send("brokkr_kitbash.detach", object_name="Brace") send("brokkr_kitbash.attach", object_name="Brace", socket="end_a", parent_name="Lower", parent_socket="pivot", roll=roll_to(p2, knee)) +# close-tolerance: the brace moved NUDGE (3.2e-4) off its seat. close accepts up to HELD, 1e-5; least claimed mutant 5e-4 (N2, 50 times +# HELD); NUDGE is 32 times the one and 0.64 of the other, as for the connection's own check below. +seat_was = np.array(brace.matrix_basis)[:3, 3] +send("setObjectTransform", targetObjectName="Brace", location=(seat_was + np.array(lower.matrix_world)[:3, :3].T @ [0.0, 0.0, NUDGE]).tolist()) +state = scene_state() +receipt, _ = send("brokkr_kitbash.close", **CLOSING) +named = re.search(r"stand (\S+) m apart", str(receipt["message"])) +check("refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", receipt["status"] != "accepted" and named + and abs(reading("close nudged", float(named.group(1))) - NUDGE) < 0.1 * NUDGE and scene_state() == state, receipt["message"]) +send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.1") # seats it again state = scene_state() receipt, report = send("brokkr_kitbash.close", **CLOSING) check("close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", receipt["status"] == "accepted" @@ -339,7 +350,7 @@ check("close states the closure on the brace when its end_b meets the leg's rod and not [k for k in leg.keys() if k.startswith("kit_close")], [receipt["message"], dict(brace.items())]) check("close reports the part: its closure holds, and its connection still does", report and report["object"] == "Brace" and report["closure"] == {**report["closure"], "to": "Leg", "socket": "end_b", "toSocket": "rod_end", "holds": True} - and reading("closed", report["closure"]["residual"]) <= 1e-5 and held(report) and closure_of("Brace") == report["closure"] + and reading("closed", report["closure"]["residual"]) <= 1e-5 and report["closure"]["reason"] is None and held(report) and closure_of("Brace") == report["closure"] and closure_of("Leg") is None, report) refused("a second closure on a part that states one", "brokkr_kitbash.close", {"object_name": "Brace", "socket": "end_b_back", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Brace' already states a closure (its socket 'end_b')") @@ -372,6 +383,51 @@ check("set_params that moves the leg's rod pin is accepted and moves no brace: t receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") check("and with the rod back the closure holds again: it is read from where the parts stand, not stored", receipt["status"] == "accepted" and report["closures"] == [{"part": "Brace", "to": "Leg", "holds": True}] and closure_row("Brace").get("holds") is True, [report and report.get("closures"), closure_of("Brace")]) +# closures-omitted: a second closure, named to sort first, far from the leg; then a receipt with room for one row. Mutant N5 (never +# omit) lists two rows; rows by name alone would keep Aa_Loose and drop the one this call opened. +anchor, loose = place("Aa_Anchor", "strut", "width=0.09", location=[0.0, -20.0, 0.0]), place("Aa_Loose", "strut", "width=0.09") +meet = Matrix((np.array(anchor.matrix_world) @ core.mate(next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_b"), + next(s for s in core.build(kit["parts"]["strut"], {"width": 0.09}).sockets if s["name"] == "end_a"), 40.0)).tolist()) +send("setObjectTransform", targetObjectName="Aa_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ"))) +receipt, report = send("brokkr_kitbash.close", object_name="Aa_Loose", socket="end_a", other_name="Aa_Anchor", other_socket="end_b") +check("a loose part placed to meet a socket closes on it", receipt["status"] == "accepted" and report and report["closure"]["holds"] is True, [receipt["message"], report and report["closure"]]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +ROWS = [{"part": "Brace", "to": "Leg", "holds": False}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": True}] +check("set_params lists the closures its own part is an end of first, then the rest", receipt["status"] == "accepted" and report["closures"] == ROWS + and "closuresOmitted" not in report, report and report.get("closures")) +addon = sys.modules["brokkr_kitbash"] +limit = addon.REPORT_LIMIT +addon.REPORT_LIMIT = len(json.dumps({k: v for k, v in report.items() if k != "closures"}, separators=(",", ":"))) + 40 + len(json.dumps(ROWS[0], separators=(",", ":"))) + 1 +receipt, report = send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.3") +addon.REPORT_LIMIT = limit +check("with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", receipt["status"] == "accepted" + and report["closures"] == ROWS[:1] and report.get("closuresOmitted") == 1 and np.array_equal(np.array(brace.matrix_world), was), report and [report.get("closures"), report.get("closuresOmitted")]) +receipt, report = send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") +check("and a closure another part's set_params opened comes before one that holds", receipt["status"] == "accepted" + and report["closures"] == [{"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}, {"part": "Brace", "to": "Leg", "holds": False}], report and report.get("closures")) +send("brokkr_kitbash.detach", object_name="Aa_Loose") +send("brokkr_kitbash.set_params", object_name="Leg", params="extension=0.15") +leg.scale = (1.0001, 1.0, 1.0) +bpy.context.view_layer.update() +found = closure_row("Brace") +leg.scale = (1.0, 1.0, 1.0) +bpy.context.view_layer.update() +check("a closure on a part scaled by hand reads broken, naming the part and why, not gone", found.get("to") == "Leg" and found.get("holds") is False and found.get("residual") is None + and "'Leg' is scaled, mirrored or sheared" in str(found.get("reason")) and closure_row("Brace").get("holds") is True, found) +twin = brace.copy() # as Shift-D leaves it: a second part stating the same closure +twin.data = brace.data.copy() +twin.name = "Brace_twin" +bpy.context.scene.collection.objects.link(twin) +found, other = closure_row("Brace"), closure_row("Brace_twin") +check("two parts that state a closure on one socket both read not held, each naming the other", found.get("holds") is False and other.get("holds") is False + and "is also closed on by 'Brace_twin'" in str(found.get("reason")) and "is also closed on by 'Brace'" in str(other.get("reason")), [found, other]) +tie["keeper"] = twin # something still points at the copy, so Delete leaves it in the file with its closure properties +with bpy.context.temp_override(selected_objects=[twin], active_object=twin): + bpy.ops.object.delete() +check("and with the copy deleted the closure holds again, though the copy is still in the file stating its own", closure_row("Brace").get("holds") is True + and bpy.data.objects.get("Brace_twin") is not None and "kit_close_to" in bpy.data.objects["Brace_twin"], closure_of("Brace")) +del tie["keeper"] +bpy.data.objects.remove(bpy.data.objects["Brace_twin"]) refused("set_params on the part a closure names, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Leg", "params": "body_r=0.07"}, "'Brace' closing on 'Leg': socket 'end_b' (pivot, size 0.054) and parent socket 'rod_end' (pivot, size 0.063)") refused("set_params on the closing part, to a size its pin no longer mates", "brokkr_kitbash.set_params", {"object_name": "Brace", "params": "width=0.1"}, @@ -393,7 +449,24 @@ found = closure_row("Brace") check("a closure follows its other part through a rename", found.get("to") == "Shin" and found.get("holds") is True, found) leg.name = "Leg" send("brokkr_kitbash.detach", object_name="Leg") -bpy.data.objects.remove(leg) +homes = list(leg.users_collection) +for home in homes: + home.objects.unlink(leg) +found = closure_row("Brace") +check("a closure on a part unlinked from every collection reads to null, holds false, with the reason", found.get("to", 0) is None and found.get("holds") is False + and "gone" in str(found.get("reason")) and "Leg" in bpy.data.objects, found) +for home in homes: + home.objects.link(leg) +check("and holds again once the part is linked back", closure_row("Brace").get("holds") is True, closure_of("Brace")) +with bpy.context.temp_override(selected_objects=[leg], active_object=leg): + bpy.ops.object.delete() # the ordinary Delete: the closure's pointer keeps the object in the file as an orphan +found = closure_row("Brace") +check("a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", found.get("to", 0) is None + and found.get("holds") is False and found.get("residual", 0) is None and bpy.data.objects.get("Leg") is not None and brace.get("kit_close_to") is not None, [found, list(bpy.data.objects.keys())]) +refused("close onto a deleted part that is still in the file", "brokkr_kitbash.close", + {"object_name": "Tie", "socket": "end_a", "other_name": "Leg", "other_socket": "rod_end_back"}, "'Leg' is in no collection") +if "Leg" in bpy.data.objects: + bpy.data.objects.remove(bpy.data.objects["Leg"]) found = closure_row("Brace") receipt, report = send("brokkr_kitbash.set_params", object_name="Brace", params="length=1.0") check("a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", found and found == {**found, "to": None, "residual": None, "holds": False} diff --git a/surfaces/blender/tests/live/kitbash_assembly.result.json b/surfaces/blender/tests/live/kitbash_assembly.result.json index ad7a3a7..98697ee 100644 --- a/surfaces/blender/tests/live/kitbash_assembly.result.json +++ b/surfaces/blender/tests/live/kitbash_assembly.result.json @@ -151,6 +151,11 @@ "ok": true, "detail": null }, + { + "name": "refused, scene unchanged: close of a brace moved by NUDGE, which a report would read as not held", + "ok": true, + "detail": null + }, { "name": "close states the closure on the brace when its end_b meets the leg's rod pin, and moves nothing", "ok": true, @@ -231,6 +236,41 @@ "ok": true, "detail": null }, + { + "name": "a loose part placed to meet a socket closes on it", + "ok": true, + "detail": null + }, + { + "name": "set_params lists the closures its own part is an end of first, then the rest", + "ok": true, + "detail": null + }, + { + "name": "with room for one row in the receipt, set_params keeps the closure it opened and counts the other in closuresOmitted", + "ok": true, + "detail": null + }, + { + "name": "and a closure another part's set_params opened comes before one that holds", + "ok": true, + "detail": null + }, + { + "name": "a closure on a part scaled by hand reads broken, naming the part and why, not gone", + "ok": true, + "detail": null + }, + { + "name": "two parts that state a closure on one socket both read not held, each naming the other", + "ok": true, + "detail": null + }, + { + "name": "and with the copy deleted the closure holds again, though the copy is still in the file stating its own", + "ok": true, + "detail": null + }, { "name": "refused, scene unchanged: set_params on the part a closure names, to a size its pin no longer mates", "ok": true, @@ -261,6 +301,26 @@ "ok": true, "detail": null }, + { + "name": "a closure on a part unlinked from every collection reads to null, holds false, with the reason", + "ok": true, + "detail": null + }, + { + "name": "and holds again once the part is linked back", + "ok": true, + "detail": null + }, + { + "name": "a closure on a part deleted with the Delete operator reads to null, holds false, though the object is still in the file", + "ok": true, + "detail": null + }, + { + "name": "refused, scene unchanged: close onto a deleted part that is still in the file", + "ok": true, + "detail": null + }, { "name": "a closure whose other part is gone reads to null and holds false, and set_params on the closing part still works", "ok": true, @@ -540,6 +600,7 @@ "hostErrors": [], "readings": { "carried": 2.6e-07, + "close nudged": 0.00032, "closed": 3.9e-07, "cut": 0.25, "kept": 6e-08, -- 2.47.3