brokkr_reference: lift_pair and flow_score, the mirrored-pair lift, the cage through a crease and the flow score in core

Promoted from experiments/mechs/fitshell.py and mechlib.built_edges (3f45b67): matrix, resampled, extended,
pair, on_plane, seen, crease_run, cage_through, along; the centre plate, the outline descent and their masks
stay in the harness.

pair meets line b's own segments (no resampling), counts unmatched and ambiguous points, and gives an
ambiguous point the crossing its lifted neighbours run on to: every crossing triangulates to a point that
draws back onto both lines, so reprojection cannot choose.

crease_run is Blender's level-1 Subdivision of a hard crease with Limit Surface on (the default, and what
kitbash shells build with): fitshell's (1, 6, 1) / 8 step, then each point set on the limit curve.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 20:24:19 +01:00
commit c9f290bb90
4 changed files with 627 additions and 14 deletions

View file

@ -1,4 +1,6 @@
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points.
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points;
lines traced on the view lifted through that camera into a part's frame; and traced lines scored against the edges
the camera sees on the build.
A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from
Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The
@ -6,14 +8,19 @@ arithmetic is core.py (numpy, tested without Blender); this file is the bpy arou
JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do.
The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and
core.camera_of reads one back. The images, traces and masks a view is marked on stay with whoever marked them:
this package takes points and gives cameras.
core.camera_of reads one back (lift_pair and flow_score take the camera that way, by its object's name). The
images, traces and masks a view is marked on stay with whoever marked them: this package takes points and lines
and gives cameras, creases and scores. A curve lift_pair draws is for the eye; its report is the truth. The edges
flow_score reads are computed on each call and kept nowhere.
"""
bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
"category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."}
import math
import bpy
from mathutils import Matrix
import numpy as np
from mathutils import Matrix, Vector
try:
from brokkr_mesh_polish import RESULT, PolishOperator, Refused
@ -75,7 +82,151 @@ class BROKKR_REFERENCE_OT_solve_camera(PolishOperator):
return report
classes = (BROKKR_REFERENCE_OT_solve_camera,)
def record(context, name, box):
"""The camera record of the scene camera `name` (core.camera_of), the frame being `box` on the image ('' for
the render's own frame from 0, 0)."""
obj = bpy.data.objects.get(name)
if obj is None or obj.type != "CAMERA":
raise Refused(f"{name!r} is not a camera object.")
data, render = obj.data, context.scene.render
if data.type != "PERSP":
raise Refused(f"camera {name!r} is {data.type}; a camera record is a perspective camera's.")
fit = "HORIZONTAL" if data.sensor_fit == "AUTO" and render.resolution_x >= render.resolution_y else data.sensor_fit
place, turn, _ = obj.matrix_world.decompose() # a scaled camera object draws the same picture
return core.camera_of({"matrix_world": [list(row) for row in Matrix.LocRotScale(place, turn, None)], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y,
"sensor_width": data.sensor_width, "sensor_fit": fit, "resolution": [render.resolution_x, render.resolution_y]},
core.numbers(box, 4, "box") if box.strip() else None)
def built_edges(context, cam, objects, angle):
"""The edges a camera record sees on the build as it stands, modifiers evaluated: creases (two faces meeting at
more than `angle` degrees, one of them toward the camera), contours (one face toward the camera, the other
away) and open borders, each kept where two of three points along it are hidden behind nothing. `objects` are
the meshes read; anything the scene renders hides. Returns {kind: [[u0, v0, u1, v1], ...]} in the record's pixels."""
scene, dg = context.scene, context.evaluated_depsgraph_get()
eye, out, cos_a = np.array(cam["C"]), {"crease": [], "contour": [], "border": []}, math.cos(math.radians(angle))
for obj in objects:
ev = obj.evaluated_get(dg)
me = ev.to_mesh()
nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons)
if not nf:
ev.to_mesh_clear()
continue
co, ends, loop_edge, totals, normal, centre = np.empty(nv * 3), np.empty(ne * 2, np.int32), np.empty(nl, np.int32), np.empty(nf, np.int32), np.empty(nf * 3), np.empty(nf * 3)
me.vertices.foreach_get("co", co)
me.edges.foreach_get("vertices", ends)
me.loops.foreach_get("edge_index", loop_edge)
me.polygons.foreach_get("loop_total", totals)
me.polygons.foreach_get("normal", normal)
me.polygons.foreach_get("center", centre)
ev.to_mesh_clear()
world = np.array(obj.matrix_world)
co, centre = co.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], centre.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
normal = normal.reshape(-1, 3) @ np.linalg.inv(world[:3, :3])
normal /= np.maximum(np.linalg.norm(normal, axis=1), 1e-12)[:, None]
order = np.argsort(loop_edge, kind="stable")
faces, count = np.repeat(np.arange(nf), totals)[order], np.bincount(loop_edge, minlength=ne)
first = np.searchsorted(loop_edge[order], np.arange(ne))
two = count == 2
f0, f1 = faces[np.minimum(first, nl - 1)], faces[np.minimum(first + 1, nl - 1)]
toward = ((eye - centre) * normal).sum(1) > 0
crease = two & ((normal[f0] * normal[f1]).sum(1) < cos_a) & (toward[f0] | toward[f1])
contour = two & (toward[f0] != toward[f1])
ends = ends.reshape(-1, 2)
for k in np.nonzero(crease | contour | (count == 1))[0]:
a, b = co[ends[k, 0]], co[ends[k, 1]]
clear = 0
for t in (0.2, 0.5, 0.8):
p = a + t * (b - a)
d = float(np.linalg.norm(p - eye))
clear += not scene.ray_cast(dg, Vector(eye), Vector((p - eye) / d), distance=d - 0.03)[0]
if clear >= 2:
(u0, v0), (u1, v1) = core.project(cam, [a, b])
out["contour" if contour[k] else "crease" if crease[k] else "border"].append([float(u0), float(v0), float(u1), float(v1)])
return out
class BROKKR_REFERENCE_OT_lift_pair(PolishOperator):
"""Lift two traced lines that are one crease and its mirror image through a camera into a frame, with the cage
column whose built crease passes through it"""
bl_idname = "brokkr_reference.lift_pair"
bl_label = "Lift Mirrored Pair"
camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="The camera object the view is seen through (solve_camera stands one)")
box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; empty is the render's own frame")
frame_name: bpy.props.StringProperty(name="Frame", maxlen=63, description="An object whose matrix_world is the part's frame; its x = 0 is the mirror plane")
line_a: bpy.props.StringProperty(name="Line A", maxlen=4000, description="u,v u,v ... the crease as traced on one side")
line_b: bpy.props.StringProperty(name="Line B", maxlen=4000, description="u,v u,v ... its mirror image as traced on the other side")
samples: bpy.props.IntProperty(name="Samples", default=24, min=2, max=200, description="Points lifted, evenly along line A")
extend: bpy.props.FloatProperty(name="Extend", default=0.2, min=0.0, max=1.0, description="Line B is run on straight past its ends by this share of its length, to find mirrors for the ends of line A")
curve_name: bpy.props.StringProperty(name="Curve", maxlen=63, description="A curve object to create or update along the crease on line A's side, parented to the frame; empty draws none")
def work(self, context):
frame = bpy.data.objects.get(self.frame_name)
if frame is None:
raise Refused(f"no object is named {self.frame_name!r}.")
if self.curve_name and getattr(bpy.data.objects.get(self.curve_name), "type", "CURVE") != "CURVE":
raise Refused(f"{self.curve_name!r} is an object that is not a curve.")
try:
cam = record(context, self.camera_name, self.box)
a, b = core.polyline(self.line_a, "line_a"), core.polyline(self.line_b, "line_b")
except core.ReferenceFitError as refusal:
raise Refused(str(refusal)) from None
F = np.array(frame.matrix_world)
out = core.pair(cam, F, a, b, n=self.samples, extend=self.extend)
if len(out["crease"]) < 2:
raise Refused(f"{out['unmatched']} of {self.samples} points of line A have no mirror on line B: the lines are not a mirrored pair in this frame through this camera.")
crease = np.array(out["crease"])
cage = core.cage_through(crease)
run = core.crease_run(cage)
report = {**out, "crease": crease.round(5).tolist(), "cage": cage.round(5).tolist(),
"miss": {"line_a": round(core.drawn_off(cam, F, run * [out["side"], 1, 1], a), 3), "line_b": round(core.drawn_off(cam, F, run * [-out["side"], 1, 1], core.extended(b, self.extend)), 3)},
"curve": None}
if self.curve_name:
obj = bpy.data.objects.get(self.curve_name)
if obj is None:
obj = bpy.data.objects.new(self.curve_name, bpy.data.curves.new(self.curve_name, "CURVE"))
context.scene.collection.objects.link(obj)
obj.data.dimensions = "3D"
obj.data.splines.clear()
spline = obj.data.splines.new("POLY")
spline.points.add(len(crease) - 1)
spline.points.foreach_set("co", np.c_[crease * [out["side"], 1, 1], np.ones(len(crease))].ravel())
obj.parent, obj.matrix_parent_inverse, obj.matrix_basis = frame, Matrix(), Matrix()
report["curve"] = obj.name
return report
class BROKKR_REFERENCE_OT_flow_score(PolishOperator):
"""Score traced lines against the edges a camera sees on the build: how much of each line has a built crease,
contour or border running along it"""
bl_idname = "brokkr_reference.flow_score"
bl_label = "Flow Score"
camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="The camera object the view is seen through (solve_camera stands one)")
box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; empty is the render's own frame")
height: bpy.props.FloatProperty(name="Height", default=0.0, min=0.0, max=1000000.0, description="The figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height")
lines: bpy.props.StringProperty(name="Lines", maxlen=12000, description="tag: u,v u,v ...; tag: u,v u,v ... the traced lines")
objects: bpy.props.StringProperty(name="Objects", maxlen=4000, description="Mesh objects whose edges are read, name; name; ... empty is every mesh the render shows")
angle: bpy.props.FloatProperty(name="Angle", default=18.0, min=1.0, max=179.0, description="Degrees between two faces' normals past which their edge is a crease")
def work(self, context):
try:
cam = record(context, self.camera_name, self.box)
lines = core.polylines(self.lines, "lines")
except core.ReferenceFitError as refusal:
raise Refused(str(refusal)) from None
names = [name.strip() for name in self.objects.split(";") if name.strip()]
meshes = [bpy.data.objects.get(name) for name in names] if names else [o for o in context.scene.objects if o.type == "MESH" and not o.hide_render]
for name, obj in zip(names, meshes):
if obj is None or obj.type != "MESH" or obj.name not in context.scene.objects:
raise Refused(f"{name!r} is not a mesh object of this scene.")
edges = built_edges(context, cam, meshes, self.angle)
height = self.height or cam["box"][3] - cam["box"][1]
segments = [seg for kind in edges.values() for seg in kind]
return {"lines": {tag: core.along(line, segments, height) for tag, line in lines.items()}, "edges": {kind: len(found) for kind, found in edges.items()},
"objects": [o.name for o in meshes], "height": height}
classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_lift_pair, BROKKR_REFERENCE_OT_flow_score)
def register():

