From 804863ccc92518bb335d2d3a63352922bd918e0a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 1 Dec 2026 08:38:05 +0100 Subject: [PATCH] brokkr_rig: no thin part is a reported outcome; shape rays reach the longest side; gauges, seeds and shrink pinned in core (Soul s2 fix batch) tendrils on a mesh with no rings reports zero chains instead of raising. The shape-diameter ray reach was half the longest side, so a body wider than that read thin; it is the longest side now. chain_gauges, seed_triangle and shrink_fraction move into core with tests; the live test pins stale colliders and the no-thin-part mesh. Co-Authored-By: Claude Sonnet 5.5 --- surfaces/blender/brokkr_rig/__init__.py | 19 +++---- surfaces/blender/brokkr_rig/core.py | 25 +++++++++ surfaces/blender/docs/rig.md | 9 +++- surfaces/blender/tests/live/rig.py | 29 ++++++++++- surfaces/blender/tests/live/rig.result.json | 50 +++++++++++++++--- surfaces/blender/tests/test_rig.py | 56 ++++++++++++++++++--- 6 files changed, 157 insertions(+), 31 deletions(-) diff --git a/surfaces/blender/brokkr_rig/__init__.py b/surfaces/blender/brokkr_rig/__init__.py index b153ccd..39dbecb 100644 --- a/surfaces/blender/brokkr_rig/__init__.py +++ b/surfaces/blender/brokkr_rig/__init__.py @@ -174,7 +174,7 @@ def shape_diameter(w: SimpleNamespace) -> np.ndarray: live = (w.TW[:, 0] != w.TW[:, 1]) & (w.TW[:, 1] != w.TW[:, 2]) & (w.TW[:, 0] != w.TW[:, 2]) tree = BVHTree.FromPolygons([tuple(p) for p in w.Vw], [tuple(int(i) for i in t) for t in w.TW[live]]) jitter = np.random.default_rng(0).normal(0.0, 0.35, (w.count, 4, 3)) - reach, lift = 0.5 * w.length, 1e-5 * w.length + reach, lift = w.length, 1e-5 * w.length out = np.zeros(w.count) for i in range(w.count): inward = -w.N[i] @@ -264,9 +264,7 @@ class BROKKR_RIG_OT_body(PolishOperator): nearest = lambda point: int(np.argmin(((centroid - np.asarray(point)) ** 2).sum(axis=1))) # noqa: E731 sd = shape_diameter(w) # the spine's seeds take body surface: a triangle with a thin vertex is a tendril or a sheet solid = (sd[w.TW] >= SPINE_THICK * w.length).all(axis=1) - pool = np.flatnonzero(solid) if solid.any() else np.arange(len(w.TW)) - nearest_solid = lambda point: int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) # noqa: E731 - placed = [(nearest_solid(point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] + placed = [(core.seed_triangle(centroid, solid, point), 0) for point in ([a for a, _ in spine] + [spine[-1][1]])] placed += [(nearest(point), parts.index(name) if name in parts else 0) for name, point in seeds] part, _ = polish.grow_parts(len(w.TW), pairs, polish.crease_costs(w.Vw, w.TW, pairs, self.crease_cost), placed) part[part < 0] = 0 @@ -407,19 +405,14 @@ class BROKKR_RIG_OT_tendrils(PolishOperator): shells = len(np.unique(polish.components(w.count, w.E[lost[w.E[:, 0]] & lost[w.E[:, 1]]])[lost])) if lost.any() else 0 branches = int(sum(1 for r in range(len(found.parent)) if not found.on_main[r] and found.parent[r] >= 0 and found.on_main[found.parent[r]] and found.tree[r] in {c.tree for c in kept})) - on_chain = (found.ring >= 0) & np.isin(found.tree[np.maximum(found.ring, 0)], [c.tree for c in kept]) - kept_trees = [c.tree for c in kept] - trees = found.tree[found.ring[on_chain]] - open_share = float(np.bincount(trees).max() / w.count) if on_chain.any() else 0.0 # the biggest chain's share of the mesh - ring_of = np.where(found.ring >= 0, found.tree[np.maximum(found.ring, 0)], -1) - a, b = ring_of[w.E[:, 0]], ring_of[w.E[:, 1]] - fused = int(((a >= 0) & (b >= 0) & (a != b) & np.isin(a, [c.tree for c in kept]) & np.isin(b, [c.tree for c in kept])).sum()) + gauges = core.chain_gauges(found, w.E, [c.tree for c in kept], w.count) + open_share = gauges["largestChainShare"] warnings = [] if open_share >= OPEN_SHEET_WARN: warnings.append(f"one chain holds {open_share:.0%} of the mesh: a plate of a hull may have become a chain; " "raise tau or fold_bands, or rig a mesh whose tendrils are tubes") return {"object": obj.name, "armature": arm.name, "bodyVertices": int(found.body.sum()), "chains": len(springs), - "chainVertexShare": float(on_chain.mean()), "largestChainShare": open_share, "fusedContacts": fused, "warnings": warnings, + **gauges, "warnings": warnings, "springBones": int(sum(len(s.pos) for s in springs)), "branchesRigid": branches, "veinsFolded": len(found.chains) - len(kept), "shellsAttached": shells, "unreachedVertices": int(lost.sum()), "rings": int(len(found.parent)), @@ -469,7 +462,7 @@ class BROKKR_RIG_OT_colliders(PolishOperator): if cleared < radius: made["shrunk"] += 1 made["shrinks"].append({"bone": bone.name, "before": round(float(radius), 6), "after": round(float(max(cleared, 0.0)), 6)}) - made["shrunkMax"] = round(max(made["shrunkMax"], float(1.0 - max(cleared, 0.0) / radius)), 4) + made["shrunkMax"] = round(max(made["shrunkMax"], core.shrink_fraction(radius, cleared)), 4) if cleared <= 0: made["dropped"] += 1 continue diff --git a/surfaces/blender/brokkr_rig/core.py b/surfaces/blender/brokkr_rig/core.py index 35c8ba9..2638c2f 100644 --- a/surfaces/blender/brokkr_rig/core.py +++ b/surfaces/blender/brokkr_rig/core.py @@ -356,3 +356,28 @@ def joint_params(sd: np.ndarray, stiffness: float, tip_ratio: float, hit_scale: linearly from the root's value to tip_ratio times it at the tip; the hit radius is half the diameter times hit_scale.""" last = len(sd) - 1 return stiffness * (1.0 + (tip_ratio - 1.0) * np.arange(last + 1) / last), 0.5 * np.asarray(sd) * hit_scale + + +# --- seeds and gauges ------------------------------------------------------------------------------------ + +def seed_triangle(centroid: np.ndarray, solid: np.ndarray, point: np.ndarray) -> int: + """The triangle nearest point among the solid ones (all of them when none is solid).""" + pool = np.flatnonzero(solid) if solid.any() else np.arange(len(centroid)) + return int(pool[np.argmin(((centroid[pool] - np.asarray(point)) ** 2).sum(axis=1))]) + + +def chain_gauges(found: SimpleNamespace, E: np.ndarray, kept: list, count: int) -> dict: + """What a rig looks like from outside: the share of the mesh on kept chains, the biggest chain's share, and the + mesh edges joining two different kept chains. kept are the trees of the chains that are not folded.""" + ring = np.maximum(found.ring, 0) + tree = np.where(found.ring >= 0, found.tree[ring] if len(found.tree) else -1, -1) + mine = np.isin(tree, kept) & (found.ring >= 0) + a, b = tree[E[:, 0]], tree[E[:, 1]] + return {"chainVertexShare": float(mine.sum() / max(count, 1)), + "largestChainShare": float(np.bincount(tree[mine]).max() / max(count, 1)) if mine.any() else 0.0, + "fusedContacts": int((np.isin(a, kept) & np.isin(b, kept) & (a != b)).sum())} + + +def shrink_fraction(before: float, after: float) -> float: + """How much of a collider's radius a shrink took: 0 none, 1 all.""" + return 1.0 - max(after, 0.0) / before diff --git a/surfaces/blender/docs/rig.md b/surfaces/blender/docs/rig.md index cf85323..379dd96 100644 --- a/surfaces/blender/docs/rig.md +++ b/surfaces/blender/docs/rig.md @@ -94,7 +94,14 @@ gauges the rig: `chainVertexShare`, `largestChainShare` (the biggest chain's sha (mesh edges joining two different chains). `warnings` says when one chain holds 4.2% of the mesh or more, which is what a hull plate that became a chain looks like (the lace leviathan reads 2.3%, the skeletal and mantle hulls 7.7% and 11.2%; the bound is the geometric mean of the first two). An open sheet reads shape diameter 0, so on a -hull the builder succeeds; read the warning. +hull the builder succeeds; read the warning. The gauge is fitted to four meshes and catches a hull whose plates +merge into a few big chains. It does not catch one that fragments into many small plate chains: the submarine +reads 2.7% largest (9 chains, 11% of the mesh on chains) and gets no warning, and no second signal tried +(open-sheet share, ring width in shape diameters, share of the mesh on chains) separated it from the leviathan. +Look at the chains in a render before trusting a hull's rig. + +A mesh with no thin part (the crystal emblem) has no rings: `tendrils` is accepted, reports `chains` 0, removes +any chains from an earlier run, and leaves the skin as `body` made it. ### colliders diff --git a/surfaces/blender/tests/live/rig.py b/surfaces/blender/tests/live/rig.py index 26de79f..09c4396 100644 --- a/surfaces/blender/tests/live/rig.py +++ b/surfaces/blender/tests/live/rig.py @@ -206,8 +206,9 @@ check("tendrils, other knobs, then the first knobs again restores the weights an check("the tendrils report says what it sees", tendrils and {"warnings", "largestChainShare", "chainVertexShare", "fusedContacts"} <= set(tendrils) and len(tendrils["warnings"]) == 1 and "one chain holds" in tendrils["warnings"][0], tendrils) # five chains hold 13% each at most: hull-like by the gauge receipt, colliders = send("brokkr_rig.colliders", object_name="Whale") -check("the colliders report lists each shrink", colliders and len(colliders["shrinks"]) == colliders["shrunk"] - and all(x["after"] < x["before"] for x in colliders["shrinks"]), colliders) +check("the colliders report lists each shrink and the largest share taken", colliders and colliders["shrunk"] > 0 + and len(colliders["shrinks"]) == colliders["shrunk"] and all(x["after"] < x["before"] for x in colliders["shrinks"]) + and abs(colliders["shrunkMax"] - max(1 - x["after"] / x["before"] for x in colliders["shrinks"])) < 1e-3, colliders) R["colliders"] = colliders # --- export: the five attributes, weights, extension, structure ---------------------------------------------------- @@ -294,6 +295,7 @@ chain_bones = sum(1 for b in arm.data.bones if "rig_chain" in b) receipt, rebody = send("brokkr_rig.body", object_name="Whale", armature_name=arm.name, seeds="jaw=0,0.45,0.05") check("body again clears the chain bones it would orphan", rebody and rebody["chainBonesCleared"] == chain_bones > 0 and not any("rig_chain" in b for b in arm.data.bones), rebody) +check("body again leaves no collider from the old body", not any("rig_colliders" in b for b in arm.data.bones), None) send("exportGltf", filepath="cleared.glb", extras=False, yUp=True, applyModifiers=True) cleared_json, _, _ = glb_json(WORK / "cleared.glb") check("an armature with no chains exports no springs", "VRMC_springBone" not in cleared_json.get("extensions", {}), None) @@ -306,6 +308,29 @@ receipt, rerun = send("brokkr_rig.tendrils", object_name="Whale", tau=0.05, band check("tendrils after the second body rebuilds the same chains", rerun and tendrils and rerun["chains"] == tendrils["chains"] and rerun["springBones"] == tendrils["springBones"], [rerun, tendrils]) +# --- a mesh with no thin part: no chains is an outcome, not a crash, and the skin stays the body's -------------------------- +ball = bmesh.new() +bmesh.ops.create_uvsphere(ball, u_segments=24, v_segments=12, radius=0.3, calc_uvs=True) +ball_mesh = bpy.data.meshes.new("Ball") +ball.to_mesh(ball_mesh) +ball.free() +ball_obj = bpy.data.objects.new("Ball", ball_mesh) +bpy.context.scene.collection.objects.link(ball_obj) +send("brokkr_rig.body", object_name="Ball", spine_bones=4) + + +def ball_weights(): + names = [g.name for g in ball_obj.vertex_groups] + return [sorted((names[e.group], e.weight) for e in v.groups) for v in ball_obj.data.vertices] + + +before = ball_weights() +receipt, bald = send("brokkr_rig.tendrils", object_name="Ball", tau=0.05, band=0.04, dilate=0.01) +check("tendrils on a mesh with no thin part is accepted and reports no chains", receipt["status"] == "accepted" and bald and bald["chains"] == 0 + and bald["springBones"] == 0 and bald["rings"] == 0 and bald["fusedContacts"] == 0, [receipt["message"], bald]) +check("and leaves the skin as body made it, with no chain bones", ball_weights() == before + and not any("rig_chain" in b for b in bpy.data.objects["Ball.rig"].data.bones), None) + R["ok"] = all(c["ok"] for c in R["checks"]) Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8") for c in R["checks"]: diff --git a/surfaces/blender/tests/live/rig.result.json b/surfaces/blender/tests/live/rig.result.json index e00bb76..9cc1424 100644 --- a/surfaces/blender/tests/live/rig.result.json +++ b/surfaces/blender/tests/live/rig.result.json @@ -125,7 +125,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } @@ -165,13 +165,13 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } }, { - "name": "the colliders report lists each shrink", + "name": "the colliders report lists each shrink and the largest share taken", "ok": true, "detail": { "capsules": 6, @@ -210,7 +210,7 @@ { "name": "exportGltf accepted", "ok": true, - "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-237ky4n3\\whale.glb (301188 bytes)." + "detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-rig-live-l9ustbpi\\whale.glb (301188 bytes)." }, { "name": "VRMC_springBone is in extensions and extensionsUsed", @@ -383,6 +383,11 @@ "weldedVertices": 1546 } }, + { + "name": "body again leaves no collider from the old body", + "ok": true, + "detail": null + }, { "name": "an armature with no chains exports no springs", "ok": true, @@ -425,7 +430,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, @@ -446,11 +451,42 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 } ] + }, + { + "name": "tendrils on a mesh with no thin part is accepted and reports no chains", + "ok": true, + "detail": [ + "Operator brokkr_rig.tendrils finished.", + { + "object": "Ball", + "armature": "Ball.rig", + "bodyVertices": 266, + "chains": 0, + "chainVertexShare": 0.0, + "largestChainShare": 0.0, + "fusedContacts": 0, + "warnings": [], + "springBones": 0, + "branchesRigid": 0, + "veinsFolded": 0, + "shellsAttached": 0, + "unreachedVertices": 0, + "rings": 0, + "shapeDiameterMedian": 0.5665553510189056, + "tau": 0.03000000163912775, + "band": 0.024000000417232492 + } + ] + }, + { + "name": "and leaves the skin as body made it, with no chain bones", + "ok": true, + "detail": null } ], "hostErrors": [], @@ -566,7 +602,7 @@ "shellsAttached": 1, "unreachedVertices": 42, "rings": 59, - "shapeDiameterMedian": 0.15453927963972092, + "shapeDiameterMedian": 0.15566504001617432, "tau": 0.05000000074505806, "band": 0.03999999910593033 }, diff --git a/surfaces/blender/tests/test_rig.py b/surfaces/blender/tests/test_rig.py index 21755b0..e25cae1 100644 --- a/surfaces/blender/tests/test_rig.py +++ b/surfaces/blender/tests/test_rig.py @@ -40,7 +40,7 @@ if np is not None: BAND, TAU = 0.25, 0.1 -def tube_graph(vein: bool = True, perm=None): +def tube_graph(vein: bool = True, perm=None, trunk_stations: int = 9): """A body of three stations (thick), a trunk of nine stations along x that forks at station 5 into a branch of three along y, a short vein of two stations off the body (vein=True also adds a lone far ring joined by one long edge and a detached shell). Every station is two vertices 0.01 apart, so a @@ -61,7 +61,7 @@ def tube_graph(vein: bool = True, perm=None): for a, b in zip(body, body[1:]): join(a, b) trunk, last = [], body[-1] - for k in range(1, 10): + for k in range(1, trunk_stations + 1): trunk.append(station(0.11 * k, 0.0)) join(last, trunk[-1]) last = trunk[-1] @@ -95,8 +95,8 @@ def tube_graph(vein: bool = True, perm=None): return V, E, sd, {"body": body, "trunk": trunk, "branch": branch, "vein": veins, "lone": lone, "shell": shell} -def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None): - V, E, sd, at_ = tube_graph(vein, perm) +def extract(fold_bands=1.5, min_joints=1, vein=True, perm=None, trunk_stations=9): + V, E, sd, at_ = tube_graph(vein, perm, trunk_stations) return V, E, sd, at_, core.extract(V, E, sd, TAU, BAND, 0.0, fold_bands, min_joints) @@ -157,12 +157,52 @@ class RingTests(unittest.TestCase): @unittest.skipIf(np is None, "numpy") def test_the_main_path_is_the_tallest_subtree_however_the_vertices_are_numbered(self): - """Dies if the main path is the shortest subtree, or the lowest ring id.""" + """Dies if the main path is the shortest subtree, or the lowest ring id. The long trunk (12 stations, six rings + past the fork) is taller than the branch (one ring), so the height alone decides, never the size tie-break.""" for seed in range(8): - perm = np.random.default_rng(seed).permutation(len(tube_graph(False)[0])) - V, E, sd, s, f = extract(vein=False, perm=perm) + perm = np.random.default_rng(seed).permutation(len(tube_graph(False, trunk_stations=12)[0])) + V, E, sd, s, f = extract(vein=False, perm=perm, trunk_stations=12) leaf = f.chains[0].rings[-1] - self.assertIn(int(perm[s["trunk"][8]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertIn(int(perm[s["trunk"][11]]), np.flatnonzero(f.ring == leaf).tolist(), seed) + self.assertEqual(len(f.chains[0].rings), 6) + + @unittest.skipIf(np is None, "numpy") + def test_a_mesh_with_no_thin_part_has_no_rings_and_no_chains(self): + V, E, sd, s = tube_graph(False) + f = core.extract(V, E, np.ones(len(V)), TAU, BAND, 0.0, 1.5, 1) + self.assertEqual((len(f.parent), f.chains, int(f.body.sum())), (0, [], len(V))) + self.assertEqual(core.plan(V, np.ones(len(V)), f, BAND), []) + self.assertEqual(core.chain_gauges(f, E, [], len(V)), {"chainVertexShare": 0.0, "largestChainShare": 0.0, "fusedContacts": 0}) + idx, w, start = core.tendril_weights(V, E, f, [], np.zeros((len(V), 4), dtype=np.int64), np.eye(4)[[0] * len(V)], 1, BAND, 0.5) + self.assertTrue((w[:, 0] == 1.0).all() and start == []) + + @unittest.skipIf(np is None, "numpy") + def test_gauges_count_the_biggest_chain_the_total_and_only_edges_between_chains(self): + """Dies if the largest share is the total, or fused contacts count edges inside one chain.""" + V, E, sd, s, f = extract() + kept = [c.tree for c in f.chains if not c.folded] + self.assertEqual(len(kept), 2) # the trunk and the lone ring + n = len(V) + own = core.chain_gauges(f, E, kept, n) + self.assertAlmostEqual(own["largestChainShare"], 24 / n) # the trunk's 9 stations and the branch's 3, two vertices each + self.assertAlmostEqual(own["chainVertexShare"], 26 / n) + self.assertEqual(own["fusedContacts"], 0) # trunk-branch edges are one chain + crossed = np.vstack([E, [s["trunk"][2], s["lone"][0]], [s["trunk"][3], s["lone"][0]]]) + self.assertEqual(core.chain_gauges(f, crossed, kept, n)["fusedContacts"], 2) + + @unittest.skipIf(np is None, "numpy") + def test_a_spine_seed_takes_the_nearest_solid_triangle_not_the_nearest_triangle(self): + """Dies if the seed is the nearest triangle whatever its thickness, or if no solid triangle leaves it nowhere.""" + centre = np.array([[0.0, 0, 0], [1.0, 0, 0], [3.0, 0, 0]]) + solid = np.array([False, True, True]) + self.assertEqual(core.seed_triangle(centre, solid, np.array([0.1, 0, 0])), 1) + self.assertEqual(core.seed_triangle(centre, np.array([False] * 3), np.array([0.1, 0, 0])), 0) # nothing solid: the nearest + + @unittest.skipIf(np is None, "numpy") + def test_shrink_fraction_is_the_share_of_the_radius_taken(self): + self.assertAlmostEqual(core.shrink_fraction(0.1, 0.0079), 0.921) + self.assertEqual(core.shrink_fraction(0.2, 0.2), 0.0) + self.assertEqual(core.shrink_fraction(0.2, -0.1), 1.0) class WeightTests(unittest.TestCase):