tools/cage_export.py and cage_score.py: a mesh read as a free cage, and two cages scored through shell (counts, limit distance, silhouette IoU, crease chamfer); core.poles; live proof kitbash_cage with its bounds by the margin rule

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-03 02:46:57 +01:00
commit 739cdb1e6b
7 changed files with 664 additions and 4 deletions

View file

@ -1624,7 +1624,7 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
built = core.sheet(document)
subdivided = core.subdivided_faces(built, self.levels)
if subdivided > SHELL_FACES_LIMIT:
raise Refused(f"sheet: {len(built.counts)} cage faces at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. "
raise Refused(f"sheet: {len(built.counts)} cage {'faces' if built.triangles else 'quads'} at {self.levels} levels subdivide to {subdivided} faces, over {SHELL_FACES_LIMIT}. "
"Use fewer levels or a sparser sheet; nothing changed.")
rebuilt = obj is not None
if rebuilt:

View file

@ -1235,7 +1235,13 @@ def subdivided_faces(built: Sheet, levels: int) -> int:
return (len(built.counts) - built.triangles) * 4 ** levels + built.triangles * 3 * 4 ** (levels - 1)
def _cage(document: Any) -> Sheet:
def poles(document: Any) -> list[int]:
"""The poles a free cage's faces make, by authored index, ascending: what its sheet.poles must state. For a
reader of a cage someone else modelled (tools/cage_export.py); every other refusal of the free form stands."""
return [int(v) for v in _cage(document, gate=False).poles if v < len(document["verts"])]
def _cage(document: Any, gate: bool = True) -> Sheet:
"""The cage of a free description {verts, faces, creases, corners, poles, mirror, rim, flip}.
verts: 4 to 256 [x, y, z]. faces: 3 or 4 vertex indices each, wound so the normal (counter-clockwise seen from
@ -1320,7 +1326,7 @@ def _cage(document: Any) -> Sheet:
flat = np.array([v for face in built for v in face], dtype=np.int32)
cage_edges, boundary, valences, poles = _cage_facts(len(V), flat, counts)
declared = document.get("poles", [])
declared = document.get("poles", []) if gate else [int(v) for v in poles if v < A]
if not isinstance(declared, list):
raise KitError("sheet.poles must be an array of vertex indices")
for k, v in enumerate(declared):

View file

@ -0,0 +1,263 @@
"""Live proof, in a background Blender, of brokkr_kitbash.shell's free cage through run_intent: a cage of triangles
and quads with declared poles becomes a shell whose subdivided face count is the reported one at each level, takes a
wall, counts folds and is cut; a mirrored cage closes over its seam; a loft shell is rebuilt in place as a free cage
under its cutters; the pole gate refuses without writing; and tools/cage_export.py and tools/cage_score.py read a
cage back and score it. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_cage.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed.
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped reading and
the least claimed mutant's, both written beside it; the result file carries the readings. The checks run inside
one try: an uncaught error is a failed check that names its section, and the result file is always written.
"""
import importlib.util
import json
import math
import os
import sys
import tempfile
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not Path(OUT).is_absolute():
raise SystemExit(f"{OUT!r} is not an absolute path")
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
from brokkr_bridge import blender_target as bt # noqa: E402
import addon_utils # noqa: E402
import cage_export # noqa: E402
import cage_score # noqa: E402
core = cage_export.load_core()
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
addon_utils.enable(module, default_set=True)
target = bt.BrokkrBlenderTarget(bpy)
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-cage-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
COUNT, SECTION = [0], ["setup"]
# Degrees: the largest dihedral angle across an edge of the tent's subdivided surface off its boundary; it is on the
# creased ridge. Shipped 71; least claimed mutant 16 (K1, the free form's creases not written to crease_edge: the
# ridge subdivides smooth), read here by clearing the attribute; the geometric mean, separation 2.1 each side.
CRISP = 34.0
# Per cent of the reference's extent: cage_score's median surface distance between the tent and the tent with its apex
# moved 5% of the extent. Shipped (a cage against itself) 0, read as 5e-6 (1e-7 m, what a float32 mesh is good to, of
# a 2 m extent); least claimed mutant 0.68 (the moved apex); the geometric mean, separation 370 each side. The moved
# apex's silhouette reads IoU 0.95 along y, under 1: checked as a strict inequality, not bounded.
SAME = 1.8e-3
# A tent: four triangles round an apex of valence 4 with two ridges creased, and a quad hung under one edge: 7
# vertices, vertices 1 and 2 boundary poles of valence 4.
TENT = {"verts": [[0.0, 0.0, 0.5], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [1.0, 0.0, -1.0], [0.0, 1.0, -1.0]],
"faces": [[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1], [2, 1, 5, 6]], "creases": [[0, 1, 1.0], [0, 3, 1.0]], "poles": [1, 2], "rim": 0.0}
# Half a lozenge hull, mirrored: seam vertices 0 to 3 (one 4 mm off the plane), a nose and tail triangle each side.
HULL = {"verts": [[0.0, -1.0, 0.0], [0.004, 0.0, 0.3], [0.0, 1.0, 0.0], [0.0, 0.0, -0.3], [0.6, 0.0, 0.0]],
"faces": [[0, 4, 1], [1, 4, 2], [2, 4, 3], [3, 4, 0]], "creases": [[0, 4, 1.0], [4, 2, 1.0]], "mirror": True}
LOFT = {"rings": [[[0.3 * j - 0.45, 0.02 * j * j, 0.3 * i] for j in range(4)] for i in range(3)], "flip": True}
CUTS = [{"name": "TentLine", "part": "slab", "params": "gap=0.02; length=0.4; depth=0.03", "origin": [0.3, -0.35, 3.0], "direction": [0, 0, -1]}]
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else json.loads(json.dumps(detail, default=str))})
def section(name):
SECTION[0] = name
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "nibu/hands", "action": action, **fields})
result = None
if receipt.get("hostResult"):
try:
result = json.loads(receipt["hostResult"])
except ValueError:
result = None
print("SEND", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def evaluated(obj, only=None):
"""An object as Blender evaluates it, as a bmesh; with `only`, with just the modifiers of those names shown."""
hidden = [m for m in obj.modifiers if only is not None and m.name not in only and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
bm = bmesh.new()
bm.from_mesh(owner.to_mesh())
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
bm.normal_update()
return bm
def sharpest(obj):
bm = evaluated(obj, only=("Kit Subsurf",))
worst = max(math.degrees(e.link_faces[0].normal.angle(e.link_faces[1].normal, 0.0)) for e in bm.edges if len(e.link_faces) == 2)
bm.free()
return worst
def state():
return {o.name: (sorted(k for k in o.keys() if k.startswith("kit_")), len(o.data.vertices) if o.type == "MESH" else None, [m.name for m in o.modifiers]) for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes)
try:
# --- live-free-cage-shell: counts at each level ----------------------------------------------------------------
section("free-cage-triangle-counts")
for levels in (1, 2, 3):
receipt, report = send("brokkr_kitbash.shell", object_name="Tent", sheet=json.dumps(TENT), thickness=0.04, levels=levels, count_folds=True)
tent = bpy.data.objects.get("Tent")
expected = 1 * 4 ** levels + 4 * 3 * 4 ** (levels - 1)
bm = evaluated(tent, only=("Kit Subsurf",))
faces, sides = len(bm.faces), {len(f.verts) for f in bm.faces}
bm.free()
wall = evaluated(tent, only=("Kit Subsurf", "Kit Solidify"))
closed, walled = all(e.is_manifold for e in wall.edges), len(wall.faces)
wall.free()
check(f"a cage of 4 triangles and a quad at {levels} levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
receipt["status"] == "accepted" and report["subdividedFaces"] == expected == faces and sides == {4}, [receipt["message"], expected, faces, sides])
check(f"at {levels} levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
closed and walled > 2 * expected and report["folded"] == 0, [closed, walled, report and report["folded"]])
built = core.sheet(TENT)
check("the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null",
report and {k: report[k] for k in ("rings", "points", "cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")}
== {"rings": None, "points": None, "cageVerts": 7, "cageFaces": 5, "triangles": 4, "creases": 2, "corners": 0, "poles": {"4": 2}, "closed": False}, report)
check("the cage mesh is core.sheet's, face for face, and kit_shell is the request",
[tuple(p.vertices) for p in tent.data.polygons] == [tuple(f) for f in TENT["faces"]] and np.abs(np.array([v.co[:] for v in tent.data.vertices]) - built.V).max() < 1e-6
and json.loads(tent["kit_shell"])["sheet"] == TENT, tent["kit_shell"])
# --- the creases reach the surface -----------------------------------------------------------------------------------
section("free-cage-crisp")
crisp = sharpest(tent)
attribute = tent.data.attributes["crease_edge"]
kept = [d.value for d in attribute.data]
attribute.data.foreach_set("value", [0.0] * len(kept)) # K1: what the surface is when the creases are not written
tent.data.update()
soft = sharpest(tent)
attribute.data.foreach_set("value", kept)
tent.data.update()
R["readings"].update({"crispDegrees": crisp, "crispDegreesK1": soft})
check(f"the creased ridge stays an edge under subdivision: over {CRISP} degrees, and under it with crease_edge cleared", crisp > CRISP * 1.2 and soft < CRISP / 1.2, [crisp, soft])
# --- cut -------------------------------------------------------------------------------------------------------------
section("live-free-cage-shell")
receipt, cut = send("brokkr_kitbash.cut_many", object_name="Tent", cuts=json.dumps(CUTS))
plate = evaluated(tent)
uncut = 2 * (4 ** 3 + 12 * 4 ** 2)
check("cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge",
receipt["status"] == "accepted" and [m.name for m in tent.modifiers] == ["Kit Subsurf", "Kit Solidify", "Kit Difference"] and len(plate.faces) > uncut + 20
and sum(1 for e in plate.edges if not e.is_manifold) == 0, [receipt["message"], len(plate.faces), sum(1 for e in plate.edges if not e.is_manifold)])
plate.free()
# --- mirror ----------------------------------------------------------------------------------------------------------
section("free-cage-mirror")
receipt, report = send("brokkr_kitbash.shell", object_name="Hull", sheet=json.dumps(HULL), thickness=0.01)
hull = bpy.data.objects.get("Hull")
bm = evaluated(hull, only=("Kit Subsurf",))
check("a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
receipt["status"] == "accepted" and (report["cageVerts"], report["cageFaces"], report["triangles"], report["closed"], report["creases"], report["subdividedFaces"]) == (6, 8, 8, True, 4, 8 * 3 * 16)
and abs(hull.data.vertices[1].co.x) < 1e-9 and all(e.is_manifold for e in bm.edges) and len(bm.faces) == 384 and report["poles"] == {}, report)
bm.free()
# --- rebuild a loft as a free cage -------------------------------------------------------------------------------------
section("free-cage-rebuild")
receipt, _ = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(LOFT), thickness=0.03)
plate_obj = bpy.data.objects["Plate"]
plate_obj.data.materials.append(bpy.data.materials.new("Khaki"))
receipt, _ = send("brokkr_kitbash.cut_many", object_name="Plate", cuts=json.dumps([{"name": "PlateLine", "part": "slab", "params": "gap=0.02; length=0.3; depth=0.02", "origin": [0.0, 3.0, 0.3], "direction": [0, -1, 0]}]))
before = (plate_obj.as_pointer(), plate_obj.data.as_pointer(), sorted(c.name for c in plate_obj.children), sorted(o.name for o in plate_obj.modifiers["Kit Difference"].collection.objects), [s.material.name for s in plate_obj.material_slots])
loft = core.sheet(LOFT)
quads = loft.faces.reshape(-1, 4).tolist()
FREE = {"verts": [[round(c, 6) for c in v] for v in loft.V.tolist()], "faces": quads[:5] + [quads[5][:3], [quads[5][0], quads[5][2], quads[5][3]]], "poles": [7, 10], "creases": [[5, 6, 1.0]]} # the last quad split along its diagonal: two boundary vertices of valence 4
receipt, report = send("brokkr_kitbash.shell", object_name="Plate", sheet=json.dumps(FREE), thickness=0.03)
again = bpy.data.objects.get("Plate")
after = (again.as_pointer(), again.data.as_pointer(), sorted(c.name for c in again.children), sorted(o.name for o in again.modifiers["Kit Difference"].collection.objects), [s.material.name for s in again.material_slots])
bm = evaluated(again)
check("a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
receipt["status"] == "accepted" and before == after and before[2:] == (["PlateLine"], ["PlateLine"], ["Khaki"]) and report["rebuilt"] is True and (report["triangles"], report["rings"], report["cageFaces"]) == (2, None, 7)
and report["poles"] == {"4": 2} and report["children"] == ["PlateLine"] and sum(1 for e in bm.edges if not e.is_manifold) == 0 and len(bm.faces) > 2 * report["subdividedFaces"], [receipt["message"], report, before, after])
bm.free()
# --- the gate refuses before it writes -------------------------------------------------------------------------------
section("free-cage-refusals")
for label, name, sheet, expected in (
("an undeclared pole, on a shell", "Plate", {**FREE, "poles": [7]}, "sheet.poles lacks vertex 10 (valence 4, on the boundary)"),
("a declared vertex that is no pole, on a new name", "New", {**TENT, "poles": [1, 2, 0]}, "sheet.poles[2] names vertex 0 (valence 4), which is no pole"),
("rings with verts", "New", {**TENT, "rings": LOFT["rings"]}, "sheet states both rings and verts"),
("a face of five sides", "New", {**TENT, "faces": TENT["faces"][:4] + [[2, 1, 5, 6, 3]]}, "sheet.faces[4] must be 3 or 4 vertex indices, not 5"),
("two faces wound against each other", "Plate", {**FREE, "faces": FREE["faces"][:6] + [FREE["faces"][6][::-1]]}, "the two are wound against each other")):
held = state()
receipt, _ = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet))
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and state() == held, [receipt["status"], receipt["message"]])
check("no refusal made an object", "New" not in bpy.data.objects, None)
# --- export-score-roundtrip -----------------------------------------------------------------------------------------
section("export-score-roundtrip")
saved = str(WORK / "scratch.blend")
probe = bpy.data.objects.new("Probe Cage", bpy.data.meshes.new("Probe Cage")) # a cage as a person leaves one: a mesh, a Mirror, creases on edges; made here, no one's file
bpy.context.scene.collection.objects.link(probe)
probe.data.from_pydata(HULL["verts"], [], HULL["faces"])
probe.data.update(calc_edges=True)
weights = probe.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for e in probe.data.edges:
weights.data[e.index].value = 1.0 if tuple(sorted(e.vertices)) in ((0, 4), (2, 4)) else 0.0
probe.modifiers.new("Mirror", "MIRROR")
probe.modifiers.new("Subdivision", "SUBSURF")
document = cage_export.export(probe, core)
exported = document["sheet"]
check("cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
exported["verts"][1] == [0.0, 0.0, 0.3] and exported["faces"] == HULL["faces"] and exported["creases"] == [[0, 4, 1.0], [2, 4, 1.0]] and exported["mirror"] is True
and exported["rim"] == 0.0 and exported["poles"] == [] and document["modifiers"] == [["MIRROR", "Mirror"], ["SUBSURF", "Subdivision"]]
and np.array_equal(core.sheet(exported).faces, core.sheet(HULL).faces), document)
bpy.data.objects.remove(probe)
tent_document = {**TENT, "rim": 1.0}
held = state()
same = cage_score.score(tent_document, tent_document, send)
check("cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again",
same["agent"] == same["reference"] and same["agent"]["cageVerts"] == 7 and same["distance"]["maxPct"] < SAME / 1.2 and set(same["silhouetteIoU"].values()) == {1.0}
and same["creaseChamferPct"] == 0.0 and state() == held, same)
moved = {**tent_document, "verts": [[0.0, 0.0, 0.5 + 0.05 * 2.0]] + TENT["verts"][1:]} # the apex lifted 5% of the 2 m extent
apart = cage_score.score(moved, tent_document, send)
R["readings"].update({"scoreSameMedianPct": same["distance"]["medianPct"], "scoreMovedMedianPct": apart["distance"]["medianPct"], "scoreMovedIoUy": apart["silhouetteIoU"]["y"],
"scoreMovedChamferPct": apart["creaseChamferPct"]})
check("cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal",
apart["distance"]["medianPct"] > SAME * 1.2 and apart["distance"]["maxPct"] > 1.0 and min(apart["silhouetteIoU"].values()) < 1.0 and apart["creaseChamferPct"] > 0.0
and apart["agent"] == apart["reference"] and abs(apart["extent"] - same["extent"]) < 1e-9, apart)
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
finally:
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())}
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
print("READINGS", R["readings"], flush=True)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,120 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "a cage of 4 triangles and a quad at 1 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 1 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "a cage of 4 triangles and a quad at 2 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 2 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "a cage of 4 triangles and a quad at 3 levels: subdividedFaces is 4^L + 4 * 3 * 4^(L-1) and the evaluated surface has that many faces, all quads",
"ok": true,
"detail": null
},
{
"name": "at 3 levels the wall is closed, twice the surface and a rim, and count_folds counts none folded",
"ok": true,
"detail": null
},
{
"name": "the report carries the cage's facts: 7 vertices, 5 faces of which 4 triangles, 2 creases, two poles of valence 4, open; rings and points null",
"ok": true,
"detail": null
},
{
"name": "the cage mesh is core.sheet's, face for face, and kit_shell is the request",
"ok": true,
"detail": null
},
{
"name": "the creased ridge stays an edge under subdivision: over 34.0 degrees, and under it with crease_edge cleared",
"ok": true,
"detail": null
},
{
"name": "cut_many cuts a free-cage shell: the Boolean stands after the wall, the plate has more faces than the wall and no non-manifold edge",
"ok": true,
"detail": null
},
{
"name": "a mirrored cage closes over its seam: 6 vertices from 5, 8 triangles, the vertex 4 mm off the plane snapped onto it, no boundary edge on the cage or its surface, and its poles reported",
"ok": true,
"detail": null
},
{
"name": "a loft shell rebuilt in place as a free cage keeps its object, mesh datablock, cutter, Boolean and material slot; the report says rebuilt, 2 triangles and the cage's poles; the plate is still cut and closed",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: an undeclared pole, on a shell",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a declared vertex that is no pole, on a new name",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: rings with verts",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a face of five sides",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: two faces wound against each other",
"ok": true,
"detail": null
},
{
"name": "no refusal made an object",
"ok": true,
"detail": null
},
{
"name": "cage_export reads a mirrored, creased mesh as the free cage it is: the seam snapped, the creases by vertex pair, mirror set, rim 0, the poles computed, and core.sheet takes it",
"ok": true,
"detail": null
},
{
"name": "cage_score of a cage against itself: equal counts, distance 0, every silhouette IoU 1, crease chamfer 0, and its two shells removed again",
"ok": true,
"detail": null
},
{
"name": "cage_score of the cage with one vertex moved 5% of the extent: distance above the bound, a silhouette under 1, a crease chamfer above 0, the counts still equal",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"crispDegrees": 71.0,
"crispDegreesK1": 16.0,
"scoreMovedChamferPct": 0.46,
"scoreMovedIoUy": 0.95,
"scoreMovedMedianPct": 0.68,
"scoreSameMedianPct": 0.0
},
"ok": true
}

View file

@ -214,7 +214,8 @@ try:
and sorted(stored) == ["bevel", "levels", "offset", "sheet", "thickness"] and stored["sheet"] == PAULDRON
and (stored["levels"], stored["offset"]) == (3, -1.0) and abs(stored["thickness"] - WALL) < 1e-7, [receipt["message"], stored])
check("shell reports cage facts: rings, points, quads, creased edges, the subdivided count, an upward facing, no children",
report and sorted(report) == ["cageFaces", "children", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "rebuilt", "rings", "subdividedFaces", "thickness"]
report and sorted(report) == ["cageFaces", "cageVerts", "children", "closed", "corners", "creases", "facing", "folded", "levels", "object", "offset", "points", "poles", "rebuilt", "rings", "subdividedFaces", "thickness", "triangles"]
and (report["cageVerts"], report["triangles"], report["poles"], report["closed"]) == (36, 0, {}, False)
and (report["object"], report["rebuilt"], report["rings"], report["points"], report["cageFaces"], report["creases"], report["corners"], report["subdividedFaces"], report["levels"],
report["thickness"], report["offset"], report["children"]) == ("Pauldron", False, 6, 6, 25, 25, 0, 1600, 3, 0.06, -1.0, [])
and report["facing"][2] > 0.5 and abs(np.linalg.norm(report["facing"]) - 1.0) < 1e-5, report)

View file

@ -0,0 +1,84 @@
"""Write one object of a .blend as a free cage document, the form brokkr_kitbash.shell's sheet takes.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_export.py -- <copy.blend> <object> <out.json>
For reading a cage a person modelled by hand: its vertex budget, faces, creases and poles, and as the reference
of tools/cage_score.py. <copy.blend> is a COPY of the file, made by whoever runs this: the script opens it, reads
one mesh, writes <out.json> (an absolute path) and nothing else, and never saves a .blend. It refuses to start
unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The document: {"object", "modifiers" (type and name, as stacked), "matrixWorld", "sheet"}. sheet is the cage in
the object's own frame, before any modifier: verts, faces, creases from the crease_edge attribute, corners from
crease_vert, mirror true when the object carries a Mirror across x (any other Mirror is refused), the seam
snapped as core.sheet snaps it (a vertex within SEAM_EPS of x = 0 goes to 0), rim 0 (a boundary edge carries the
crease it was given and no more), and poles as the faces make them (core.poles). The sheet is what core.sheet
accepts: a cage it would refuse (a face of five sides, a fin on the mirror plane) is refused here with its reason.
"""
import importlib.util
import json
import os
import sys
from pathlib import Path
import bpy
SURFACE = Path(__file__).resolve().parents[1]
def load_core():
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_tool", SURFACE / "brokkr_kitbash" / "core.py")
core = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = core
spec.loader.exec_module(core)
return core
def export(obj, core) -> dict:
"""The document of a mesh object's cage. Raises core.KitError when the cage is none core.sheet takes."""
if obj.type != "MESH":
raise core.KitError(f"{obj.name!r} is a {obj.type}, not a mesh")
mirrors = [m for m in obj.modifiers if m.type == "MIRROR"]
if len(mirrors) > 1 or mirrors and (tuple(mirrors[0].use_axis) != (True, False, False) or mirrors[0].mirror_object is not None):
raise core.KitError(f"{obj.name!r} is mirrored otherwise than once across its own x: a free cage mirrors across x = 0 only")
mesh = obj.data
verts = [[round(float(c), 6) for c in v.co] for v in mesh.vertices]
if mirrors:
for point in verts:
if abs(point[0]) <= core.SEAM_EPS:
point[0] = 0.0
creases, corners = mesh.attributes.get("crease_edge"), mesh.attributes.get("crease_vert")
sheet = {"verts": verts, "faces": [list(p.vertices) for p in mesh.polygons],
"creases": sorted([*sorted(e.vertices), round(float(creases.data[e.index].value), 4)] for e in mesh.edges if creases.data[e.index].value > 0) if creases else [],
"corners": [[v.index, round(float(corners.data[v.index].value), 4)] for v in mesh.vertices if corners.data[v.index].value > 0] if corners else [],
"mirror": bool(mirrors), "rim": 0.0}
sheet["poles"] = core.poles(sheet)
core.sheet(sheet)
return {"object": obj.name, "modifiers": [[m.type, m.name] for m in obj.modifiers], "matrixWorld": core.rows(obj.matrix_world), "sheet": sheet}
def main() -> int:
sys.path.insert(0, str(Path(__file__).resolve().parent))
import private_dirs
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if refused:
raise SystemExit(f"cage_export: {refused}")
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
raise SystemExit("usage: blender --background --factory-startup --python cage_export.py -- <copy.blend> <object> <absolute out.json>")
blend, name, out = arguments
core = load_core()
bpy.ops.wm.open_mainfile(filepath=str(Path(blend).resolve()), load_ui=False, use_scripts=False)
obj = bpy.data.objects.get(name)
if obj is None:
raise SystemExit(f"cage_export: {blend} has no object {name!r}; its meshes: {', '.join(sorted(o.name for o in bpy.data.objects if o.type == 'MESH'))}")
try:
document = export(obj, core)
except core.KitError as error:
raise SystemExit(f"cage_export: {name!r} is no free cage: {error}") from None
Path(out).write_text(json.dumps(document, indent=1), encoding="utf-8")
print("cage_export:", json.dumps({key: core.cage_report(core.sheet(document["sheet"]))[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed")}), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())

View file

@ -0,0 +1,186 @@
"""Read how close one free cage comes to another: an agent's cage against a reference, both in one frame.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tools/cage_score.py -- <agent.json> <reference.json> <out.json>
Each input is a sheet (either form of brokkr_kitbash.shell's) or a cage_export.py document holding one. Both are
built by brokkr_kitbash.shell through the add-on's own agent turn, at three levels, and read with their Kit
Subsurf alone: the tool measures what the tool builds. <out.json> is an absolute path and the one file written;
no .blend is saved. It refuses to start unless BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and
BLENDER_USER_SCRIPTS are private (tools/private_dirs.py).
The result is a reading with no pass bar:
agent, reference each cage's counts as shell reports them: cageVerts, cageFaces, triangles, creases, corners, poles, closed
extent the reference surface's largest extent, metres: the unit of every percentage
distance between the two level-3 surfaces, each one's vertices to the nearest point of the other, pooled:
medianPct, p95Pct, maxPct
silhouetteIoU orthographic silhouettes seen along x, y and z, 512 px across the two surfaces' common box:
intersection over union
creaseChamferPct the creased cage edges (rim included, where its weight is over 0) as they lie on each level-3
surface, sampled every 1% of extent: the mean distance from each curve's samples to the
other's, averaged both ways; null when either cage has no crease
"""
import importlib.util
import json
import os
import sys
import types
from pathlib import Path
import bpy
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree
SURFACE = Path(__file__).resolve().parents[1]
LEVELS, PIXELS, SPACING = 3, 512, 0.01
COUNTS = ("cageVerts", "cageFaces", "triangles", "creases", "corners", "poles", "closed")
def surface(obj):
"""(V, triangles, creased polylines) of a shell read with its Kit Subsurf alone. A creased cage edge is found on
the subdivided mesh as Blender lays it out: the cage's vertices keep their indices, then each cage edge's 2^L - 1
inner vertices follow in edge order; the chain is checked edge by edge against the mesh, not assumed."""
hidden = [m for m in obj.modifiers if m.name != "Kit Subsurf" and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
bpy.context.view_layer.update()
owner = obj.evaluated_get(bpy.context.evaluated_depsgraph_get())
mesh = owner.to_mesh()
V = np.array([v.co[:] for v in mesh.vertices], dtype=np.float64)
triangles = np.array([[p.vertices[0], p.vertices[k], p.vertices[k + 1]] for p in mesh.polygons for k in range(1, len(p.vertices) - 1)], dtype=np.int64)
edges = {tuple(sorted(e.vertices)) for e in mesh.edges}
owner.to_mesh_clear()
finally:
for m in hidden:
m.show_viewport = True
bpy.context.view_layer.update()
cage, inner = obj.data, 2 ** obj.modifiers["Kit Subsurf"].levels - 1
weights = cage.attributes["crease_edge"].data
curves = []
for e in cage.edges:
if weights[e.index].value <= 0:
continue
between = [len(cage.vertices) + e.index * inner + k for k in range(inner)]
for chain in ([e.vertices[0], *between, e.vertices[1]], [e.vertices[0], *between[::-1], e.vertices[1]]):
if all(tuple(sorted(pair)) in edges for pair in zip(chain, chain[1:])):
curves.append(V[chain])
break
else:
raise SystemExit(f"cage_score: cage edge {tuple(e.vertices)} of {obj.name!r} is not where the subdivided mesh was expected to carry it; this Blender lays a Subdivision out otherwise")
return V, triangles, curves
def nearest(points, V, triangles):
tree = BVHTree.FromPolygons([Vector(v) for v in V], [tuple(int(i) for i in t) for t in triangles])
return np.array([tree.find_nearest(Vector(p))[3] for p in points])
def silhouette(V, triangles, axis, low, scale):
"""A PIXELS-square mask of the triangles seen along `axis`, in the frame (low, scale) both surfaces share."""
keep = [k for k in range(3) if k != axis]
P = (V[:, keep] - low[keep]) * scale
mask = np.zeros((PIXELS, PIXELS), dtype=bool)
for a, b, c in P[triangles]:
x0, y0 = np.floor(np.minimum(np.minimum(a, b), c)).astype(int).clip(0, PIXELS - 1)
x1, y1 = np.ceil(np.maximum(np.maximum(a, b), c)).astype(int).clip(0, PIXELS - 1)
area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
if abs(area) < 1e-12:
continue
X, Y = np.meshgrid(np.arange(x0, x1 + 1) + 0.5, np.arange(y0, y1 + 1) + 0.5)
u = ((b[0] - X) * (c[1] - Y) - (b[1] - Y) * (c[0] - X)) / area
v = ((c[0] - X) * (a[1] - Y) - (c[1] - Y) * (a[0] - X)) / area
mask[y0:y1 + 1, x0:x1 + 1] |= (u >= 0) & (v >= 0) & (u + v <= 1)
return mask
def sampled(curves, step):
points = []
for curve in curves:
lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1)
along = np.concatenate([[0.0], np.cumsum(lengths)])
at = np.linspace(0.0, along[-1], max(2, int(np.ceil(along[-1] / step)) + 1))
points.append(np.stack([np.interp(at, along, curve[:, k]) for k in range(3)], axis=1))
return np.concatenate(points) if points else np.zeros((0, 3))
def score(agent: dict, reference: dict, send) -> dict:
"""The reading of two sheets. send(action, **fields) -> (receipt, report) runs an intent; the two shells it
builds (Cage Score Agent, Cage Score Reference) are removed again."""
built, reports = {}, {}
try:
for role, sheet in (("agent", agent), ("reference", reference)):
name = f"Cage Score {role.title()}"
receipt, report = send("brokkr_kitbash.shell", object_name=name, sheet=json.dumps(sheet), levels=LEVELS, thickness=0.001)
if receipt["status"] != "accepted":
raise SystemExit(f"cage_score: the {role} cage was refused: {receipt['message']}")
reports[role] = {key: report[key] for key in COUNTS}
built[role] = surface(bpy.data.objects[name])
finally:
for role in ("agent", "reference"):
obj = bpy.data.objects.get(f"Cage Score {role.title()}")
if obj is not None:
mesh = obj.data
bpy.data.objects.remove(obj)
bpy.data.meshes.remove(mesh)
(VA, TA, CA), (VB, TB, CB) = built["agent"], built["reference"]
extent = float(np.ptp(VB, axis=0).max())
d = np.concatenate([nearest(VA, VB, TB), nearest(VB, VA, TA)]) / extent * 100.0
both = np.concatenate([VA, VB])
low = both.min(axis=0)
scale = (PIXELS - 1) / float(np.ptp(both, axis=0).max())
overlap = {}
for axis, label in enumerate("xyz"):
a, b = silhouette(VA, TA, axis, low, scale), silhouette(VB, TB, axis, low, scale)
overlap[label] = round(float((a & b).sum() / max(1, (a | b).sum())), 4)
chamfer = None
if CA and CB:
SA, SB = sampled(CA, SPACING * extent), sampled(CB, SPACING * extent)
away = lambda P, Q: float(np.mean([np.linalg.norm(Q - p, axis=1).min() for p in P])) # noqa: E731
chamfer = round(0.5 * (away(SA, SB) + away(SB, SA)) / extent * 100.0, 4)
return {"levels": LEVELS, "agent": reports["agent"], "reference": reports["reference"], "extent": round(extent, 6),
"distance": {"medianPct": round(float(np.median(d)), 4), "p95Pct": round(float(np.percentile(d, 95)), 4), "maxPct": round(float(d.max()), 4)},
"silhouetteIoU": overlap, "creaseChamferPct": chamfer}
def main() -> int:
sys.path.insert(0, str(Path(__file__).resolve().parent))
import private_dirs
refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if refused:
raise SystemExit(f"cage_score: {refused}")
arguments = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
if len(arguments) != 3 or not Path(arguments[2]).is_absolute():
raise SystemExit("usage: blender --background --factory-startup --python cage_score.py -- <agent.json> <reference.json> <absolute out.json>")
sheets = []
for path in arguments[:2]:
document = json.loads(Path(path).read_text(encoding="utf-8"))
sheets.append(document["sheet"] if "sheet" in document else document)
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
blender_target = importlib.import_module("brokkr_bridge.blender_target")
import addon_utils
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
addon_utils.enable(module, default_set=True)
target = blender_target.BrokkrBlenderTarget(bpy)
target.configure_action_dirs("", str(Path(arguments[2]).parent))
target.reload_host_actions()
count = [0]
def send(action, **fields):
count[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"cage-score-{count[0]}", "requestedBy": "tools/cage_score", "action": action, **fields})
return receipt, json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
result = score(sheets[0], sheets[1], send)
Path(arguments[2]).write_text(json.dumps(result, indent=1), encoding="utf-8")
print("cage_score:", json.dumps(result), flush=True)
return 0
if __name__ == "__main__":
sys.exit(main())