View file

@ -80,6 +80,128 @@
"doc": "pixels across the frame the box becomes when camera_name is given"
}
]
},
{
"name": "brokkr_reference.lift_pair",
"doc": "Lift two traced lines that are one crease and its mirror image, on a part symmetric about its frame's x = 0, through a camera into the frame. The result is the crease, the cage column whose level-1 crease is built through it, the counts of ambiguous and unmatched points, and how far the built crease draws from each line (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "camera_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the camera object the view is seen through (solve_camera stands one)"
},
{
"name": "box",
"type": "string",
"maxLength": 120,
"doc": "u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0"
},
{
"name": "frame_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "an object whose matrix_world is the part's frame; its x = 0 is the mirror plane"
},
{
"name": "line_a",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 4000,
"doc": "u,v u,v ... the crease as traced on one side, pixels, v down"
},
{
"name": "line_b",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 4000,
"doc": "u,v u,v ... its mirror image as traced on the other side"
},
{
"name": "samples",
"type": "integer",
"minimum": 2,
"maximum": 200,
"default": 24,
"doc": "points lifted, evenly along line_a"
},
{
"name": "extend",
"type": "number",
"minimum": 0,
"maximum": 1,
"default": 0.2,
"doc": "line_b is run on straight past its ends by this share of its length, to find mirrors for the ends of line_a"
},
{
"name": "curve_name",
"type": "string",
"maxLength": 63,
"doc": "a curve object to create or update along the crease on line_a's side, parented to the frame; absent draws none"
}
]
},
{
"name": "brokkr_reference.flow_score",
"doc": "Score traced lines against the edges a camera sees on the evaluated build (creases, contours and open borders, unhidden): per line, the share with a built edge running along it (on), the mean distance to one in % of height (off) and the longest unbroken share (run); and the count of edges by kind (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "camera_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the camera object the view is seen through (solve_camera stands one)"
},
{
"name": "box",
"type": "string",
"maxLength": 120,
"doc": "u0,v0,u1,v1: the camera's frame on the image, in the pixels the lines were traced in; absent is the render's own frame from 0,0"
},
{
"name": "height",
"type": "number",
"minimum": 0,
"maximum": 1000000,
"default": 0,
"doc": "the figure's height in those pixels: an edge within 1% of it is near; 0 is the box's height"
},
{
"name": "lines",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 12000,
"doc": "tag: u,v u,v ...; tag: u,v u,v ... the traced lines"
},
{
"name": "objects",
"type": "string",
"maxLength": 4000,
"doc": "mesh objects whose edges are read, name; name; ... absent is every mesh the render shows"
},
{
"name": "angle",
"type": "number",
"minimum": 1,
"maximum": 179,
"default": 18,
"doc": "degrees between two faces' normals past which their edge is a crease"
}
]
}
]
}

