tests/live/reference_lift.py: crease_run against Blender's subdivision, lift_pair and flow_score through run_intent

21 checks on Blender 5.3. The folded sheet seen from behind claims mutant N5 (back-facing creases counted).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 20:34:48 +01:00
commit 777401c97c
2 changed files with 527 additions and 0 deletions

View file

@ -0,0 +1,209 @@
"""Live proof, in a background Blender, of brokkr_reference.lift_pair and flow_score through run_intent, and of
core.crease_run against Blender's own subdivision.
crease_run a strip of quads with its middle column creased hard, subdivided once by Blender: the built crease
is where core.crease_run says (the numbers printed as BUILT are test_reference.py's fixture)
lift_pair a crease of a turned frame and its mirror image, drawn by Blender's own projection through a known
camera, lifted back; again with the lines in an image's pixels through `box`; the curve it draws
flow_score a box and, beside it, a folded sheet seen from behind: the box's front edge scores 1, its hidden back
edge 0, and the sheet's fold 0, since neither of its faces is toward the camera (mutant N5, which
counts such creases, reads 1 and four creases)
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.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: it writes <out>.result.json and exits 1 when a check failed. Not part
of the unittest run: it needs Blender.
"""
import json
import os
import sys
import tempfile
import time
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from bpy_extras.object_utils import world_to_camera_view
from mathutils import Euler, Matrix, Vector
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 os.path.isabs(OUT):
raise SystemExit(f"<out> must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory")
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
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_reference"):
addon_utils.enable(module, default_set=True)
from brokkr_reference import core # noqa: E402
target = bt.BrokkrBlenderTarget(bpy)
target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-lift-live-"))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
"hostRows": [row["name"] for row in target.host_actions()[0]]}
COUNT = [0]
T0 = time.time()
WIDTH, HEIGHT = 800, 600
COLUMN = [[0.5, 0.0, 0.0], [0.6, 0.2, 1.0], [0.4, 0.1, 2.0], [0.7, -0.2, 3.0], [0.5, 0.0, 4.0]]
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def mesh_object(name, verts, faces):
mesh = bpy.data.meshes.new(name)
mesh.from_pydata(verts, [], faces)
obj = bpy.data.objects.new(name, mesh)
bpy.context.scene.collection.objects.link(obj)
return obj
def traced(camera, points, scale=1.0, corner=(0.0, 0.0)):
"""'u,v u,v ...' where Blender's own projection draws world points, in an image whose pixels are the frame's
times `scale` from `corner`."""
out = []
for p in points:
x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(p))
out.append(f"{corner[0] + scale * x * WIDTH:.3f},{corner[1] + scale * (1.0 - y) * HEIGHT:.3f}")
return " ".join(out)
try:
check("host file admitted", not R["hostErrors"] and {"brokkr_reference.lift_pair", "brokkr_reference.flow_score"} <= set(R["hostRows"]), R["hostRows"])
scene = bpy.context.scene
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
# --- crease_run is Blender's level-1 subdivision of a hard crease -------------------------------------------------
col = np.array(COLUMN)
verts = [tuple(p + d) for p in col for d in ((-0.5, 0.3, 0.0), (0.0, 0.0, 0.0), (0.5, -0.3, 0.1))]
strip = mesh_object("Strip", verts, [(3 * i + j, 3 * i + j + 1, 3 * i + j + 4, 3 * i + j + 3) for i in range(4) for j in range(2)])
sharp = strip.data.attributes.new("crease_edge", "FLOAT", "EDGE")
for edge in strip.data.edges:
sharp.data[edge.index].value = 1.0 if all(v % 3 == 1 for v in edge.vertices) else 0.0
modifier = strip.modifiers.new("Subdivision", "SUBSURF")
modifier.levels, modifier.subdivision_type, modifier.use_creases = 1, "CATMULL_CLARK", True
bpy.context.view_layer.update()
evaluated = strip.evaluated_get(bpy.context.evaluated_depsgraph_get())
built_all = np.array([v.co for v in evaluated.data.vertices])
run = core.crease_run(COLUMN)
nearest = [built_all[np.linalg.norm(built_all - p, axis=1).argmin()] for p in run]
R["BUILT"] = [[round(float(v), 6) for v in p] for p in nearest]
print("BUILT", json.dumps(R["BUILT"]), flush=True)
worst = float(np.abs(np.array(nearest) - run).max())
# Shipped 4.8e-7 m (Blender's single floats); without the limit step (N3) 0.0208: the bound is their geometric mean.
check("crease_run stands where Blender builds the creased column, within 1e-4 m", len(built_all) == 45 and worst < 1e-4, worst)
strip.hide_render = True
strip.hide_viewport = True
# --- lift_pair: a crease of a turned frame and its mirror image, drawn by Blender, lifted back ---------------------
truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth"))
scene.collection.objects.link(truth)
truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit = 50.0, 36.0, "HORIZONTAL"
truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4()
hull = bpy.data.objects.new("Hull", None)
scene.collection.objects.link(hull)
hull.matrix_world = Matrix.Translation((0.3, -0.2, 0.1)) @ Euler((0.0, 0.0, 0.2618), "XYZ").to_matrix().to_4x4()
bpy.context.view_layer.update()
t = np.linspace(0, 1, 40)
crease = np.stack([0.4 + 0.2 * np.sin(2.5 * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1)
F = np.array(hull.matrix_world)
world = lambda side: (crease * [side, 1, 1]) @ F[:3, :3].T + F[:3, 3] # noqa: E731
before = sorted(o.name for o in bpy.data.objects)
receipt, lifted = send("brokkr_reference.lift_pair", camera_name="Truth", frame_name="Hull", line_a=traced(truth, world(-1)), line_b=traced(truth, world(1)))
off = lifted and float(core._off(np.array(lifted["crease"]), crease).max())
check("lift_pair: accepted, 24 points on the crease within 1 mm, on the frame's -x side, none ambiguous or unmatched, no object made",
receipt["status"] == "accepted" and len(lifted["crease"]) == 24 and off < 1e-3 and lifted["side"] == -1 and lifted["ambiguous"] == 0 and lifted["unmatched"] == 0
and lifted["curve"] is None and sorted(o.name for o in bpy.data.objects) == before, [receipt["message"], off])
through = lifted and float(np.abs(core.crease_run(lifted["cage"])[0::2] - np.array(lifted["crease"])).max())
check("the cage column's built crease passes through the lifted crease, and draws within 1 px of both lines",
lifted and through < 1e-4 and max(lifted["miss"].values()) < 1.0, [through, lifted and lifted["miss"]])
R["lift"] = {"off": off, "through": through, "miss": lifted and lifted["miss"]}
box = "100,50,1700,1250" # the same view as an image twice the frame's size, its corner at 100, 50
receipt, boxed = send("brokkr_reference.lift_pair", camera_name="Truth", box=box, frame_name="Hull", line_a=traced(truth, world(1), 2.0, (100.0, 50.0)),
line_b=traced(truth, world(-1), 2.0, (100.0, 50.0)), samples=12, curve_name="Crease")
curve = bpy.data.objects.get("Crease")
drawn_at = curve and np.array([core.project(core.camera_of({"matrix_world": [list(r) for r in truth.matrix_world], "lens": 50.0, "shift_x": 0.0, "shift_y": 0.0,
"resolution": [WIDTH, HEIGHT]}), [curve.matrix_world @ Vector(p.co[:3])])[0] for p in curve.data.splines[0].points])
on_line = curve and float(core._off(drawn_at, core.polyline(traced(truth, world(1)), "a")).max())
check("lift_pair through a box, with curve_name: 12 points on the +x side, a poly curve parented to the frame that the camera draws on line A",
receipt["status"] == "accepted" and len(boxed["crease"]) == 12 and boxed["side"] == 1 and float(core._off(np.array(boxed["crease"]), crease).max()) < 1e-3
and curve is not None and curve.type == "CURVE" and curve.parent == hull and len(curve.data.splines[0].points) == 12 and on_line < 0.05, [receipt["message"], on_line])
receipt, _ = send("brokkr_reference.lift_pair", camera_name="Truth", box=box, frame_name="Hull", line_a=traced(truth, world(1), 2.0, (100.0, 50.0)),
line_b=traced(truth, world(-1), 2.0, (100.0, 50.0)), curve_name="Crease")
check("a second run updates the one curve: 24 points, one spline", receipt["status"] == "accepted" and [o.name for o in bpy.data.objects if o.type == "CURVE"] == ["Crease"]
and len(curve.data.splines) == 1 and len(curve.data.splines[0].points) == 24, receipt["message"])
for fields, said in (({"frame_name": "Nobody"}, "no object is named"), ({"camera_name": "Hull"}, "not a camera"), ({"line_a": "1,2"}, "no length"),
({"curve_name": "Truth"}, "not a curve"), ({"line_b": "5000,5000 5010,5000"}, "no mirror")):
receipt, _ = send("brokkr_reference.lift_pair", **{"camera_name": "Truth", "frame_name": "Hull", "line_a": traced(truth, world(1)), "line_b": traced(truth, world(-1)), **fields})
check(f"lift_pair refuses {next(iter(fields))}: failed, saying '{said}'", receipt["status"] == "failed" and said in receipt["message"], receipt["message"])
# --- flow_score: the edges the camera sees on a box and on a folded sheet seen from behind ------------------------
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=2.0, matrix=Matrix.Translation((0.0, 0.0, 1.0)))
mesh = bpy.data.meshes.new("Box")
bm.to_mesh(mesh)
bm.free()
scene.collection.objects.link(bpy.data.objects.new("Box", mesh))
# a valley fold running toward the camera in plan, its faces rising 45 degrees to either side: seen from above, both look down and away
fold, wing = [(2.176, -1.734, 0.5), (2.824, -1.266, 0.5)], np.array([0.1755, -0.2433, 0.3])
sheet = mesh_object("Sheet", [fold[0], fold[1], tuple(fold[1] - wing * [1, 1, -1]), tuple(fold[0] - wing * [1, 1, -1]), tuple(fold[1] + wing), tuple(fold[0] + wing)], [(0, 1, 2, 3), (1, 0, 5, 4)])
for polygon in sheet.data.polygons:
if polygon.normal.z > 0:
polygon.flip()
sheet.data.update()
bpy.context.view_layer.update()
eye = np.array(truth.matrix_world.translation)
check("fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so",
all((eye - np.array(p.center)) @ np.array(p.normal) < 0 for p in sheet.data.polygons) and abs(sheet.data.polygons[0].normal @ sheet.data.polygons[1].normal) < 0.5,
[list(p.normal) for p in sheet.data.polygons])
front, back = [(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)], [(1.0, 1.0, 0.0), (1.0, 1.0, 2.0)]
lines = f"front: {traced(truth, front)}; back: {traced(truth, back)}; fold: {traced(truth, fold)}; top: {traced(truth, [(-1.0, -1.0, 2.0), (1.0, -1.0, 2.0), (1.0, 1.0, 2.0)])}"
receipt, flow = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines)
R["flow"] = flow
check("flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease", receipt["status"] == "accepted"
and flow["edges"] == {"crease": 3, "contour": 6, "border": 6} and flow["objects"] == ["Box", "Sheet"] and flow["height"] == HEIGHT, [receipt["message"], flow and flow["edges"]])
check("the box's front edge and the top's two edges score on 1, run 1", flow and flow["lines"]["front"]["on"] == 1.0 and flow["lines"]["front"]["run"] == 1.0
and flow["lines"]["top"]["on"] > 0.95, flow and flow["lines"])
check("the box's hidden back edge scores on 0", flow and flow["lines"]["back"] == {"on": 0.0, "off": 5.0, "run": 0.0}, flow and flow["lines"]["back"])
check("the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)", flow and flow["lines"]["fold"]["on"] == 0.0, flow and flow["lines"]["fold"])
receipt, only = send("brokkr_reference.flow_score", camera_name="Truth", lines=lines, objects="Box", box=box, height=600)
check("objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size",
receipt["status"] == "accepted" and only["edges"] == {"crease": 3, "contour": 6, "border": 0} and only["objects"] == ["Box"] and only["lines"]["front"]["on"] == 0.0, [receipt["message"], only])
for fields, said in (({"objects": "Nobody"}, "not a mesh object"), ({"objects": "Truth"}, "not a mesh object"), ({"lines": "1,2 3,4"}, "no tag"), ({"camera_name": "Box"}, "not a camera")):
receipt, _ = send("brokkr_reference.flow_score", **{"camera_name": "Truth", "lines": lines, **fields})
check(f"flow_score refuses {next(iter(fields))}: failed, saying '{said}'", receipt["status"] == "failed" and said in receipt["message"], receipt["message"])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,318 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "host file admitted",
"ok": true,
"detail": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera",
"brokkr_reference.lift_pair",
"brokkr_reference.flow_score"
]
},
{
"name": "crease_run stands where Blender builds the creased column, within 1e-4 m",
"ok": true,
"detail": 4.76837158203125e-07
},
{
"name": "lift_pair: accepted, 24 points on the crease within 1 mm, on the frame's -x side, none ambiguous or unmatched, no object made",
"ok": true,
"detail": [
"Operator brokkr_reference.lift_pair finished.",
9.701819854982612e-06
]
},
{
"name": "the cage column's built crease passes through the lifted crease, and draws within 1 px of both lines",
"ok": true,
"detail": [
8.333333333387927e-06,
{
"line_a": 0.004,
"line_b": 0.001
}
]
},
{
"name": "lift_pair through a box, with curve_name: 12 points on the +x side, a poly curve parented to the frame that the camera draws on line A",
"ok": true,
"detail": [
"Operator brokkr_reference.lift_pair finished.",
0.000585166962680123
]
},
{
"name": "a second run updates the one curve: 24 points, one spline",
"ok": true,
"detail": "Operator brokkr_reference.lift_pair finished."
},
{
"name": "lift_pair refuses frame_name: failed, saying 'no object is named'",
"ok": true,
"detail": "Error: no object is named 'Nobody'."
},
{
"name": "lift_pair refuses camera_name: failed, saying 'not a camera'",
"ok": true,
"detail": "Error: 'Hull' is not a camera object."
},
{
"name": "lift_pair refuses line_a: failed, saying 'no length'",
"ok": true,
"detail": "Error: line_a is 1 points of no length; a traced line is two or more, 'u,v u,v ...'"
},
{
"name": "lift_pair refuses curve_name: failed, saying 'not a curve'",
"ok": true,
"detail": "Error: 'Truth' is an object that is not a curve."
},
{
"name": "lift_pair refuses line_b: failed, saying 'no mirror'",
"ok": true,
"detail": "Error: 24 of 24 points of line A have no mirror on line B: the lines are not a mirrored pair in this frame through this camera."
},
{
"name": "fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so",
"ok": true,
"detail": [
[
-0.4140099287033081,
0.5732445120811462,
-0.7070971727371216
],
[
0.4140099287033081,
-0.5732445120811462,
-0.7070971727371216
]
]
},
{
"name": "flow_score: accepted; the box shows 3 creases and 6 contours, the sheet 6 borders and no crease",
"ok": true,
"detail": [
"Operator brokkr_reference.flow_score finished.",
{
"crease": 3,
"contour": 6,
"border": 6
}
]
},
{
"name": "the box's front edge and the top's two edges score on 1, run 1",
"ok": true,
"detail": {
"front": {
"on": 1.0,
"off": 0.0,
"run": 1.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.988,
"off": 0.06,
"run": 0.537
}
}
},
{
"name": "the box's hidden back edge scores on 0",
"ok": true,
"detail": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
{
"name": "the sheet's fold, both faces turned away, scores on 0 (N5 reads 1)",
"ok": true,
"detail": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
{
"name": "objects names the meshes read: the box alone has no border; lines in the frame's pixels miss a box twice its size",
"ok": true,
"detail": [
"Operator brokkr_reference.flow_score finished.",
{
"lines": {
"front": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.0,
"off": 5.0,
"run": 0.0
}
},
"edges": {
"crease": 3,
"contour": 6,
"border": 0
},
"objects": [
"Box"
],
"height": 600.0
}
]
},
{
"name": "flow_score refuses objects: failed, saying 'not a mesh object'",
"ok": true,
"detail": "Error: 'Nobody' is not a mesh object of this scene."
},
{
"name": "flow_score refuses objects: failed, saying 'not a mesh object'",
"ok": true,
"detail": "Error: 'Truth' is not a mesh object of this scene."
},
{
"name": "flow_score refuses lines: failed, saying 'no tag'",
"ok": true,
"detail": "Error: lines entry '1,2 3,4' has no tag; it is 'tag: u,v u,v ...'"
},
{
"name": "flow_score refuses camera_name: failed, saying 'not a camera'",
"ok": true,
"detail": "Error: 'Box' is not a camera object."
}
],
"hostErrors": [],
"hostRows": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera",
"brokkr_reference.lift_pair",
"brokkr_reference.flow_score"
],
"BUILT": [
[
0.5,
0.0,
0.0
],
[
0.54375,
0.09375,
0.5
],
[
0.55,
0.15,
1.0
],
[
0.504167,
0.139583,
1.5
],
[
0.483333,
0.066667,
2.0
],
[
0.55,
-0.04375,
2.5
],
[
0.616667,
-0.116667,
3.0
],
[
0.589583,
-0.089583,
3.5
],
[
0.5,
0.0,
4.0
]
],
"lift": {
"off": 9.701819854982612e-06,
"through": 8.333333333387927e-06,
"miss": {
"line_a": 0.004,
"line_b": 0.001
}
},
"flow": {
"lines": {
"front": {
"on": 1.0,
"off": 0.0,
"run": 1.0
},
"back": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"fold": {
"on": 0.0,
"off": 5.0,
"run": 0.0
},
"top": {
"on": 0.988,
"off": 0.06,
"run": 0.537
}
},
"edges": {
"crease": 3,
"contour": 6,
"border": 6
},
"objects": [
"Box",
"Sheet"
],
"height": 600.0
},
"ok": true
}