View file

@ -23,7 +23,18 @@ focal length trade against each other (a dolly zoom), and "lens_band" says how f
blender(cam, width) what a Blender camera takes to be this one, the frame being the box
camera_of(params, box) the record of a Blender camera: blender() read back
in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders
points(text, size), numbers(text, count) the action's string fields
points, numbers, polyline, polylines the actions' string fields
A line traced on the view is two numbers a point; a crease in the world is three. The third comes from what is
known of the part, in a frame: a 4 x 4 frame-to-world matrix whose x = 0 is the part's mirror plane.
pair(cam, frame, a, b) two traced lines that are one crease and its mirror image: the crease
on_plane(cam, frame, line, point, normal) one traced line lifted onto a plane of the frame
seen(cam, frame, points) pixels of points of a frame
crease_run(points) where Blender builds the hard crease of a cage column at one level
cage_through(targets) the cage column whose built crease passes through the targets
drawn_off(cam, frame, points, line) mean distance, pixels, from a drawn polyline of the frame to a line
along(line, segments, height) the flow score: how much of a traced line has a seen edge along it
"""
from __future__ import annotations
@ -334,6 +345,172 @@ def in_frame(cam, pixels, width):
return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2])
# --- traced lines lifted into a frame ---------------------------------------------------------------------------------
MIRROR = np.diag([-1.0, 1.0, 1.0, 1.0]) # a frame's mirror plane is its x = 0
def matrix(cam):
"""The camera as a 3 x 4 projection: pixels = (P @ [x, y, z, 1])[:2] / its third."""
R, C, f, c = np.asarray(cam["R"], float), np.asarray(cam["C"], float), cam["f"], cam["c"]
K = np.array([[f, 0, -c[0]], [0, -f, -c[1]], [0, 0, -1.0]])
return K @ np.c_[R, -R @ C]
def resampled(points, n):
"""A polyline as n points evenly spaced along it."""
p = np.asarray(points, float)
d = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))])
t = np.linspace(0, d[-1], n)
return np.stack([np.interp(t, d, p[:, k]) for k in range(p.shape[1])], 1)
def extended(points, by):
"""A polyline run on straight past both ends by `by` of its length."""
p = np.asarray(points, float)
length = np.linalg.norm(np.diff(p, axis=0), axis=1).sum()
head, tail = p[0] - p[1], p[-1] - p[-2]
return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length])
def pair(cam, frame, a, b, n=24, extend=0.2):
"""The crease that traced lines `a` and `b` (pixels) are the two mirror images of, on a part symmetric about its
frame's x = 0. A point of `a` and its mirror on `b` lie on a line through the vanishing point of the frame's x
axis; the pair is triangulated as one point seen by the camera and by the camera's mirror image, so each lifted
point draws back onto both lines exactly. `b` is run on past its ends by `extend` of its length to find mirrors
for the ends of `a`.
Returns {"crease": [[x, y, z], ...] in the frame, x >= 0, in the order of `a`; "side": the side of the frame
`a` is on, +1 or -1; "unmatched": points of `a` whose line to the vanishing point never meets `b`, left out;
"ambiguous": points whose line meets `b` more than once}. Every crossing of such a line triangulates to a
point that draws back onto both lines, so the drawing cannot say which is meant; the crease can: an ambiguous
point takes the crossing whose lift stands nearest where its two lifted neighbours along `a` run on to, the
points with one crossing first. With no such point anywhere, the first ambiguous point takes its first crossing along `b`.
The lift is as sure as the frame's turn to the camera: seen nearly along the mirror plane the two sight lines
are nearly parallel, and a degree of turn moves the crease a long way in depth."""
P = matrix(cam)
F = np.asarray(frame, float)
P1, P2 = P @ F, P @ F @ MIRROR
vp = P1 @ np.array([1.0, 0, 0, 0])
A, B = resampled(a, n), extended(b, extend)
found = []
for q in A:
d = vp[:2] - vp[2] * q # toward the vanishing point, wherever it is (at infinity too)
s = (B - q) @ (np.array([-d[1], d[0]]) / np.linalg.norm(d))
lifts = []
for k in np.nonzero((s[:-1] < 0) != (s[1:] < 0))[0]:
m = B[k] + s[k] / (s[k] - s[k + 1]) * (B[k + 1] - B[k])
M = np.array([q[0] * P1[2] - P1[0], q[1] * P1[2] - P1[1], m[0] * P2[2] - P2[0], m[1] * P2[2] - P2[1]])
X = np.linalg.svd(M)[2][-1]
lifts.append(X[:3] / X[3])
found.append(lifts)
chosen = [lifts[0] if len(lifts) == 1 else None for lifts in found]
open_ = [i for i, lifts in enumerate(found) if len(lifts) > 1]
if open_ and len(open_) == sum(1 for lifts in found if lifts):
chosen[open_[0]] = found[open_[0]][0]
fold = lambda X: np.array([abs(X[0]), X[1], X[2]]) # noqa: E731
for order in (range(n), range(n - 1, -1, -1)):
last = [] # the two lifted points before this one, as (index, point): the crease runs on from them
for i in order:
if chosen[i] is None and found[i] and last:
(j, X1), (k, X0) = last[-1], last[-2] if len(last) > 1 else last[-1]
ahead = X1 + (X1 - X0) * ((i - j) / (j - k) if j != k else 0.0)
chosen[i] = min(found[i], key=lambda X: np.linalg.norm(fold(X) - ahead))
if chosen[i] is not None:
last = (last + [(i, fold(chosen[i]))])[-2:]
lifted = [X for X in chosen if X is not None]
return {"crease": [[float(v) for v in fold(X)] for X in lifted], "side": 1 if sum(np.sign(X[0]) for X in lifted) >= 0 else -1,
"ambiguous": len(open_), "unmatched": sum(1 for lifts in found if not lifts)}
def on_plane(cam, frame, line, point, normal, n=24):
"""A traced line (pixels) lifted onto the plane of the frame through `point` with `normal`: [[x, y, z], ...] in
the frame."""
F = np.asarray(frame, float)
inv = np.linalg.inv(F)
p0, nw = F[:3, :3] @ np.asarray(point, float) + F[:3, 3], np.asarray(normal, float) @ inv[:3, :3]
return [[float(v) for v in inv[:3, :3] @ lift(cam, q, p0, nw) + inv[:3, 3]] for q in resampled(line, n)]
def seen(cam, frame, points):
"""Pixels of points of a frame."""
F = np.asarray(frame, float)
return project(cam, np.asarray(points, float) @ F[:3, :3].T + F[:3, 3])
def crease_run(points):
"""The built edges of a hard crease whose cage column is `points`, after one level of Catmull-Clark as Blender's
Subdivision modifier builds it: each inner cage point moves to (1, 6, 1) / 8 of itself and its neighbours, a
new point stands at each middle, the ends stay; then every point but the ends is set on the limit curve,
(1, 4, 1) / 6 of itself and its new neighbours (the modifier's Limit Surface, on by default; with it off the
crease stands at the first step and this is not it). A polyline of 2n - 1 points; the cage's own points are
its even ones, each at (1, 4, 1) / 6 of the cage."""
p = np.asarray(points, float)
v = p.copy()
v[1:-1] = (p[:-2] + 6 * p[1:-1] + p[2:]) / 8
out = np.empty((2 * len(p) - 1, p.shape[1]))
out[0::2], out[1::2] = v, (p[:-1] + p[1:]) / 2
out[1:-1] = (out[:-2] + 4 * out[1:-1] + out[2:]) / 6
return out
def cage_through(targets, rounds=30):
"""The cage column whose built crease (crease_run) passes through `targets` at its own points."""
t = np.asarray(targets, float)
c = t.copy()
for _ in range(rounds):
c += t - crease_run(c)[0::2]
return c
def _off(points, line):
"""Per point, its distance to a polyline."""
p, q = np.asarray(points, float), np.asarray(line, float)
a, d = q[:-1], q[1:] - q[:-1]
t = np.clip(((p[:, None] - a) * d).sum(2) / np.maximum((d * d).sum(1), 1e-18), 0, 1)
return np.linalg.norm(a + t[:, :, None] * d - p[:, None], axis=2).min(1)
def drawn_off(cam, frame, points, line, n=200):
"""Mean distance, pixels, from where the camera draws a polyline of the frame to a traced line."""
return float(_off(resampled(seen(cam, frame, points), n), line).mean())
def along(line, segments, height, near=0.01, turn=20.0, cap=0.05):
"""The flow score: how much of a traced line (pixels) has a seen edge running along it. `segments` are
[u0, v0, u1, v1] in the same pixels, `height` the figure's height there. Per point of the line: the distance to
the nearest segment within `turn` degrees of the line's direction. Returns {"on": the share of the line with
such an edge within `near` of the height, "off": the mean distance to one in % of the height, capped at `cap`,
"run": the longest unbroken share that is on}."""
p = resampled(line, 80)
tan = np.gradient(p, axis=0)
tan /= np.linalg.norm(tan, axis=1)[:, None]
S = np.asarray(segments, float).reshape(-1, 4)
if not len(S):
return {"on": 0.0, "off": 100 * cap, "run": 0.0}
a, d = S[:, :2], S[:, 2:] - S[:, :2]
length = np.maximum(np.linalg.norm(d, axis=1), 1e-9)
u = d / length[:, None]
dist = np.empty(len(p))
for i, (q, t) in enumerate(zip(p, tan)):
ok = np.abs(u @ t) >= math.cos(math.radians(turn))
if not ok.any():
dist[i] = np.inf
continue
s = np.clip(((q - a[ok]) * u[ok]).sum(1), 0, length[ok])
dist[i] = np.linalg.norm(a[ok] + s[:, None] * u[ok] - q, axis=1).min()
on = dist <= near * height
run = best = 0
for flag in on:
run = run + 1 if flag else 0
best = max(best, run)
return {"on": round(float(on.mean()), 3), "off": round(float(100 * np.minimum(dist / height, cap).mean()), 2), "run": round(best / len(on), 3)}
# --- fields ----------------------------------------------------------------------------------------------------------
def numbers(text, count, what):
"""'1, 2.5, 3' as `count` finite floats; ReferenceFitError names `what`."""
try:
@ -360,3 +537,29 @@ def points(text, size, what):
raise ReferenceFitError(f"{what} names {name!r} twice")
out[name] = numbers(values, size, f"{what} point {name!r}:")
return out
def polyline(text, what):
"""'u,v u,v ...' as an (n, 2) array of two or more different points; ReferenceFitError names `what`."""
line = np.array([numbers(piece, 2, f"{what} point") for piece in text.split()], float).reshape(-1, 2)
if len(line) < 2 or not np.ptp(line, axis=0).max() > 0:
raise ReferenceFitError(f"{what} is {len(line)} points of no length; a traced line is two or more, 'u,v u,v ...'")
return line
def polylines(text, what):
"""'tag: u,v u,v ...; tag: ...' as {tag: polyline}; a tag given twice is refused."""
out = {}
for entry in (piece.strip() for piece in text.split(";")):
if not entry:
continue
tag, colon, line = entry.partition(":")
tag = tag.strip()
if not colon or not tag:
raise ReferenceFitError(f"{what} entry {entry[:40]!r} has no tag; it is 'tag: u,v u,v ...'")
if tag in out:
raise ReferenceFitError(f"{what} names {tag!r} twice")
out[tag] = polyline(line, f"{what} line {tag!r}")
if not out:
raise ReferenceFitError(f"{what} holds no line; it is 'tag: u,v u,v ...; tag: ...'")
return out

View file

@ -237,6 +237,132 @@ class SolveTests(unittest.TestCase):
self.assertNotIn("NaN", json.dumps(held))
def crease(n=2000):
"""A crease of a part in its frame, x > 0: a bowed line 2 m long, as dense as a line drawn with a ruler."""
t = np.linspace(0, 1, n)
return np.stack([0.4 + 0.2 * np.sin(2.5 * t), -1.0 + 2.0 * t, 0.5 + 0.3 * t * t], 1)
FRAME = [[0.9659258262890683, -0.25881904510252074, 0.0, 0.3], [0.25881904510252074, 0.9659258262890683, 0.0, -0.2], [0.0, 0.0, 1.0, 0.1], [0.0, 0.0, 0.0, 1.0]] # turned 15 degrees about z and moved
VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35))
@unittest.skipIf(np is None, "numpy")
class LiftTests(unittest.TestCase):
"""Traced lines lifted into a frame, the cage through a crease, and the flow score. Mutants, each run once:
N1 the mirror camera without MIRROR test_a_mirrored_pair_lifts_back_to_its_crease
N2 the first crossing kept test_a_folded_line_takes_the_crossing_its_neighbours_agree_with
N3 crease_run without the limit step test_crease_run_is_one_level_of_subdivision
N3b its first step weighs (1, 4, 1) / 6 the same
N4 along without the direction test test_along_scores_edges_that_run_with_the_line
N6 cage_through stops after one round test_the_cage_through_a_crease_builds_through_it
N5 (back-facing creases counted) is claimed by tests/live/reference_lift.py."""
@classmethod
def setUpClass(cls):
cls.truth = crease()
F = np.array(FRAME)
both = np.vstack([cls.truth, cls.truth * [-1, 1, 1]]) @ F[:3, :3].T + F[:3, 3]
cls.cams = [camera(both, *view) for view in VIEWS]
def traced(self, cam, side=1):
return core.seen(cam, FRAME, self.truth * [side, 1, 1])
def off(self, lifted):
"""How far lifted points stand from the true crease, metres: the worst."""
return float(core._off(np.array(lifted), self.truth).max())
def test_a_mirrored_pair_lifts_back_to_its_crease(self):
"""pair-exact, N1: with nothing mirrored both sight lines are one camera's and the lift is nowhere: 6.0 m off
at the first view and on the wrong side at the second. Shipped reads 1e-15 m, float noise; 1e-6 m is the
cut's tolerance round the truth."""
for cam, flipped in zip(self.cams, (1, -1, 1)):
out = core.pair(cam, FRAME, self.traced(cam, flipped), self.traced(cam, -flipped))
self.assertEqual((len(out["crease"]), out["side"], out["ambiguous"], out["unmatched"]), (24, flipped, 0, 0))
self.assertLess(self.off(out["crease"]), 1e-6)
for side, line in ((out["side"], self.traced(cam, flipped)), (-out["side"], self.traced(cam, -flipped))):
self.assertLess(float(core._off(core.seen(cam, FRAME, np.array(out["crease"]) * [side, 1, 1]), line).max()), 1e-6)
def test_a_hand_traced_pair_lifts_within_a_bound(self):
"""pair-exact at 1.5 px: twelve points a line, each 1.5 px off (a hand's trace). A tolerance round the truth
that no mutant claims: the worst of three views reads 0.0122 m, 0.6% of the crease's 2.05 m."""
r = np.random.default_rng(11)
worst = 0.0
for cam in self.cams:
a, b = (core.resampled(self.traced(cam, side), 12) + r.normal(0, 1.5, (12, 2)) for side in (1, -1))
out = core.pair(cam, FRAME, a, b)
self.assertGreaterEqual(len(out["crease"]), 20)
worst = max(worst, self.off(out["crease"]))
self.assertLess(worst, 0.02)
def test_a_folded_line_takes_the_crossing_its_neighbours_agree_with(self):
"""pair-folded-line, N2: line b starts with a stroke that doubles back beside itself, so the first points of
`a` meet it twice or more. Shipped reads 9e-16 m off the true crease (float noise, for which the exact
lift's 1e-6 m stands), the first crossing kept (N2) 0.0089 m: the bound is the geometric mean of 1e-6 and
0.0089, separation 94 each side."""
cam = self.cams[0]
a, b = self.traced(cam)[100:], self.traced(cam, -1)
d = b[600] - b[0]
hook = b[600:0:-40] + 0.04 * np.array([-d[1], d[0]])
out = core.pair(cam, FRAME, a, np.vstack([hook, b]), extend=0.02)
self.assertGreater(out["ambiguous"], 3)
self.assertEqual((out["unmatched"], len(out["crease"])), (0, 24))
self.assertLess(self.off(out["crease"]), 9.4e-5)
def test_a_line_with_no_mirror_is_counted_unmatched(self):
cam = self.cams[0]
out = core.pair(cam, FRAME, self.traced(cam), self.traced(cam, -1)[:1000], extend=0.0)
self.assertGreater(out["unmatched"], 8)
self.assertEqual(len(out["crease"]) + out["unmatched"], 24)
self.assertLess(self.off(out["crease"]), 1e-6)
def test_a_line_lifted_onto_a_plane_stands_on_it(self):
cam = self.cams[1]
flat = np.c_[np.full(50, 0.3), np.linspace(-1, 1, 50), np.linspace(0.2, 0.9, 50) ** 2]
lifted = np.array(core.on_plane(cam, FRAME, core.seen(cam, FRAME, flat), [0.3, 0.0, 0.0], [1.0, 0.0, 0.0]))
self.assertLess(np.abs(lifted[:, 0] - 0.3).max(), 1e-9)
self.assertLess(float(core._off(lifted, flat).max()), 1e-3)
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]]
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]] # Blender 5.3's level-1 Subdivision of this column creased hard, as tests/live/reference_lift.py printed it
def test_crease_run_is_one_level_of_subdivision(self):
"""crease-run-and-through, N3: against Blender's own numbers, which are the limit curve's (the modifier's
Limit Surface is on unless turned off). Shipped reads 3.3e-7 m, the fixture's rounding; N3b 0.0139 and N3
0.0208: the bound is the geometric mean of 3.3e-7 and 0.0139, separation 205 each side."""
run = core.crease_run(self.COLUMN)
self.assertEqual(run.shape, (9, 3))
self.assertLess(np.abs(run - np.array(self.BUILT)).max(), 6.8e-5)
def test_the_cage_through_a_crease_builds_through_it(self):
"""crease-run-and-through, N6: shipped reads 3.7e-11 m between the built crease and its targets, one round
1.57e-3: the bound is their geometric mean, separation 6500 each side."""
targets = self.truth[::400]
cage = core.cage_through(targets)
self.assertLess(np.abs(core.crease_run(cage)[0::2] - targets).max(), 2.4e-7)
def test_along_scores_edges_that_run_with_the_line(self):
"""along-scores, N4: rungs 5 px apart cross the line square-on, each within the 10 px that counts as near."""
line = [[100.0, 200.0], [500.0, 200.0]]
self.assertEqual(core.along(line, [[80.0, 203.0, 520.0, 203.0]], 1000.0), {"on": 1.0, "off": 0.3, "run": 1.0})
rungs = [[float(u), 150.0, float(u), 250.0] for u in range(100, 501, 5)]
self.assertEqual(core.along(line, rungs, 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0})
half = core.along(line, [[100.0, 200.0, 300.0, 200.0]], 1000.0)
self.assertAlmostEqual(half["on"], 0.5, delta=0.03)
self.assertEqual(half["run"], half["on"])
self.assertEqual(core.along(line, [], 1000.0), {"on": 0.0, "off": 5.0, "run": 0.0})
def test_line_parsers(self):
self.assertEqual(core.polyline("1,2 3,4.5", "line_a").tolist(), [[1.0, 2.0], [3.0, 4.5]])
self.assertEqual({k: v.tolist() for k, v in core.polylines("r: 1,2 3,4; l: 5,6 7,8;", "lines").items()}, {"r": [[1.0, 2.0], [3.0, 4.0]], "l": [[5.0, 6.0], [7.0, 8.0]]})
for call, text, said in ((core.polyline, "1,2", "no length"), (core.polyline, "1,2 1,2", "no length"), (core.polyline, "1,2 3", "point"),
(core.polylines, "1,2 3,4", "no tag"), (core.polylines, "r: 1,2 3,4; r: 1,2 3,4", "twice"), (core.polylines, " ; ", "no line")):
with self.assertRaises(core.ReferenceFitError) as caught:
call(text, "lines")
self.assertIn(said, str(caught.exception))
@unittest.skipIf(np is None, "numpy")
class CameraTests(unittest.TestCase):
CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX}
@ -300,13 +426,15 @@ class HostFileTests(unittest.TestCase):
def test_the_row_names_the_operator_and_properties_the_add_on_defines(self):
source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8")
(row,) = self.document["actions"]
self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
for field in row["fields"]:
self.assertIn(f" {field['name']}: bpy.props.", body, field["name"])
self.assertEqual(body.count(": bpy.props."), len(row["fields"]))
self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.lift_pair", "brokkr_reference.flow_score"])
self.assertEqual(source.count("bl_idname = "), 3)
for row in self.document["actions"]:
self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
for field in row["fields"]:
self.assertIn(f" {field['name']}: bpy.props.", body, field["name"])
self.assertEqual(body.count(": bpy.props."), len(row["fields"]), row["name"])
def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self):
fields = {"world": "a=0,0,0", "pixels": "a=1,2", "box": "0,0,10,10"}
@ -315,6 +443,14 @@ class HostFileTests(unittest.TestCase):
for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}):
with self.assertRaises(at.IntentInvalid):
at.validate({**self.envelope, **fields, **bad}, self.host)
lift = {**self.envelope, "action": "brokkr_reference.lift_pair", "camera_name": "Concept", "frame_name": "Hull", "line_a": "1,2 3,4", "line_b": "5,6 7,8"}
admitted = at.validate(lift, self.host)
self.assertEqual((admitted["samples"], admitted["extend"]), (24, 0.2))
flow = {**self.envelope, "action": "brokkr_reference.flow_score", "camera_name": "Concept", "lines": "r: 1,2 3,4"}
self.assertEqual((at.validate(flow, self.host)["angle"], at.validate(flow, self.host)["height"]), (18, 0))
for intent, bad in ((lift, {"samples": 1}), (lift, {"frame_name": ""}), (lift, {"extend": 1.5}), (flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})):
with self.assertRaises(at.IntentInvalid):
at.validate({**intent, **bad}, self.host)
class OwnershipTests(unittest.TestCase):
@ -325,9 +461,10 @@ class OwnershipTests(unittest.TestCase):
self.assertIsNone(re.search(r"import bpy|mathutils", (SURFACE / "brokkr_reference" / "core.py").read_text(encoding="utf-8")))
def test_the_package_reads_no_image_or_sheet(self):
"""Nor does it hold the harness's recipes: the centre plate, the outline descent and their masks stay there."""
for path in (SURFACE / "brokkr_reference").glob("*"):
if path.is_file():
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open", path.read_text(encoding="utf-8")), path.name)
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open|centre_plate|silhouette|polygon_mask|knotted", path.read_text(encoding="utf-8")), path.name)
def test_no_other_package_names_this_one(self):
for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"):