From e311f65ce3c3f6b7c86ba316d3a5b88756a8b108 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:24:19 +0100 Subject: [PATCH 01/13] 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 --- surfaces/blender/brokkr_reference/__init__.py | 161 +++++++++++++- .../brokkr_reference/brokkr_actions.json | 122 +++++++++++ surfaces/blender/brokkr_reference/core.py | 205 +++++++++++++++++- surfaces/blender/tests/test_reference.py | 153 ++++++++++++- 4 files changed, 627 insertions(+), 14 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index eb9d58f..422b324 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -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(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index 759504c..acd418b 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -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" + } + ] } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index eb3fd63..da29e51 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -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 diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 18d77e4..131a4e0 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -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"): -- 2.47.3 From d9c750542686244d17b375a27be10a5202359357 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:27:09 +0100 Subject: [PATCH 02/13] brokkr_reference: planes are solved and say so; the exact gates are one constant with a test at the gate Follow-up reference-camera-s2-lows. World points in one plane seen obliquely decide the lens, so they are solved: the record's 'plane' is the degrees between the line of sight and square-on, auto leaves the free model untried (a plane never decides the centre), and what a near square-on view leaves open is the band's to say. Refused before solving: a plane with the model free, and a plane seen exactly square-on with no lens held ('may not decide the lens'). core.EXACT (1e-9) is the one tolerance of the four exact tests; marks at 3.16e-10 are refused and at 3.16e-9 pass, so a gate ten times looser or tighter fails. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 53 +++++++++++++----- surfaces/blender/tests/test_reference.py | 67 +++++++++++++++++++++-- 2 files changed, 101 insertions(+), 19 deletions(-) diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index da29e51..4f28bb3 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -205,24 +205,45 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): return float(np.sqrt(np.mean(np.square(miss)))) -def _decidable(names, W, P, plane_will_do): +EXACT = 1e-9 # of the marks' extent: under this a set of marks is exactly degenerate (true lines and planes read 1e-16); marks placed by hand are never within 1e-3 + + +def _square_on(Q, P): + """How far pixels are from a turned and scaled copy of the points' own plane (Q, their two coordinates in it), + mirrored or not, as a share of the pixels' extent: nothing, when the plane is seen square-on.""" + b = (P - P.mean(0)).T.ravel() + miss = [] + for hand in (1.0, -1.0): + x, y = Q[:, 0], hand * Q[:, 1] + A = np.r_[np.c_[x, -y], np.c_[y, x]] + miss.append(np.linalg.norm(b - A @ np.linalg.lstsq(A, b, rcond=None)[0])) + return min(miss) / np.linalg.norm(b) + + +def _decidable(names, W, P, model, lens_held): """Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of - NaN). These are exact degeneracies, to nine digits of the marks' extent; points nearly in a line or a plane are - solved, and what they leave undecided is the band's to say.""" + NaN). These are exact degeneracies, to EXACT of the marks' extent; points nearly in a line or a plane are + solved, and what they leave undecided is the band's to say. Returns the unit normal of the plane the world + points all lie in, or None.""" for what, A in (("world point", W), ("pixel", P)): first = {} twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None] if len(first) < 6: raise ReferenceFitError(f"{len(first)} different {what}s are marked; six are needed ({twins[0][0]!r} and {twins[0][1]!r} share one)") - flat = lambda A: np.linalg.svd(A - A.mean(0), compute_uv=False) # noqa: E731 the marks' extents along their own axes, widest first - w, p = flat(W), flat(P) - if p[1] <= 1e-9 * p[0]: + (_, w, axes), p = np.linalg.svd(W - W.mean(0), full_matrices=False), np.linalg.svd(P - P.mean(0), compute_uv=False) # the marks' extents along their own axes, widest first + if p[1] <= EXACT * p[0]: raise ReferenceFitError("the pixels lie on one line: marks along a line of the image cannot say how the camera is turned about it") - if w[1] <= 1e-9 * w[0]: + if w[1] <= EXACT * w[0]: raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it") - if w[2] <= 1e-9 * w[0] and not plane_will_do: - raise ReferenceFitError("the world points lie in one plane, which does not decide the lens or the centre: mark a point off the plane, or hold `lens` and name a model other than free") + if w[2] > EXACT * w[0]: + return None + if model == "free": + raise ReferenceFitError("the world points lie in one plane, which does not decide the centre: mark a point off the plane, or name a model other than free") + if not lens_held and _square_on((W - W.mean(0)) @ axes[:2].T, P) <= EXACT: + raise ReferenceFitError("the world points lie in one plane seen square-on, which may not decide the lens: every lens draws them so from its own distance. " + "Mark a point off the plane, or hold `lens`") + return axes[2] def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): @@ -245,11 +266,16 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", - "twist" (degrees), "residuals" {name: [du, dv]}}. Every number in it is finite. + "twist" (degrees), "plane" (None, or when the world points all lie in one plane the degrees between the line + of sight and square-on to it), "residuals" {name: [du, dv]}}. Every number in it is finite. + + World points in one plane may not decide the lens: seen obliquely they do, by the plane's foreshortening; the + nearer square-on, the less, and the band says how little (a headline lens then sits anywhere in it, often at + an end of LENS_MM). The centre they never decide, so "auto" leaves "free" untried. Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or fewer than six different world points or different pixels among them; pixels on one line; world points on one - line; world points in one plane, unless `lens` is held and the model is upright, rolled or square.""" + line; world points in one plane with the model "free", or seen exactly square-on with no `lens` held.""" if model != "auto" and model not in MODELS: raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") box = [float(v) for v in box] @@ -265,13 +291,13 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) - _decidable(names, W, P, lens is not None and model not in ("auto", "free")) + normal = _decidable(names, W, P, model, lens is not None) T = np.array([k in turned for k in names]) c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) fixed = None if lens is None else lens * width / SENSOR tried = {} - for m in (("upright", "rolled", "free") if model == "auto" else (model,)): + for m in ((("upright", "rolled", "free") if normal is None else ("upright", "rolled")) if model == "auto" else (model,)): rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot) tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot)) kind = min(tried, key=lambda k: tried[k][5]) @@ -302,6 +328,7 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. "left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()}, "azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))), "distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)), + "plane": None if normal is None else float(math.degrees(math.acos(min(1.0, abs(float(cam["R"][2] @ normal)))))), "residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}} diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 131a4e0..b709b99 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -15,6 +15,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end + G10, G01 core.EXACT ten times looser, ten tighter test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent """ from __future__ import annotations @@ -211,31 +212,85 @@ class SolveTests(unittest.TestCase): self.assertTrue(issubclass(core.ReferenceFitError, ValueError)) def test_marks_that_decide_no_camera_are_refused(self): - """refusals: marks with no extent, in a line or in a plane are refused by which they are before any solve - (one pixel for every name was a bare ValueError, one world point a record of NaN). A plane is enough once - the lens is held and the centre is not solved.""" + """refusals: marks with no extent or in a line, a plane asked for its centre and a plane seen square-on + with no lens held are refused by which they are before any solve (one pixel for every name was a bare + ValueError, one world point a record of NaN).""" solved, lm = [], core.lm core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) self.addCleanup(setattr, core, "lm", lm) plane = np.c_[self.points[:, :2], np.zeros(13)] on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + square_on = on_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist())) cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"), (({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"), ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), ((line, self.pixels), {}, "world points lie on one line"), - (on_plane, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane")) + (on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre"), + (square_on, {}, "seen square-on, which may not decide the lens"), (square_on, {"model": "upright"}, "may not decide the lens"), + (square_on, {"model": "square"}, "may not decide the lens")) for args, kwargs, said in cases: with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, BOX, **kwargs) self.assertIn(said, str(caught.exception)) self.assertEqual(solved, []) - held = core.solve(*on_plane, BOX, model="upright", lens=50.0) + held = core.solve(*square_on, BOX, model="upright", lens=50.0) # with the lens held a plane decides the rest, square-on too self.assertLess(held["rms"], 1e-3) - self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01) + self.assertAlmostEqual(held["elevation"], 90.0, delta=0.01) + self.assertAlmostEqual(held["plane"], 0.0, delta=0.01) self.assertNotIn("NaN", json.dumps(held)) + def test_a_plane_seen_obliquely_decides_the_lens_and_says_it_is_a_plane(self): + """plane-honest: world points in one plane are solved, not refused: the plane's foreshortening decides the + lens (Zhang's calibration from a plane), "plane" says how far from square-on the view is, and auto leaves + the free model untried, since a plane never decides the centre. Seen within a pixel's noise of square-on + the marks decide no lens, and the record says so by its band rather than by a refusal: the headline lens + sits at an end of the range.""" + plane = np.c_[self.points[:, :2], np.zeros(13)] + world = dict(zip(NAMES, plane.tolist())) + solved = core.solve(world, dict(zip(NAMES, core.project(self.oblique, plane).tolist())), BOX) + self.assertAlmostEqual(solved["lens"], 50.0, delta=0.01) + self.assertAlmostEqual(solved["plane"], 70.0, delta=0.01) + self.assertEqual(sorted(solved["tried"]), ["rolled", "upright"]) + self.assertLess(place_error(solved, self.oblique), 1e-3) + self.assertIsNone(self.auto["plane"]) + noisy = core.project(camera(plane, 35, 90, 50), plane) + np.random.default_rng(5).normal(0, 1.0, (13, 2)) + open_ = core.solve(world, dict(zip(NAMES, noisy.tolist())), BOX, model="upright") + self.assertEqual((open_["lens_band"], open_["lens_at_bound"]), ([4.0, 4000.0], "short")) + self.assertLess(open_["plane"], 0.1) + self.assertNotIn("NaN", json.dumps(open_)) + + def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self): + """exact-gate: each of _decidable's four tests reads a ratio (the marks' thinnest extent over their widest, + or their misfit to a square-on copy of their plane) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused + and marks at 3.16e-9 pass: the geometric means of the shipped gate with a gate ten times tighter and ten + times looser, the least mutants claimed (separation 3.16 each side).""" + r = np.random.default_rng(7) + bump = r.normal(0, 1, 13) + plane = np.c_[self.points[:, :2], np.zeros(13)] + line = np.outer(np.linspace(-2, 2, 13), [1.0, 2.0, 0.5]) + across = np.cross([1.0, 2.0, 0.5], [0.0, 0.0, 1.0]) + flat_px, slope = np.c_[np.linspace(200, 900, 13), np.linspace(300, 500, 13)], np.array([-200.0, 700.0]) + turned = self.points[:, :2] @ np.array([[120.0, -90.0], [-90.0, -120.0]]) + [600.0, 400.0] # the plane's own picture, turned, scaled and v down + thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # noqa: E731 + misfit = lambda P: core._square_on(plane[:, :2] - plane[:, :2].mean(0), P) # noqa: E731 + sites = (("pixels lie on one line", lambda t: (self.points, flat_px + t * np.outer(bump, slope)), lambda W, P: thin(P), {}), + ("world points lie on one line", lambda t: (line + t * np.outer(bump, across), np.array(list(self.pixels.values()))), lambda W, P: (lambda s: s[1] / s[0])(np.linalg.svd(W - W.mean(0), compute_uv=False)), {}), + ("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"}), + ("seen square-on", lambda t: (plane, turned + t * np.c_[bump, bump[::-1]]), lambda W, P: misfit(P), {"model": "upright"})) + for said, make, reading, how in sites: + unit = reading(*make(1e-6)) / 1e-6 # the reading is the offset's size times this, the offset being small + for at, refused in ((3.16e-10, True), (3.16e-9, False)): + W, P = make(at / unit) + self.assertAlmostEqual(reading(W, P) / at, 1.0, delta=0.01, msg=said) + try: + core._decidable(NAMES, W, P, how.get("model", "auto"), False) + self.assertFalse(refused, f"{said}: marks at {at:g} passed") + except core.ReferenceFitError as refusal: + self.assertTrue(refused, f"{said}: marks at {at:g} were refused: {refusal}") + self.assertIn(said, str(refusal)) + 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.""" -- 2.47.3 From 727c55a99fa506ca34637a62c86ea886a43cf7fd Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:34:48 +0100 Subject: [PATCH 03/13] 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 --- surfaces/blender/tests/live/reference_lift.py | 209 ++++++++++++ .../tests/live/reference_lift.result.json | 318 ++++++++++++++++++ 2 files changed, 527 insertions(+) create mode 100644 surfaces/blender/tests/live/reference_lift.py create mode 100644 surfaces/blender/tests/live/reference_lift.result.json diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_lift.py new file mode 100644 index 0000000..2311622 --- /dev/null +++ b/surfaces/blender/tests/live/reference_lift.py @@ -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 -- + +Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses +without them). is an absolute path: it writes .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" 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) diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_lift.result.json new file mode 100644 index 0000000..5441113 --- /dev/null +++ b/surfaces/blender/tests/live/reference_lift.result.json @@ -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 +} \ No newline at end of file -- 2.47.3 From a25eb072180772077eb33961fb85557c2ab8f884 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 20:34:48 +0100 Subject: [PATCH 04/13] docs/reference.md: lift_pair, flow_score, and what a plane of marks decides Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/docs/reference.md | 103 ++++++++++++++++++++++++++--- 1 file changed, 94 insertions(+), 9 deletions(-) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 83e967f..176e463 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,4 +1,4 @@ -# Reference views: the camera a picture was drawn through +# Reference views: the camera a picture was drawn through, and lines lifted through it `surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the @@ -8,11 +8,11 @@ it lays over the image pixel for pixel and a line traced on the image can be lif It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the -one operator agents may run; the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +three operators agents may run (`solve_camera`, `lift_pair`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. -The package takes points and gives cameras. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras, creases and scores. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -29,7 +29,7 @@ made them; nothing here opens an image. The record is the truth. A Blender camera stood at it (`core.blender`) is derived, and `core.camera_of` reads one back into a record. -## The action +## solve_camera `brokkr_reference.solve_camera`. Host action fields are scalar, so points go in as text: @@ -72,9 +72,18 @@ object's name or null) and, when a camera was stood, `blender` (what `core.blend Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any solve: fewer than six different world points or six different pixels among the shared names (the message names two -that share one), pixels all on one line, world points all on one line, and world points all in one plane unless -`lens` is held and the model is `upright`, `rolled` or `square`. These are exact cases; points nearly in a line or -a plane are solved, and the band says what they leave open. A report never holds a number that is not finite. +that share one), pixels all on one line, world points all on one line, world points all in one plane with the +model `free`, and world points all in one plane seen exactly square-on with no `lens` held. These are exact cases, +to a billionth of the marks' extent (`core.EXACT`); points nearly in a line or a plane are solved, and the band +says what they leave open. A report never holds a number that is not finite. + +World points all in one plane (a deck, a wall, a flat sheet of marks) are solved, and `plane` in the report is then +the degrees between the line of sight and square-on to that plane (it is null otherwise). A plane may not decide +the lens. Seen obliquely it does, by its foreshortening: at 20 to 70 degrees off square-on with a pixel of marking +noise a 50 mm view came back at 48.7 to 49.9 mm. The nearer square-on, the less: at 10 degrees the band was 42 to +51 mm, and within a pixel's noise of square-on every lens fits, the band is 4 to 4000 and the headline lens sits at +an end of it. Read `plane` and the band together, and hold `lens` when the view is near square-on. A plane never +decides the centre, so `auto` tries `upright` and `rolled` only. ## How far to trust the lens @@ -107,6 +116,77 @@ place, not about a lift made in the view's own frame. pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model). +## lift_pair: a crease from two traced lines + +A line traced on the view is two numbers a point; a crease in the scene is three. `lift_pair` takes the third from +symmetry: two traced lines that are one crease and its mirror image, on a part symmetric about the x = 0 plane of +its frame. A point of one line and its mirror on the other 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. + +| field | | +| --- | --- | +| `camera_name` | the camera object the view is seen through; `solve_camera` stands one | +| `box` | `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 | +| `frame_name` | an object whose `matrix_world` is the part's frame; its x = 0 is the mirror plane | +| `line_a`, `line_b` | `u,v u,v ...`, the crease as traced on one side and its mirror image on the other | +| `samples` | points lifted, evenly along `line_a` (default 24) | +| `extend` | `line_b` is run on straight past its ends by this share of its length (default 0.2), to find mirrors for the ends of `line_a` | +| `curve_name` | a poly curve to create or update along the crease on `line_a`'s side, parented to the frame; absent draws none | + +The report: `crease` (`[[x, y, z], ...]` in the frame, x >= 0, in the order of `line_a`), `side` (+1 or -1: the side +of the frame `line_a` is on), `unmatched` (points of `line_a` whose line to the vanishing point never meets +`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `cage`, `miss` and +`curve`. The camera is read back from the object (`core.camera_of`): a perspective camera with a horizontal sensor +fit. The curve is for the eye; the report is the truth. + +Every lifted point draws back onto both traced lines exactly, so the drawing cannot tell two crossings apart. Where +a line folds back, the crease can: an ambiguous point takes the crossing whose lift stands nearest where its two +lifted neighbours run on to, the points with one crossing first. A high `ambiguous` count says a line is jagged or +folded and deserves a look. + +`cage` is the column of cage points whose hard crease, as Blender's Subdivision modifier builds it at one level, +passes through the lifted crease at the cage's own points (`core.cage_through`, `core.crease_run`). The built +crease is not the cage: with Limit Surface on (the modifier's default, and what kitbash shells use) a cage point is +built at (1, 4, 1) / 6 of itself and its neighbours along the column, the ends staying; a cage laid on the lifted +points would be built inside every bend. With Limit Surface off the weights differ and `cage` is not that +column. `miss` is the mean distance in pixels from where the camera draws that built crease to each traced line +(`line_b` run on by `extend`). + +How far to trust it: the lift is as sure as the frame and as the angle between the line of sight and the mirror +plane. Seen nearly along the mirror plane the two sight lines are nearly parallel, and a degree of the frame's turn +moves the crease a long way in depth. On twelve-point traces 1.5 px off, three views of a 2 m crease lifted within +0.6% of its length. On the Orchid's concept render (a hand trace of the upper petals' inboard edges, eight hand +marks, the frame fitted to a generated mesh's own mirror plane, 34 degrees between sight and mirror plane) the +lifted creases stood a mean 0.9% and 1.7% of the hull's length from that mesh, 4% at worst, at a petal's tip, and +moved 0.6% between the ends of the lens band. A wrong frame is not reported: the lift cannot see it. + +One traced line with no mirror is lifted onto a plane of the frame by `core.on_plane` (no action). + +## flow_score: traced lines against built edges + +`flow_score` says how much of each traced line the build already carries as an edge. It reads the evaluated meshes +(modifiers applied) and keeps the edges the camera sees: creases (two faces whose normals differ by more than +`angle` degrees, at least one of them facing the camera), contours (one face toward the camera, one away) and open +borders, each where two of three points along it are hidden behind nothing the scene shows. A face that looks away +by its winding does not count as seen, so a cage with flipped normals shows no creases. + +| field | | +| --- | --- | +| `camera_name`, `box` | as for `lift_pair` | +| `height` | the figure's height in the box's pixels; an edge within 1% of it is near. 0 (default) is the box's height | +| `lines` | `tag: u,v u,v ...; tag: u,v u,v ...` | +| `objects` | `name; name; ...`, the meshes whose edges are read; absent is every mesh the render shows. Everything the scene shows hides | +| `angle` | degrees (default 18) | + +The report: `lines` (`{tag: {on, off, run}}`), `edges` (the count of seen edges by kind), `objects` and `height`. +`on` is the share of the line with a seen edge within 1% of the height and within 20 degrees of the line's own +direction; `off` the mean distance to such an edge in % of the height, capped at 5; `run` the longest unbroken +share that is on. The edges themselves are not returned and not kept: they are computed on each call. + +The hiding test stops 0.03 scene units short of each point, a tolerance sized for builds metres across; on a +subject one unit long it is 3% of the subject. The action writes nothing to the scene (its row says `changesScene` +because the operator base pushes an undo step). + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -122,9 +202,14 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane +out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched +cage = core.cage_through(out["crease"]) # the column whose built crease passes through it +score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back ``` -The tests are `tests/test_reference.py` (no Blender) and `tests/live/reference.py` (a known scene rendered, -solved through the action and rendered again; `reference.result.json` is its last run). +The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved +through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_lift.py` +(`crease_run` against Blender's own subdivision, a crease lifted through `lift_pair`, a box and a folded sheet +scored by `flow_score`; `reference_lift.result.json` is its last run). -- 2.47.3 From a8518bfc520b109df2ba3618c185fa1e07732b2e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 21:23:40 +0100 Subject: [PATCH 05/13] brokkr_reference: a lens the marks leave open says so, the band runs to the first miss, pair refuses a repeated end point solve() no longer refuses a plane seen exactly square-on; that gate only moved the cliff one step off exact. The record carries planarity (the marks' least extent over their greatest) and lens_determined. The band is judged against no less than FINE pixels of error, runs out to the first lens that misses each way, and near a plane (planarity under PLANAR) a band open at one end of LENS_MM is the whole of LENS_MM. A sweep from square-on to 30 degrees off it pins the true lens inside the band at every tilt (mutants PL1, PL3, PL4, PL5). pair: a repeated first or last point of line b is a ReferenceFitError, not a LinAlgError. The forward pass has its own test (Mfwd), the N2 bound sits at the geometric mean of its readings, the hand-trace bound has a mutant (H1). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 5 +- surfaces/blender/brokkr_reference/core.py | 76 +++++------ surfaces/blender/tests/test_reference.py | 119 +++++++++++++----- 3 files changed, 129 insertions(+), 71 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 422b324..fd31f77 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -172,7 +172,10 @@ class BROKKR_REFERENCE_OT_lift_pair(PolishOperator): 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) + try: + out = core.pair(cam, F, a, b, n=self.samples, extend=self.extend) + except core.ReferenceFitError as refusal: + raise Refused(str(refusal)) from None 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"]) diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 4f28bb3..ee9819f 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -47,6 +47,9 @@ SENSOR = 36.0 # mm, fitted to the box's width LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md) BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best STEP = 0.1 # the band is walked in steps of this in log f +FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) +PLANAR = 0.1 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both +DECIDED = 1.5 # a lens is determined when its band is inside LENS_MM and spans no more than this factor MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -208,24 +211,12 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot): EXACT = 1e-9 # of the marks' extent: under this a set of marks is exactly degenerate (true lines and planes read 1e-16); marks placed by hand are never within 1e-3 -def _square_on(Q, P): - """How far pixels are from a turned and scaled copy of the points' own plane (Q, their two coordinates in it), - mirrored or not, as a share of the pixels' extent: nothing, when the plane is seen square-on.""" - b = (P - P.mean(0)).T.ravel() - miss = [] - for hand in (1.0, -1.0): - x, y = Q[:, 0], hand * Q[:, 1] - A = np.r_[np.c_[x, -y], np.c_[y, x]] - miss.append(np.linalg.norm(b - A @ np.linalg.lstsq(A, b, rcond=None)[0])) - return min(miss) / np.linalg.norm(b) - - -def _decidable(names, W, P, model, lens_held): +def _decidable(names, W, P, model): """Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of NaN). These are exact degeneracies, to EXACT of the marks' extent; points nearly in a line or a plane are - solved, and what they leave undecided is the band's to say. Returns the unit normal of the plane the world - points all lie in, or None.""" + solved, and what they leave undecided is the band's to say. Returns (the unit normal of the plane the world + points all lie in, or None; the marks' planarity: their least extent over their greatest, 0 for a plane).""" for what, A in (("world point", W), ("pixel", P)): first = {} twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None] @@ -237,13 +228,10 @@ def _decidable(names, W, P, model, lens_held): if w[1] <= EXACT * w[0]: raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it") if w[2] > EXACT * w[0]: - return None + return None, float(w[2] / w[0]) if model == "free": raise ReferenceFitError("the world points lie in one plane, which does not decide the centre: mark a point off the plane, or name a model other than free") - if not lens_held and _square_on((W - W.mean(0)) @ axes[:2].T, P) <= EXACT: - raise ReferenceFitError("the world points lie in one plane seen square-on, which may not decide the lens: every lens draws them so from its own distance. " - "Mark a point off the plane, or hold `lens`") - return axes[2] + return axes[2], float(w[2] / w[0]) def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)): @@ -259,23 +247,29 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where they were given. - Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that - refit within BAND of the best rms, walked out from the best in steps of STEP in log f, about 10%, to the first - that misses: an equal-error band, not a confidence interval, and no finer than its step, so [x, x] says the - band is narrower than one step each way, not that the lens is exact), + Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (walked out from the + best lens in steps of STEP in log f, about 10%, to the first lens each way whose refit misses BAND of the best + rms, or of FINE pixels where the marks fit closer than any hand places them: every lens outside it misses, + and its ends are the first that do, so it is an equal-error band no finer than its step, not a confidence + interval. Near a plane (planarity under PLANAR) a band that reaches one end of LENS_MM is the whole of + LENS_MM), "lens_determined" (True when the band is inside LENS_MM and spans no more than DECIDED times; + False when the marks leave the lens open, and the headline lens is then one of many that fit; None when + `lens` was held), "planarity" (the marks' least extent over their greatest: 0 for a plane), "lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median" (pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out, lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll", "twist" (degrees), "plane" (None, or when the world points all lie in one plane the degrees between the line of sight and square-on to it), "residuals" {name: [du, dv]}}. Every number in it is finite. - World points in one plane may not decide the lens: seen obliquely they do, by the plane's foreshortening; the - nearer square-on, the less, and the band says how little (a headline lens then sits anywhere in it, often at - an end of LENS_MM). The centre they never decide, so "auto" leaves "free" untried. + World points in or near one plane may not decide the lens: seen obliquely they do, by the plane's + foreshortening; the nearer square-on, the less, and "lens_determined" and the band say so (a headline lens + then sits anywhere in LENS_MM: a tilt of the plane seen through a long lens draws what a short lens draws + square-on, and the marks' error chooses between them). The centre a plane never decides, so "auto" leaves + "free" untried. Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or fewer than six different world points or different pixels among them; pixels on one line; world points on one - line; world points in one plane with the model "free", or seen exactly square-on with no `lens` held.""" + line; world points in one plane with the model "free".""" if model != "auto" and model not in MODELS: raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}") box = [float(v) for v in box] @@ -291,7 +285,7 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])): raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}") W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float) - normal = _decidable(names, W, P, model, lens is not None) + normal, planarity = _decidable(names, W, P, model) T = np.array([k in turned for k in names]) c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2] logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR)) @@ -303,27 +297,32 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0. kind = min(tried, key=lambda k: tried[k][5]) rms, p, cam, X, angle, left = tried[kind] mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end - span, best = [cam["f"]], math.log(cam["f"]) - for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound + walked, best = [(cam["f"], True)], math.log(cam["f"]) # (focal length, whether its refit is within the band) + for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1 while True: at = best + STEP * way * step f = math.exp(min(max(at, logf[0]), logf[1])) r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2] - if r_f > BAND * rms + 1e-9: - break - span.append(f) - if not logf[0] < at < logf[1]: + walked.append((f, r_f <= BAND * max(rms, FINE) + 1e-9)) + if not walked[-1][1] or not logf[0] < at < logf[1]: # marks with depth stop at the first miss; near a plane the error can come back under, so the walk runs to the bound break step += 1 + walked.sort() + within = [k for k, (_, ok) in enumerate(walked) if ok] + span = [walked[max(within[0] - 1, 0)][0], walked[min(within[-1] + 1, len(walked) - 1)][0]] # out to the first miss past each end: the band's end is somewhere in that step, and the band never leaves it out + if fixed is None and planarity < PLANAR and (math.log(walked[within[0]][0]) <= logf[0] + 1e-9 or math.log(walked[within[-1]][0]) >= logf[1] - 1e-9): + span = [math.exp(logf[0]), math.exp(logf[1])] # near a plane, a band open at one end is open at both: what closes the other is a tilt traded for the lens, which the marks' error sets either way off = cam["C"] - X.mean(0) res = project(cam, X) - P if not (math.isfinite(rms) and math.isfinite(left) and np.isfinite(cam["C"]).all() and np.isfinite(res).all()): raise ReferenceFitError("the solve did not come to finite numbers: the marks do not decide a camera") worst = int(np.argmax(np.linalg.norm(res, axis=1))) + band = [float(mm(span[0])), float(mm(span[1]))] edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]], - "box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge, + "box": box, "lens": float(mm(cam["f"])), "lens_band": band, "lens_at_bound": edge, "lens_determined": None if fixed is not None else bool(LENS_MM[0] < band[0] and band[1] < LENS_MM[1] and band[1] <= DECIDED * band[0]), + "planarity": planarity, "rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))], "left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()}, "azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))), @@ -393,10 +392,13 @@ def resampled(points, n): def extended(points, by): - """A polyline run on straight past both ends by `by` of its length.""" + """A polyline run on straight past both ends by `by` of its length. Refuses one whose first or last point is + given twice.""" 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] + if not (head.any() and tail.any()): + raise ReferenceFitError(f"a line to run on past its ends repeats its {'last' if head.any() else 'first'} point, so that end has no direction (line b of a pair is run on): drop the repeated point") return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length]) diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index b709b99..7075144 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -16,6 +16,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end G10, G01 core.EXACT ten times looser, ten tighter test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent + PL1, PL3, PL4, PL5 the band and lens_determined test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide """ from __future__ import annotations @@ -118,19 +119,20 @@ class SolveTests(unittest.TestCase): self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0) def test_the_band_is_an_equal_error_band(self): - """band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one - step past each end does not.""" + """band-is-equal-error: a build 4 cm off. Every lens inside the band refits within BAND of the best rms; the + band's ends are the first lenses that do not (PL4, a band that stops at the last lens that fits, has ends + that fit).""" world, pixels = marks(self.oblique, self.points, build=0.04) s = core.solve(world, pixels, BOX, model="upright") low, high = s["lens_band"] self.assertLess(low, s["lens"] * 0.95) self.assertGreater(high, s["lens"] * 1.05) - for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high): + for lens in (low * math.exp(core.STEP), math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high * math.exp(-core.STEP)): self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens) - for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)): + for lens in (low, high): self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens) held = core.solve(world, pixels, BOX, model="upright", lens=low) - self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None)) + self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"], held["lens_determined"]), (low, [low, low], None, None)) def test_the_band_is_walked_from_the_last_solve(self): """M3: each step of the walk is one solve started at the one before; restarting from the grid costs 16 per @@ -212,9 +214,8 @@ class SolveTests(unittest.TestCase): self.assertTrue(issubclass(core.ReferenceFitError, ValueError)) def test_marks_that_decide_no_camera_are_refused(self): - """refusals: marks with no extent or in a line, a plane asked for its centre and a plane seen square-on - with no lens held are refused by which they are before any solve (one pixel for every name was a bare - ValueError, one world point a record of NaN).""" + """refusals: marks with no extent or in a line and a plane asked for its centre are refused by which they + are before any solve (one pixel for every name was a bare ValueError, one world point a record of NaN).""" solved, lm = [], core.lm core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) self.addCleanup(setattr, core, "lm", lm) @@ -227,9 +228,7 @@ class SolveTests(unittest.TestCase): ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), ((line, self.pixels), {}, "world points lie on one line"), - (on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre"), - (square_on, {}, "seen square-on, which may not decide the lens"), (square_on, {"model": "upright"}, "may not decide the lens"), - (square_on, {"model": "square"}, "may not decide the lens")) + (on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) for args, kwargs, said in cases: with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, BOX, **kwargs) @@ -244,9 +243,7 @@ class SolveTests(unittest.TestCase): def test_a_plane_seen_obliquely_decides_the_lens_and_says_it_is_a_plane(self): """plane-honest: world points in one plane are solved, not refused: the plane's foreshortening decides the lens (Zhang's calibration from a plane), "plane" says how far from square-on the view is, and auto leaves - the free model untried, since a plane never decides the centre. Seen within a pixel's noise of square-on - the marks decide no lens, and the record says so by its band rather than by a refusal: the headline lens - sits at an end of the range.""" + the free model untried, since a plane never decides the centre.""" plane = np.c_[self.points[:, :2], np.zeros(13)] world = dict(zip(NAMES, plane.tolist())) solved = core.solve(world, dict(zip(NAMES, core.project(self.oblique, plane).tolist())), BOX) @@ -254,16 +251,43 @@ class SolveTests(unittest.TestCase): self.assertAlmostEqual(solved["plane"], 70.0, delta=0.01) self.assertEqual(sorted(solved["tried"]), ["rolled", "upright"]) self.assertLess(place_error(solved, self.oblique), 1e-3) + self.assertEqual((solved["planarity"], solved["lens_determined"]), (0.0, True)) self.assertIsNone(self.auto["plane"]) - noisy = core.project(camera(plane, 35, 90, 50), plane) + np.random.default_rng(5).normal(0, 1.0, (13, 2)) - open_ = core.solve(world, dict(zip(NAMES, noisy.tolist())), BOX, model="upright") - self.assertEqual((open_["lens_band"], open_["lens_at_bound"]), ([4.0, 4000.0], "short")) - self.assertLess(open_["plane"], 0.1) - self.assertNotIn("NaN", json.dumps(open_)) + self.assertGreater(self.auto["planarity"], core.PLANAR) + self.assertIs(self.auto["lens_determined"], True) + + def test_a_plane_tilted_from_square_on_never_reports_a_lens_it_does_not_decide(self): + """plane-sweep: a plane of thirteen marks seen through a 50 mm lens from square-on to 30 degrees off it, + each mark a pixel off (a second seed at 0 and 3 degrees), and from square-on and a hair off it with exact marks. At every tilt the + band holds 50 mm; where the lens is called determined the headline is within a quarter of 50 mm, and it is + never called determined within 3 degrees of square-on, where the headlines read 4 to 4000 mm; from 15 + degrees on it is. Truth tolerances, no bound a mutant claims by a reading; the mutants die by which + assertion: PL1 (a band open at one end stays closed at the other) at square-on, seed 0, band [309, 4000]; + PL3 (no FINE floor under the band's error) on the exact marks square-on, band [192, 2855]; PL4 (the band + stops at the last lens that fits) at 6 degrees, band [51, 69]; + PL5 (DECIDED 10) at 3 degrees, seed 0, 90 mm called determined.""" + plane = np.c_[self.points[:, :2], np.zeros(13)] + world = dict(zip(NAMES, plane.tolist())) + cases = [(tilt, 1.0, 0) for tilt in (0.0, 3.0, 6.0, 10.0, 15.0, 20.0, 30.0)] + [(0.0, 1.0, 1), (3.0, 1.0, 1), (0.0, 0.0, 0), (1e-5, 0.0, 0)] + for tilt, noise, seed in cases: + drawn = core.project(camera(plane, 35, 90.0 - tilt, 50), plane) + np.random.default_rng(seed).normal(0, noise, (13, 2)) + s = core.solve(world, dict(zip(NAMES, drawn.tolist())), BOX) + said = f"tilt {tilt:g}, noise {noise:g}, seed {seed}: lens {s['lens']:.0f}, band {s['lens_band']}, determined {s['lens_determined']}" + self.assertTrue(s["lens_band"][0] <= 50.0 <= s["lens_band"][1], said) + self.assertNotIn("NaN", json.dumps(s)) + if s["lens_determined"]: + self.assertAlmostEqual(math.log(s["lens"] / 50.0), 0.0, delta=math.log(1.25), msg=said) + self.assertAlmostEqual(s["plane"], tilt, delta=3.0, msg=said) + if tilt <= 3.0: + self.assertIs(s["lens_determined"], False, said) + if tilt < 1.0: + self.assertEqual(s["lens_band"], list(core.LENS_MM), said) + if tilt >= 15.0: + self.assertIs(s["lens_determined"], True, said) def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self): - """exact-gate: each of _decidable's four tests reads a ratio (the marks' thinnest extent over their widest, - or their misfit to a square-on copy of their plane) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused + """exact-gate: each of _decidable's three tests reads a ratio (the marks' thinnest extent over their + widest) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused and marks at 3.16e-9 pass: the geometric means of the shipped gate with a gate ten times tighter and ten times looser, the least mutants claimed (separation 3.16 each side).""" r = np.random.default_rng(7) @@ -272,20 +296,17 @@ class SolveTests(unittest.TestCase): line = np.outer(np.linspace(-2, 2, 13), [1.0, 2.0, 0.5]) across = np.cross([1.0, 2.0, 0.5], [0.0, 0.0, 1.0]) flat_px, slope = np.c_[np.linspace(200, 900, 13), np.linspace(300, 500, 13)], np.array([-200.0, 700.0]) - turned = self.points[:, :2] @ np.array([[120.0, -90.0], [-90.0, -120.0]]) + [600.0, 400.0] # the plane's own picture, turned, scaled and v down thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # noqa: E731 - misfit = lambda P: core._square_on(plane[:, :2] - plane[:, :2].mean(0), P) # noqa: E731 sites = (("pixels lie on one line", lambda t: (self.points, flat_px + t * np.outer(bump, slope)), lambda W, P: thin(P), {}), ("world points lie on one line", lambda t: (line + t * np.outer(bump, across), np.array(list(self.pixels.values()))), lambda W, P: (lambda s: s[1] / s[0])(np.linalg.svd(W - W.mean(0), compute_uv=False)), {}), - ("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"}), - ("seen square-on", lambda t: (plane, turned + t * np.c_[bump, bump[::-1]]), lambda W, P: misfit(P), {"model": "upright"})) + ("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"})) for said, make, reading, how in sites: unit = reading(*make(1e-6)) / 1e-6 # the reading is the offset's size times this, the offset being small for at, refused in ((3.16e-10, True), (3.16e-9, False)): W, P = make(at / unit) self.assertAlmostEqual(reading(W, P) / at, 1.0, delta=0.01, msg=said) try: - core._decidable(NAMES, W, P, how.get("model", "auto"), False) + core._decidable(NAMES, W, P, how.get("model", "auto")) self.assertFalse(refused, f"{said}: marks at {at:g} passed") except core.ReferenceFitError as refusal: self.assertTrue(refused, f"{said}: marks at {at:g} were refused: {refusal}") @@ -307,6 +328,8 @@ 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 + Mfwd, Mback the forward pass deleted, the backward test_a_fold_at_the_far_end_is_settled_by_the_forward_pass, the test above + H1 a crossing snapped to line b's point before it test_a_hand_traced_pair_lifts_within_a_bound 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 @@ -339,8 +362,10 @@ class LiftTests(unittest.TestCase): 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.""" + """pair-exact at 1.5 px, H1: twelve points a line, each 1.5 px off (a hand's trace). The worst of three views + reads 0.0122 m, 0.6% of the crease's 2.05 m; with each crossing snapped to the traced point before it + instead of taken where the lines cross (H1) 0.277 m. The bound is their geometric mean, separation 4.8 + each side.""" r = np.random.default_rng(11) worst = 0.0 for cam in self.cams: @@ -348,13 +373,13 @@ class LiftTests(unittest.TestCase): 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) + self.assertLess(worst, 0.058) 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.""" + `a` meet it twice or more. Shipped reads 8.9e-16 m off the true crease, the first crossing kept (N2) + 0.00892 m: the bound is their geometric mean, separation 3.2e6 each side. The backward pass settles these + (Mback leaves 7 of the 24 points unlifted).""" cam = self.cams[0] a, b = self.traced(cam)[100:], self.traced(cam, -1) d = b[600] - b[0] @@ -362,7 +387,35 @@ class LiftTests(unittest.TestCase): 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) + self.assertLess(self.off(out["crease"]), 2.8e-9) + + def test_a_fold_at_the_far_end_is_settled_by_the_forward_pass(self): + """pair-folded-line, Mfwd: line b's last two fifths are drawn three times over, out, back and out again beside + themselves, so the last points of `a` meet it more than once and have no lifted point after them. Shipped + reads 7.2e-16 m, the forward pass deleted (Mfwd) 0.0605 m and the first crossing kept (N2) 0.0302 m: the + bound is the geometric mean of the shipped reading and N2's, separation 6.5e6 each side. Seen at 10 + degrees of elevation the same fold is beyond the rule: docs/reference.md.""" + cam = self.cams[0] + b = self.traced(cam, -1) + v = b[-1] - b[1199] + d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * 0.06 * np.ptp(b, axis=0).max() + out = core.pair(cam, FRAME, self.traced(cam), np.vstack([b[:1199], b[1199:] + d, b[:1198:-1] + 2 * d, b[1199:]]), extend=0.0) + self.assertEqual((out["ambiguous"], out["unmatched"], len(out["crease"])), (10, 2, 22)) + self.assertLess(self.off(out["crease"]), 4.7e-9) + + def test_a_line_that_repeats_an_end_point_is_refused(self): + """A doubled click at an end of line b leaves that end no direction to run on in: refused by name (it was a + LinAlgError out of the triangulation). A repeat inside either line, or at an end of line a, is harmless.""" + cam = self.cams[0] + a, b = self.traced(cam), self.traced(cam, -1) + for line, which, extend in ((np.vstack([b[:1], b]), "first", 0.2), (np.vstack([b, b[-1:]]), "last", 0.2), (np.vstack([b[:1], b]), "first", 0.0)): + with self.assertRaises(core.ReferenceFitError) as caught: + core.pair(cam, FRAME, a, line, extend=extend) + self.assertIn(f"repeats its {which} point", str(caught.exception)) + for one, other in ((np.vstack([a[:1], a]), b), (a, np.vstack([b[:500], b[500:501], b[500:]]))): + out = core.pair(cam, FRAME, one, other) + self.assertEqual(len(out["crease"]), 24) + self.assertLess(self.off(out["crease"]), 1e-6) def test_a_line_with_no_mirror_is_counted_unmatched(self): cam = self.cams[0] -- 2.47.3 From 7183ae41a0f5c79271dd64645d1b645cca4fb694 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 21:26:24 +0100 Subject: [PATCH 06/13] brokkr_reference.flow_score: the hiding margin is a share of the build's diagonal, with a live case an occluder decides built_edges stopped each sight line 0.03 scene units short of the edge, so a surface within 0.03 units never hid one, whatever the scale. It stops HIDE (1e-3) of the diagonal of the meshes read short. tests/live/reference_lift.py sees a box's front edge, then hides it behind a strip 0.316% of the diagonal in front, at scales 0.01, 1 and 100 (mutants O1, O2, O3, O4 die; O5 unclaimed), and lift_pair's refusal of a repeated end point is a failed receipt. docs/reference.md: lens_determined, planarity, the band to its first miss, the fold rule's measured limit. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 13 ++- surfaces/blender/docs/reference.md | 75 +++++++++---- surfaces/blender/tests/live/reference_lift.py | 50 ++++++++- .../tests/live/reference_lift.result.json | 100 +++++++++++++++++- 4 files changed, 206 insertions(+), 32 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index fd31f77..b6f3c8a 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -98,13 +98,20 @@ def record(context, name, box): core.numbers(box, 4, "box") if box.strip() else None) +HIDE = 1e-3 # of the diagonal of the meshes read: a sight line stops this short of an edge, so that the edge's own faces do not hide it; a surface nearer the edge than this does not either + + 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.""" + away) and open borders, each kept where two of three points along it are hidden behind nothing: a ray from the + camera toward the point meets no surface before it stops HIDE of the build's diagonal short of it, the same + share at any scale. `objects` are the meshes read, and the build whose diagonal that is; 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)) + corners = np.array([obj.matrix_world @ Vector(corner) for obj in objects for corner in obj.evaluated_get(dg).bound_box]).reshape(-1, 3) + short = HIDE * float(np.linalg.norm(np.ptp(corners, axis=0))) if len(corners) else 0.0 for obj in objects: ev = obj.evaluated_get(dg) me = ev.to_mesh() @@ -139,7 +146,7 @@ def built_edges(context, cam, objects, angle): 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] + clear += not scene.ray_cast(dg, Vector(eye), Vector((p - eye) / d), distance=d - short)[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)]) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 176e463..74d975b 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -63,7 +63,7 @@ proportion. It does not make it the scene's active camera and does not touch `re render through it at 100% is then the image's pixel less the box's corner, times `width` over the box's width (`core.in_frame`; the frame's height is a whole number of pixels, so it can stand half a pixel off the box's). -The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `rms`, `median` +The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `lens_determined`, `planarity`, `plane`, `rms`, `median` and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tried` (each model's `rms`, `left_out` and `lens`), `azimuth`, `elevation` and `distance` (where the camera stands round the points' middle), `roll`, `twist`, and `residuals` (`{name: [du, dv]}`, to a hundredth of a pixel in a receipt); plus `camera` (the @@ -72,18 +72,33 @@ object's name or null) and, when a camera was stood, `blender` (what `core.blend Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any solve: fewer than six different world points or six different pixels among the shared names (the message names two -that share one), pixels all on one line, world points all on one line, world points all in one plane with the -model `free`, and world points all in one plane seen exactly square-on with no `lens` held. These are exact cases, -to a billionth of the marks' extent (`core.EXACT`); points nearly in a line or a plane are solved, and the band -says what they leave open. A report never holds a number that is not finite. +that share one), pixels all on one line, world points all on one line, and world points all in one plane with the +model `free`. These are exact cases, to a billionth of the marks' extent (`core.EXACT`); points nearly in a line or +a plane are solved, and `lens_determined` and the band say what they leave open. A report never holds a number +that is not finite. -World points all in one plane (a deck, a wall, a flat sheet of marks) are solved, and `plane` in the report is then -the degrees between the line of sight and square-on to that plane (it is null otherwise). A plane may not decide -the lens. Seen obliquely it does, by its foreshortening: at 20 to 70 degrees off square-on with a pixel of marking -noise a 50 mm view came back at 48.7 to 49.9 mm. The nearer square-on, the less: at 10 degrees the band was 42 to -51 mm, and within a pixel's noise of square-on every lens fits, the band is 4 to 4000 and the headline lens sits at -an end of it. Read `plane` and the band together, and hold `lens` when the view is near square-on. A plane never -decides the centre, so `auto` tries `upright` and `rolled` only. +`planarity` is how flat the marked world points are: their least extent over their greatest, 0 for a plane, 0.3 +for points spread through a box. World points all in one plane (a deck, a wall, a flat sheet of marks) are solved, +and `plane` is then the degrees between the line of sight and square-on to that plane (it is null otherwise). A +plane never decides the centre, so `auto` tries `upright` and `rolled` only. + +Flat marks may not decide the lens, and `lens_determined` says whether these did. Seen obliquely a plane does, by +its foreshortening. Seen square-on it does not: every lens draws it the same from its own distance, and a small +tilt of the plane seen through a long lens draws what a short lens draws square-on, so the marks' error picks the +headline lens. Measured on a plane of thirteen marks through a 50 mm lens, each mark a pixel off, six seeds a tilt: + +| degrees off square-on | headline lens, mm | band, mm | `lens_determined` | +| --- | --- | --- | --- | +| 0 | 4 to 4000 | 4 to 4000 | false, all six | +| 3 | 4 to 90 | 4 to 4000 (one 45 to 134) | false, all six | +| 6 | 42 to 62 | from 13 to 84, one 4 to 4000 | false, all six | +| 9 | 46 to 57 | from 35 to 69 | true in five | +| 15 | 48 to 53 | from 44 to 59 | true, all six | +| 30 | 49 to 51 | from 45 to 57 | true, all six | + +The band held 50 mm in all 36. With marks 3 px off, one band of nine at 5 degrees did not (68 to 152, not +determined). When `lens_determined` is false, do not read `lens` as the lens: hold `lens` from another view, or mark +a point off the plane. ## How far to trust the lens @@ -94,13 +109,21 @@ and focal length trade against each other (a dolly zoom) and the picture barely - The focal length is held inside 4 to 4000 mm. Without a bound the solve ran the focal length to overflow on long views; past 4000 mm a view is orthographic to any marking. `lens_at_bound` is `"long"` or `"short"` when the answer sits at an end: read that as "at least this long", not as a lens. -- `lens_band` is `[low, high]`: the lenses that, held and refitted, come within 1.1 times the best rms, walked out - from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error - band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens - lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound. - The walk's step is the band's resolution: each end is the last step that still fitted, so the true end lies up - to one step (about 10%) further out, and a band of `[x, x]` means the first step each way already missed, that - is, a band narrower than one 10% step each way, not a lens known exactly. +- `lens_band` is `[low, high]`, walked out from the best lens in steps of a tenth in log f (about 10%) to the first + lens each way that, held and refitted, misses 1.1 times the best rms. Every lens outside the band misses; each + end is the first step that did, so the lenses that fit end somewhere in the step before it, and a band is never + narrower than a step each way. The rms the walk is judged against is never taken under 1 pixel (`core.FINE`): + marks placed truer than a hand places them fit every lens of a flat view to a millionth of a pixel, and one of + those would be called best. It is an **equal-error band, not a confidence interval**: it says which lenses the + marks cannot tell apart, and on probes a few such bands excluded the true lens. A band that ends at 4000 or at 4 + was stopped by the bound. +- For flat marks (`planarity` under 0.1, `core.PLANAR`) a band that reaches one end of the range is reported as + the whole range, 4 to 4000. What closes the other end of such a band is a tilt of the plane traded against the + lens, and the marks' error sets that either way: a square-on plane's band read 309 to 4000 mm on one seed with + the true lens at 50. This gives up the one-sided reading ("at least 300 mm") for flat marks; marks with depth + keep it. +- `lens_determined` is true when the band lies inside 4 to 4000 mm and spans no more than 1.5 times + (`core.DECIDED`), false otherwise, and null when `lens` was held. - There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm. - Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix. @@ -141,8 +164,12 @@ fit. The curve is for the eye; the report is the truth. Every lifted point draws back onto both traced lines exactly, so the drawing cannot tell two crossings apart. Where a line folds back, the crease can: an ambiguous point takes the crossing whose lift stands nearest where its two -lifted neighbours run on to, the points with one crossing first. A high `ambiguous` count says a line is jagged or -folded and deserves a look. +lifted neighbours run on to, the points with one crossing first, along the line and then back along it. A high +`ambiguous` count says a line is jagged or folded and deserves a look: the rule is a heuristic. On 189 strokes of +`line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three views) it lifted 174 exactly +and 15 off by 1 to 10% of the crease's length, all 15 on the view 10 degrees above the crease, each with 9 to 20 +ambiguous points and no other sign. A line whose first or last point is given twice is refused: that end of +`line_b` has no direction to run on in. `cage` is the column of cage points whose hard crease, as Blender's Subdivision modifier builds it at one level, passes through the lifted crease at the cage's own points (`core.cage_through`, `core.crease_run`). The built @@ -183,8 +210,10 @@ The report: `lines` (`{tag: {on, off, run}}`), `edges` (the count of seen edges direction; `off` the mean distance to such an edge in % of the height, capped at 5; `run` the longest unbroken share that is on. The edges themselves are not returned and not kept: they are computed on each call. -The hiding test stops 0.03 scene units short of each point, a tolerance sized for builds metres across; on a -subject one unit long it is 3% of the subject. The action writes nothing to the scene (its row says `changesScene` +The hiding test's sight line stops short of each point by a thousandth of the diagonal of the meshes read +(`HIDE`), so that the edge's own faces do not hide it; a surface nearer an edge than that does not hide it either. +It is the same share at any scale: a strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, +1 and 100. The action writes nothing to the scene (its row says `changesScene` because the operator base pushes an undo step). ## What it cannot do diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_lift.py index 2311622..2bac59c 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_lift.py @@ -5,9 +5,14 @@ core.crease_run against Blender's own subdivision. 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) + flow_score a box and, beside it, a folded sheet seen from behind: the box's front edge scores 1, its back edge 0 + (it faces away, so it is never read), 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). Then the box alone at + scales 0.01, 1 and 100, its front edge seen, and hidden by a strip standing in front of it by + 0.316% of the box's diagonal (mutants O1, nothing hides; O2, a margin of 0.03 units; O3, HIDE ten + times over: each reads the hidden edge as seen. O4, no margin at all, loses seen edges to their + own faces here and at the first box. O5, HIDE at 1e-6, passes every check: unclaimed, the margin's + floor is the ray's own rounding, which this fixture does not reach) blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- @@ -16,6 +21,7 @@ without them). is an absolute path: it writes .result.json and exits of the unittest run: it needs Blender. """ import json +import math import os import sys import tempfile @@ -160,7 +166,8 @@ try: 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")): + ({"curve_name": "Truth"}, "not a curve"), ({"line_b": "5000,5000 5010,5000"}, "no mirror"), + ({"line_b": " ".join(traced(truth, world(-1)).split()[:1] * 2 + traced(truth, world(-1)).split()[1:])}, "repeats its first point")): 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"]) @@ -191,7 +198,7 @@ try: 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 box's back edge, both its faces turned away, is not read: 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", @@ -199,6 +206,39 @@ try: 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"]) + + # --- flow_score: an edge the camera would see, hidden by a nearer surface, at three scales ------------------------ + for s in (0.01, 1.0, 100.0): + for obj in [o for o in bpy.data.objects if o.type in ("MESH", "CURVE")]: + bpy.data.objects.remove(obj) + scaled = bpy.data.objects.new(f"Scaled {s:g}", bpy.data.cameras.new(f"Scaled {s:g}")) + scene.collection.objects.link(scaled) + scaled.data.lens, scaled.data.sensor_width, scaled.data.sensor_fit, scaled.data.clip_start, scaled.data.clip_end = 50.0, 36.0, "HORIZONTAL", 0.01 * s, 1000.0 * s + scaled.matrix_world = Matrix.Translation(truth.matrix_world.translation * s) @ truth.matrix_world.to_3x3().to_4x4() + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=2.0 * s, matrix=Matrix.Translation((0.0, 0.0, s))) + mesh = bpy.data.meshes.new("Box") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Box", mesh)) + bpy.context.view_layer.update() + edge = np.array([(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)]) * s + line = f"front: {traced(scaled, edge)}" + receipt, bare = send("brokkr_reference.flow_score", camera_name=scaled.name, lines=line, objects="Box") + # a strip standing along the edge, toward the camera from it: every sight line to the edge meets it `gap` before the edge + toward = np.array(scaled.matrix_world.translation) - edge.mean(0) + toward /= np.linalg.norm(toward) + level = np.array([toward[0], toward[1], 0.0]) / np.hypot(toward[0], toward[1]) + side = np.cross([0.0, 0.0, 1.0], level) + gap = 3.16e-3 * 2.0 * s * math.sqrt(3.0) # of the box's diagonal: the geometric mean of the shipped HIDE, 1e-3, and one ten times it (mutant O3), 3.16 from each + at = edge.mean(0) + level * gap * float(toward @ level) + mesh_object("Wall", [tuple(at + side * a * 0.2 * s + np.array([0.0, 0.0, b * 1.5 * s])) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))], [(0, 1, 2, 3)]) + bpy.context.view_layer.update() + receipt2, walled = send("brokkr_reference.flow_score", camera_name=scaled.name, lines=line, objects="Box") + check(f"at scale {s:g} the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), " + "O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + receipt["status"] == "accepted" and receipt2["status"] == "accepted" and bare["lines"]["front"]["on"] == 1.0 and bare["edges"]["crease"] == 3 + and walled["lines"]["front"]["on"] == 0.0 and walled["edges"]["crease"] == 2, [bare and bare["lines"], bare and bare["edges"], walled and walled["lines"], walled and walled["edges"], gap]) 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:]) diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_lift.result.json index 5441113..6e8baf8 100644 --- a/surfaces/blender/tests/live/reference_lift.result.json +++ b/surfaces/blender/tests/live/reference_lift.result.json @@ -79,6 +79,11 @@ "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": "lift_pair refuses line_b: failed, saying 'repeats its first point'", + "ok": true, + "detail": "Error: a line to run on past its ends repeats its first point, so that end has no direction (line b of a pair is run on): drop the repeated point" + }, { "name": "fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so", "ok": true, @@ -134,7 +139,7 @@ } }, { - "name": "the box's hidden back edge scores on 0", + "name": "the box's back edge, both its faces turned away, is not read: on 0", "ok": true, "detail": { "on": 0.0, @@ -210,6 +215,99 @@ "name": "flow_score refuses camera_name: failed, saying 'not a camera'", "ok": true, "detail": "Error: 'Box' is not a camera object." + }, + { + "name": "at scale 0.01 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + { + "front": { + "on": 1.0, + "off": 0.0, + "run": 1.0 + } + }, + { + "crease": 3, + "contour": 6, + "border": 0 + }, + { + "front": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + { + "crease": 2, + "contour": 6, + "border": 0 + }, + 0.00010946561103835305 + ] + }, + { + "name": "at scale 1 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + { + "front": { + "on": 1.0, + "off": 0.0, + "run": 1.0 + } + }, + { + "crease": 3, + "contour": 6, + "border": 0 + }, + { + "front": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + { + "crease": 2, + "contour": 6, + "border": 0 + }, + 0.010946561103835304 + ] + }, + { + "name": "at scale 100 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", + "ok": true, + "detail": [ + { + "front": { + "on": 1.0, + "off": 0.0, + "run": 1.0 + } + }, + { + "crease": 3, + "contour": 6, + "border": 0 + }, + { + "front": { + "on": 0.0, + "off": 5.0, + "run": 0.0 + } + }, + { + "crease": 2, + "contour": 6, + "border": 0 + }, + 1.0946561103835304 + ] } ], "hostErrors": [], -- 2.47.3 From 1c0f0e6d2e724c454162c8c1906aa971fea8a215 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:34:06 +0100 Subject: [PATCH 07/13] brokkr_reference.pair: crossings chosen together by least total turn, a kink at a chosen crossing refused; DECIDED and PLANAR between readings The two-pass chain is gone: _smoothest picks one crossing per point by dynamic programming over neighbouring choices. On Soul's 189 doubled-back strokes the chain lifted 15 wrong (0.018 to 0.21 m); now 174 lift exactly and 15 are refused, none wrong. The 15 have a point whose true crossing is not among its crossings; kink reads 7.7 to 66 on them, at most 1.245 on the 174, KINK 3.1. On hand-traced folds the refusal is blunt (20 to 50% of unharmed lifts): docs. DECIDED 1.57 and PLANAR 0.057 sit at geometric means, with mutants. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/core.py | 72 +++++++++++++++------ surfaces/blender/docs/reference.md | 40 ++++++++---- surfaces/blender/tests/test_reference.py | 79 ++++++++++++++++++++--- 3 files changed, 146 insertions(+), 45 deletions(-) diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index ee9819f..49e8818 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -48,8 +48,9 @@ LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a vi BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best STEP = 0.1 # the band is walked in steps of this in log f FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) -PLANAR = 0.1 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both -DECIDED = 1.5 # a lens is determined when its band is inside LENS_MM and spans no more than this factor +PLANAR = 0.057 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.009, a panel with relief whose band does open at one end, and 0.36, marks with depth (tests/test_reference.py) +KINK = 3.1 # pair refuses a lift whose worst turn at a chosen crossing is more than this many times the crease's median turn (tests/test_reference.py holds the readings either side) +DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65) MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -402,6 +403,40 @@ def extended(points, by): return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length]) +def _bend(X0, X1, X2): + """The turn, in radians, of a crease that runs X0, X1, X2; a half turn where it stands still.""" + u, v = X1 - X0, X2 - X1 + along = np.linalg.norm(u) * np.linalg.norm(v) + return float(np.arccos(np.clip(u @ v / along, -1, 1))) if along > 1e-24 else math.pi + + +def _smoothest(candidates): + """One candidate per point, chosen together: the choice whose curve turns least in all (the sum of _bend over + every three points in a row), found by dynamic programming over pairs of neighbouring choices, so no point is + settled before the points after it are read. Returns the index taken at each point; ties go to the earlier + candidate.""" + m = len(candidates) + if m < 3: + return [0] * m + cost = {(j, k): 0.0 for j in range(len(candidates[0])) for k in range(len(candidates[1]))} + back = [] + for t in range(2, m): + new, via = {}, {} + for (h, j), c in cost.items(): + for k, X in enumerate(candidates[t]): + total = c + _bend(candidates[t - 2][h], candidates[t - 1][j], X) + if (j, k) not in new or total < new[j, k]: + new[j, k], via[j, k] = total, h + cost = new + back.append(via) + j, k = min(cost, key=lambda s: (cost[s], s)) + taken = [k, j] + for via in reversed(back): + j, k = via[j, k], j + taken.append(j) + return taken[::-1] + + 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 @@ -411,10 +446,13 @@ def pair(cam, frame, a, b, n=24, extend=0.2): 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`. + "ambiguous": points whose line meets `b` more than once; "kink": the worst turn (_bend) at a point that had + a crossing to choose, over the crease's median turn}. 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: the crossings are + chosen together, as the choice whose crease turns least in all (_smoothest). That is the true crease wherever + every point's true crossing is among its crossings. Where one is not (the end of `a` mirrors the very end of + `b`, and only the doubled strokes are met) the smoothest crease still kinks there, and a kink over KINK is + refused. 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.""" @@ -434,23 +472,15 @@ def pair(cam, frame, a, b, n=24, extend=0.2): 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] + at = [i for i, lifts in enumerate(found) if lifts] + lifted = [found[i][k] for i, k in zip(at, _smoothest([[fold(X) for X in found[i]] for i in at]))] + bends = [(_bend(fold(lifted[t - 2]), fold(lifted[t - 1]), fold(lifted[t])), any(len(found[i]) > 1 for i in at[t - 2:t + 1])) for t in range(2, len(at))] + kink = max((bend for bend, chose in bends if chose), default=0.0) / max(float(np.median([bend for bend, _ in bends])), 1e-12) if bends else 0.0 + if kink > KINK: + raise ReferenceFitError(f"line b doubles back and the smoothest crease through its crossings still turns {kink:.1f} times its usual turn where a crossing was chosen (over {KINK} is refused): a point of line a has no true mirror among its crossings, most often at an end. Draw line b as one stroke that does not run beside itself") 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)} + "ambiguous": sum(1 for lifts in found if len(lifts) > 1), "kink": float(kink), "unmatched": sum(1 for lifts in found if not lifts)} def on_plane(cam, frame, line, point, normal, n=24): diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 74d975b..d18a741 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -117,12 +117,12 @@ and focal length trade against each other (a dolly zoom) and the picture barely those would be called best. It is an **equal-error band, not a confidence interval**: it says which lenses the marks cannot tell apart, and on probes a few such bands excluded the true lens. A band that ends at 4000 or at 4 was stopped by the bound. -- For flat marks (`planarity` under 0.1, `core.PLANAR`) a band that reaches one end of the range is reported as +- For flat marks (`planarity` under 0.057, `core.PLANAR`) a band that reaches one end of the range is reported as the whole range, 4 to 4000. What closes the other end of such a band is a tilt of the plane traded against the lens, and the marks' error sets that either way: a square-on plane's band read 309 to 4000 mm on one seed with the true lens at 50. This gives up the one-sided reading ("at least 300 mm") for flat marks; marks with depth keep it. -- `lens_determined` is true when the band lies inside 4 to 4000 mm and spans no more than 1.5 times +- `lens_determined` is true when the band lies inside 4 to 4000 mm and spans no more than 1.57 times (`core.DECIDED`), false otherwise, and null when `lens` was held. - There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm. - Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their @@ -158,17 +158,26 @@ x axis; the pair is triangulated as one point seen by the camera and by the came The report: `crease` (`[[x, y, z], ...]` in the frame, x >= 0, in the order of `line_a`), `side` (+1 or -1: the side of the frame `line_a` is on), `unmatched` (points of `line_a` whose line to the vanishing point never meets -`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `cage`, `miss` and +`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `kink`, `cage`, `miss` and `curve`. The camera is read back from the object (`core.camera_of`): a perspective camera with a horizontal sensor fit. The curve is for the eye; the report is the truth. Every lifted point draws back onto both traced lines exactly, so the drawing cannot tell two crossings apart. Where -a line folds back, the crease can: an ambiguous point takes the crossing whose lift stands nearest where its two -lifted neighbours run on to, the points with one crossing first, along the line and then back along it. A high -`ambiguous` count says a line is jagged or folded and deserves a look: the rule is a heuristic. On 189 strokes of -`line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three views) it lifted 174 exactly -and 15 off by 1 to 10% of the crease's length, all 15 on the view 10 degrees above the crease, each with 9 to 20 -ambiguous points and no other sign. A line whose first or last point is given twice is refused: that end of +a line folds back, the crease can: the crossings of all the points are chosen together, as the choice whose lifted +crease turns least in all (the sum of its turns at each point, by dynamic programming), so no point is settled +before the points after it are read. Wherever each point's true crossing is among its crossings, that is the true +crease. Where it is not (most often the last point of `line_a`, whose mirror is the very end of `line_b`, meeting +only the doubled strokes) the smoothest crease still kinks at that point. `kink` is the worst turn at a point that +had a choice, over the crease's median turn, and a lift whose `kink` is over 3.1 (`core.KINK`) is refused: draw +`line_b` as one stroke. + +On 189 exact strokes of `line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three +views) 174 lift exactly, with `kink` at most 1.25, and 15 are refused, `kink` 7.7 to 66, all on the view 10 degrees +above the crease; none lifts wrong. On hand-traced lines the refusal is blunt: with the same folds drawn on +twelve-point traces 0.5 and 1.5 px off, it refuses 20% and 50% of the lifts the fold did not harm (108 of 540, 264 +of 533), and passes none of 27 and 3 of 34 that it did, the three within 1.8 cm of the unfolded lift. A trace's own wobble turns the crease as +much as a wrong crossing does, and no reading of the lift tells them apart. A lift with no ambiguous +point has no choice anywhere and is never refused. A line whose first or last point is given twice is refused: that end of `line_b` has no direction to run on in. `cage` is the column of cage points whose hard crease, as Blender's Subdivision modifier builds it at one level, @@ -210,10 +219,13 @@ The report: `lines` (`{tag: {on, off, run}}`), `edges` (the count of seen edges direction; `off` the mean distance to such an edge in % of the height, capped at 5; `run` the longest unbroken share that is on. The edges themselves are not returned and not kept: they are computed on each call. -The hiding test's sight line stops short of each point by a thousandth of the diagonal of the meshes read -(`HIDE`), so that the edge's own faces do not hide it; a surface nearer an edge than that does not hide it either. -It is the same share at any scale: a strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, -1 and 100. The action writes nothing to the scene (its row says `changesScene` +The hiding test's sight line stops short of each point by a thousandth (`HIDE`) of the diagonal of the edge's own +object, so that the edge's own faces do not hide it. A surface of another object nearer the edge than that hides +it when it stands further off than a thousandth of its own diagonal: the margin is the smaller of the two objects', +whatever else the scene holds. A strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, 1 and +100, and with a ground 20 or 40 times the box among the meshes read; chips a fortieth of a box hide its edge from +0.05% of its diagonal. Past the own object's margin the first surface met decides. Edges read true from cameras to +about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene` because the operator base pushes an undo step). ## What it cannot do @@ -231,7 +243,7 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane -out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched +out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched, kink cage = core.cage_through(out["crease"]) # the column whose built crease passes through it score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 7075144..e333c45 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -285,6 +285,31 @@ class SolveTests(unittest.TestCase): if tilt >= 15.0: self.assertIs(s["lens_determined"], True, said) + def test_determined_and_planar_sit_between_readings_either_side(self): + """lens_determined's two thresholds, each between two readings (lodur:ruling:deterministic-bound-margin). + DECIDED: a band spans a whole number of STEPs, so the readings are discrete. Marks with depth seen through + 85 mm, 3 px off, read a band of four steps, 1.4918 times, the widest of 48 such solves, and are called + determined; the same marks 5 px off read five steps, 1.6487, and are not. DECIDED 1.57 is the geometric + mean, 1.05 from each: the readings are one step apart, 1.105, under the ruling's 1.2, and no nearer pair + exists. Mutants DECIDED 1.4 and 1.7 die here by which call flips; 2.5 too. PLANAR: a panel with relief + (planarity 0.009) seen square-on reads a band open at 4000 mm and so is reported open at both ends; marks + with depth read 0.36. PLANAR 0.057 is the geometric mean, 6.3 from each: PLANAR 0.001 and 0.008 leave the + panel's band at [38.6, 4000] and die here, PLANAR 1.0 dies at the oblique view. Unclaimed, no reading + between: mutants from 0.009 to 0.36 (0.03 and 0.3 pass every test); panels of planarity 0.03 and 0.06 + read closed bands 1.5 to 4 times wide, where PLANAR does nothing.""" + for noise, span, determined in ((3.0, 1.4918, True), (5.0, 1.6487, False)): + drawn = core.project(camera(self.points, 35, 20, 85), self.points) + np.random.default_rng(3).normal(0, noise, (13, 2)) + s = core.solve(dict(zip(NAMES, self.points.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) + self.assertAlmostEqual(s["lens_band"][1] / s["lens_band"][0], span, delta=1e-3) + self.assertIs(s["lens_determined"], determined) + self.assertAlmostEqual(s["planarity"], 0.3615, delta=1e-3) + relief = np.random.default_rng(77).uniform(-1, 1, 13) + panel = np.c_[self.points[:, :2], relief / np.ptp(relief) * 0.01 * np.ptp(self.points[:, :2], axis=0).max()] + drawn = core.project(camera(panel, 35, 90.0, 50), panel) + np.random.default_rng(0).normal(0, 1.0, (13, 2)) + s = core.solve(dict(zip(NAMES, panel.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) + self.assertAlmostEqual(s["planarity"], 0.009, delta=5e-4) + self.assertEqual((s["lens_band"], s["lens_determined"]), (list(core.LENS_MM), False)) + def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self): """exact-gate: each of _decidable's three tests reads a ratio (the marks' thinnest extent over their widest) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused @@ -327,8 +352,11 @@ VIEWS = ((35, 20, 50), (-60, 40, 85), (150, 10, 35)) 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 - Mfwd, Mback the forward pass deleted, the backward test_a_fold_at_the_far_end_is_settled_by_the_forward_pass, the test above + N2 the first crossing kept test_a_folded_line_takes_the_smoothest_crossing, and the two after it + G1 each crossing chosen as it is reached (greedy) test_strokes_doubled_back_lift_exactly_or_are_refused + K1 no refusal; K2, K3 KINK 1.2 and 8 the same + Unclaimed: S1, a crease that stands still costs no turn (_bend's half turn read as 0), passes every test: no + fixture lifts two points to one place. H1 a crossing snapped to line b's point before it test_a_hand_traced_pair_lifts_within_a_bound 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 @@ -375,11 +403,10 @@ class LiftTests(unittest.TestCase): worst = max(worst, self.off(out["crease"])) self.assertLess(worst, 0.058) - def test_a_folded_line_takes_the_crossing_its_neighbours_agree_with(self): + def test_a_folded_line_takes_the_smoothest_crossing(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 8.9e-16 m off the true crease, the first crossing kept (N2) - 0.00892 m: the bound is their geometric mean, separation 3.2e6 each side. The backward pass settles these - (Mback leaves 7 of the 24 points unlifted).""" + 0.00892 m: the bound is their geometric mean, separation 3.2e6 each side.""" cam = self.cams[0] a, b = self.traced(cam)[100:], self.traced(cam, -1) d = b[600] - b[0] @@ -389,12 +416,11 @@ class LiftTests(unittest.TestCase): self.assertEqual((out["unmatched"], len(out["crease"])), (0, 24)) self.assertLess(self.off(out["crease"]), 2.8e-9) - def test_a_fold_at_the_far_end_is_settled_by_the_forward_pass(self): - """pair-folded-line, Mfwd: line b's last two fifths are drawn three times over, out, back and out again beside + def test_a_fold_at_the_far_end_is_settled(self): + """pair-folded-line: line b's last two fifths are drawn three times over, out, back and out again beside themselves, so the last points of `a` meet it more than once and have no lifted point after them. Shipped - reads 7.2e-16 m, the forward pass deleted (Mfwd) 0.0605 m and the first crossing kept (N2) 0.0302 m: the - bound is the geometric mean of the shipped reading and N2's, separation 6.5e6 each side. Seen at 10 - degrees of elevation the same fold is beyond the rule: docs/reference.md.""" + reads 7.2e-16 m and the first crossing kept (N2) 0.0302 m: the bound is their geometric mean, separation + 6.5e6 each side.""" cam = self.cams[0] b = self.traced(cam, -1) v = b[-1] - b[1199] @@ -403,6 +429,39 @@ class LiftTests(unittest.TestCase): self.assertEqual((out["ambiguous"], out["unmatched"], len(out["crease"])), (10, 2, 22)) self.assertLess(self.off(out["crease"]), 4.7e-9) + def test_strokes_doubled_back_lift_exactly_or_are_refused(self): + """pair-global-choice: 189 strokes of line b doubled back beside themselves (seven stretches of the crease, + three offsets, the true stroke first, between or last, three views), `extend` 0. The crossings are chosen + together, so every stroke whose points all have their true crossing lifts exactly: 174, worst 9.7e-16 m. + In the other 15, all on the view 10 degrees above the crease, the last point of `a` meets only the doubled + strokes (its mirror is line b's very end), and they are refused by the kink that leaves: the worst turn + at a chosen crossing over the crease's median turn reads 7.7 to 66 on the 15 and at most 1.245 on the 174. + KINK 3.1 is the geometric mean of 1.245 and 7.71, separation 2.5 each side. G1 (each crossing + settled as it is reached) refuses strokes of the first view; K1 lifts the 15 wrong, 0.018 to 0.21 m off; + K2 (KINK 1.2) refuses strokes that lift exactly; K3 (KINK 8) lifts the strokes that read 7.7, 0.018 m off. + The lift bound is the folded-line test's.""" + n, wrong, refused = len(self.truth), [], [] + for view, cam in enumerate(self.cams): + a, b = self.traced(cam), self.traced(cam, -1) + for start, end in ((0.1, 0.3), (0.3, 0.5), (0.3, 0.7), (0.1, 0.9), (0.5, 0.8), (0.0, 0.4), (0.6, 1.0)): + i0, i1 = int(start * (n - 1)), int(end * (n - 1)) + v = b[i1] - b[i0] + out, back = b[i0:i1 + 1], b[i1:i0 - 1 if i0 else None:-1] + for offset in (0.01, 0.03, 0.06): + d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * offset * np.ptp(b, axis=0).max() + for which, line in (("first", np.vstack([b[:i1 + 1], back + d, out + 2 * d, b[i1 + 1:]])), ("last", np.vstack([b[:i0], out + d, back + 2 * d, b[i0:]])), + ("between", np.vstack([b[:i0], out + d, back + 2 * d, out, b[i1 + 1:]]))): + try: + lifted = core.pair(cam, FRAME, a, line, extend=0.0) + except core.ReferenceFitError as refusal: + self.assertIn("doubles back", str(refusal)) + refused.append(view) + continue + if self.off(lifted["crease"]) > 2.8e-9: + wrong.append((view, start, end, offset, which, self.off(lifted["crease"]), lifted["kink"])) + self.assertEqual(wrong, []) + self.assertEqual(refused, [2] * 15) + def test_a_line_that_repeats_an_end_point_is_refused(self): """A doubled click at an end of line b leaves that end no direction to run on in: refused by name (it was a LinAlgError out of the triangulation). A repeat inside either line, or at an end of line a, is harmless.""" -- 2.47.3 From 64061d4fe51262d1de8e25ba18dcdd1c89f74443 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Wed, 2 Dec 2026 22:34:07 +0100 Subject: [PATCH 08/13] brokkr_reference.flow_score: the hiding margin is the edge's own object's or the met object's, the smaller A ground or hull among the meshes read no longer sets the margin. Live: a box over a ground 20 and 40 times its size, a small box behind a long strip (O7), chips before a large box (O9), cameras 30 and 144 diagonals off (O5). Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 34 ++-- surfaces/blender/tests/live/reference_lift.py | 91 ++++++--- .../tests/live/reference_lift.result.json | 178 +++++++++++------- 3 files changed, 197 insertions(+), 106 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index b6f3c8a..d596b41 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -98,22 +98,37 @@ def record(context, name, box): core.numbers(box, 4, "box") if box.strip() else None) -HIDE = 1e-3 # of the diagonal of the meshes read: a sight line stops this short of an edge, so that the edge's own faces do not hide it; a surface nearer the edge than this does not either +HIDE = 1e-3 # of an object's diagonal: a sight line stops this share of the edge's own object short of the edge, so that the edge's own faces do not hide it; a surface nearer the edge than that hides it only from further than this share of its own object + + +def _diagonal(obj, placed, dg): + """The diagonal of an object's evaluated bounding box as `placed` (a world matrix) stands it.""" + return float(np.linalg.norm(np.ptp(np.array([placed @ Vector(corner) for corner in obj.evaluated_get(dg).bound_box]), axis=0))) 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: a ray from the - camera toward the point meets no surface before it stops HIDE of the build's diagonal short of it, the same - share at any scale. `objects` are the meshes read, and the build whose diagonal that is; anything the scene - renders hides. Returns {kind: [[u0, v0, u1, v1], ...]} in the record's pixels.""" + camera toward the point meets no surface nearer it than the hiding margin: HIDE of the diagonal of the edge's + own object or of the object met, the smaller of the two, so the margin is the same share of the parts involved + at any scale and whatever else the scene holds (a ground plane, a hull). Past the own object's margin the ray + is cast once more, and the first surface it meets there decides. `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)) - corners = np.array([obj.matrix_world @ Vector(corner) for obj in objects for corner in obj.evaluated_get(dg).bound_box]).reshape(-1, 3) - short = HIDE * float(np.linalg.norm(np.ptp(corners, axis=0))) if len(corners) else 0.0 + + def hidden(p, short): + d = float(np.linalg.norm(p - eye)) + toward = (p - eye) / d + if scene.ray_cast(dg, Vector(eye), Vector(toward), distance=d - short)[0]: + return True + hit, where, _, _, other, placed = scene.ray_cast(dg, Vector(eye + toward * (d - short)), Vector(toward), distance=short) + return hit and d - float(np.linalg.norm(np.array(where) - eye)) > HIDE * _diagonal(other, placed, dg) + for obj in objects: ev = obj.evaluated_get(dg) + short = HIDE * _diagonal(obj, obj.matrix_world, dg) me = ev.to_mesh() nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons) if not nf: @@ -142,12 +157,7 @@ def built_edges(context, cam, objects, angle): 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 - short)[0] - if clear >= 2: + if sum(not hidden(a + t * (b - a), short) for t in (0.2, 0.5, 0.8)) >= 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 diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_lift.py index 2bac59c..2c453f1 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_lift.py @@ -11,8 +11,10 @@ core.crease_run against Blender's own subdivision. scales 0.01, 1 and 100, its front edge seen, and hidden by a strip standing in front of it by 0.316% of the box's diagonal (mutants O1, nothing hides; O2, a margin of 0.03 units; O3, HIDE ten times over: each reads the hidden edge as seen. O4, no margin at all, loses seen edges to their - own faces here and at the first box. O5, HIDE at 1e-6, passes every check: unclaimed, the margin's - floor is the ray's own rounding, which this fixture does not reach) + own faces here and at the first box). The margin is the objects' own: a box over a ground 20 and + 40 times its size, a small box over a ground behind a long strip (O7, a share of the largest mesh + read), two chips before a large box (O9, no second cast). Cameras 30 and 144 diagonals off + still read every edge (O5, HIDE at 1e-6, loses four contours at 144) blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- @@ -207,38 +209,85 @@ try: 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"]) - # --- flow_score: an edge the camera would see, hidden by a nearer surface, at three scales ------------------------ - for s in (0.01, 1.0, 100.0): + # --- flow_score: an edge the camera would see, hidden by a nearer surface; the margin is the objects' own ---------- + def stage(half, ground=0.0, far=0.0): + """A box of half-width `half` standing on z = 0, alone or over a square ground `ground` across, and a camera: + the first box's, scaled with the box, or one `far` box diagonals off with the lens grown to match. Returns + the camera, the box's front edge, and its line as the camera draws it.""" for obj in [o for o in bpy.data.objects if o.type in ("MESH", "CURVE")]: bpy.data.objects.remove(obj) - scaled = bpy.data.objects.new(f"Scaled {s:g}", bpy.data.cameras.new(f"Scaled {s:g}")) - scene.collection.objects.link(scaled) - scaled.data.lens, scaled.data.sensor_width, scaled.data.sensor_fit, scaled.data.clip_start, scaled.data.clip_end = 50.0, 36.0, "HORIZONTAL", 0.01 * s, 1000.0 * s - scaled.matrix_world = Matrix.Translation(truth.matrix_world.translation * s) @ truth.matrix_world.to_3x3().to_4x4() + name = f"Staged {half:g} {ground:g} {far:g}" + staged = bpy.data.objects.new(name, bpy.data.cameras.new(name)) + scene.collection.objects.link(staged) + staged.data.lens, staged.data.sensor_width, staged.data.sensor_fit, staged.data.clip_start, staged.data.clip_end = 50.0 * max(1.0, far / 5.0), 36.0, "HORIZONTAL", 0.01 * half, 1e9 + if far: + centre = Vector((0.0, 0.0, half)) + place = centre + Vector((-0.55, -0.7, 0.4)).normalized() * far * 2.0 * half * math.sqrt(3.0) + staged.matrix_world = Matrix.Translation(place) @ (centre - place).to_track_quat("-Z", "Y").to_matrix().to_4x4() + else: + staged.matrix_world = Matrix.Translation(truth.matrix_world.translation * half) @ truth.matrix_world.to_3x3().to_4x4() bm = bmesh.new() - bmesh.ops.create_cube(bm, size=2.0 * s, matrix=Matrix.Translation((0.0, 0.0, s))) + bmesh.ops.create_cube(bm, size=2.0 * half, matrix=Matrix.Translation((0.0, 0.0, half))) mesh = bpy.data.meshes.new("Box") bm.to_mesh(mesh) bm.free() scene.collection.objects.link(bpy.data.objects.new("Box", mesh)) + if ground: + g = ground / 2.0 + mesh_object("Ground", [(-g, -g, -4.0 * half), (g, -g, -4.0 * half), (g, g, -4.0 * half), (-g, g, -4.0 * half)], [(0, 1, 2, 3)]) bpy.context.view_layer.update() - edge = np.array([(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)]) * s - line = f"front: {traced(scaled, edge)}" - receipt, bare = send("brokkr_reference.flow_score", camera_name=scaled.name, lines=line, objects="Box") - # a strip standing along the edge, toward the camera from it: every sight line to the edge meets it `gap` before the edge - toward = np.array(scaled.matrix_world.translation) - edge.mean(0) + edge = np.array([(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0)]) * half + return staged, edge, f"front: {traced(staged, edge)}" + + def screen(staged, name, point, gap, wide, tall): + """An upright quad `wide` by `tall` that every sight line to `point` meets `gap` before it.""" + toward = np.array(staged.matrix_world.translation) - point toward /= np.linalg.norm(toward) level = np.array([toward[0], toward[1], 0.0]) / np.hypot(toward[0], toward[1]) side = np.cross([0.0, 0.0, 1.0], level) - gap = 3.16e-3 * 2.0 * s * math.sqrt(3.0) # of the box's diagonal: the geometric mean of the shipped HIDE, 1e-3, and one ten times it (mutant O3), 3.16 from each - at = edge.mean(0) + level * gap * float(toward @ level) - mesh_object("Wall", [tuple(at + side * a * 0.2 * s + np.array([0.0, 0.0, b * 1.5 * s])) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))], [(0, 1, 2, 3)]) + at = point + level * gap * float(toward @ level) + mesh_object(name, [tuple(at + side * a * wide / 2.0 + np.array([0.0, 0.0, b * tall / 2.0])) for a, b in ((-1, -1), (1, -1), (1, 1), (-1, 1))], [(0, 1, 2, 3)]) bpy.context.view_layer.update() - receipt2, walled = send("brokkr_reference.flow_score", camera_name=scaled.name, lines=line, objects="Box") + + def front(staged, line, objects): + receipt, flow = send("brokkr_reference.flow_score", camera_name=staged.name, lines=line, **objects) + return (flow["lines"]["front"]["on"], flow["edges"]["crease"], flow["edges"]["contour"]) if receipt["status"] == "accepted" else receipt["message"] + + DIAGONAL = 2.0 * math.sqrt(3.0) # of a box, in its half-widths + for s in (0.01, 1.0, 100.0): + staged, edge, line = stage(s) + bare = front(staged, line, {"objects": "Box"}) + gap = 3.16e-3 * DIAGONAL * s # of the box's diagonal: the geometric mean of the shipped HIDE, 1e-3, and one ten times it (mutant O3), 3.16 from each + screen(staged, "Wall", edge.mean(0), gap, 0.4 * s, 3.0 * s) + walled = front(staged, line, {"objects": "Box"}) check(f"at scale {s:g} the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), " - "O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", - receipt["status"] == "accepted" and receipt2["status"] == "accepted" and bare["lines"]["front"]["on"] == 1.0 and bare["edges"]["crease"] == 3 - and walled["lines"]["front"]["on"] == 0.0 and walled["edges"]["crease"] == 2, [bare and bare["lines"], bare and bare["edges"], walled and walled["lines"], walled and walled["edges"], gap]) + "O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled, gap]) + # a larger mesh in the scene and among the meshes read: the margin stays the box's + for half, ground in ((0.5, 20.0), (0.05, 4.0)): + staged, edge, line = stage(half, ground) + bare = front(staged, line, {}) + screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * half, 0.4 * half, 3.0 * half) + walled = front(staged, line, {}) + check(f"a box {2 * half:g} across over a ground {ground:g} across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it " + f"(a margin of the ground's is {1e-3 * ground * math.sqrt(2.0) / (0.01 * DIAGONAL * half):.1f} times the gap)", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled]) + # a small box's edge behind a strip far longer than the box, over a ground: the margin is the box's, not the strip's or the ground's (O7, a share of the largest mesh read, reads on 1) + staged, edge, line = stage(0.05, 4.0) + gap = math.sqrt(1e-3 * DIAGONAL * 0.05 * 1e-3 * math.hypot(0.02, 4.0)) # the geometric mean of the box's margin and the strip's, 4.8 from each + screen(staged, "Wall", edge.mean(0), gap, 0.02, 4.0) + walled = front(staged, line, {}) + check("a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", walled == (0.0, 2, 6), [walled, gap]) + # two chips far smaller than the box, in front of two of the edge's three read points: the margin is the chips' (O9, no second cast, reads on 1) + staged, edge, line = stage(1.0) + gap = math.sqrt(1e-3 * DIAGONAL * 1e-3 * 0.05 * math.sqrt(2.0)) # the geometric mean of the box's margin and a chip's, 7 from each + for t in (0.2, 0.5): + screen(staged, f"Chip {t}", edge[0] + t * (edge[1] - edge[0]), gap, 0.05, 0.05) + chipped = front(staged, line, {"objects": "Box"}) + check("a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)", chipped == (0.0, 2, 6), [chipped, gap]) + # far cameras: the margin's floor is the ray's rounding (O5, HIDE 1e-6, loses four contours to their own faces at 144 diagonals; at 30 it reads true here) + for far in (30.0, 144.0): + staged, edge, line = stage(1.0, far=far) + bare = front(staged, line, {"objects": "Box"}) + check(f"a camera {far:g} box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1" + (" (O5 reads 2 contours)" if far == 144.0 else ""), bare == (1.0, 3, 6), bare) 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:]) diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_lift.result.json index 6e8baf8..e80de0e 100644 --- a/surfaces/blender/tests/live/reference_lift.result.json +++ b/surfaces/blender/tests/live/reference_lift.result.json @@ -220,61 +220,33 @@ "name": "at scale 0.01 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", "ok": true, "detail": [ - { - "front": { - "on": 1.0, - "off": 0.0, - "run": 1.0 - } - }, - { - "crease": 3, - "contour": 6, - "border": 0 - }, - { - "front": { - "on": 0.0, - "off": 5.0, - "run": 0.0 - } - }, - { - "crease": 2, - "contour": 6, - "border": 0 - }, - 0.00010946561103835305 + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], + 0.00010946561103835304 ] }, { "name": "at scale 1 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", "ok": true, "detail": [ - { - "front": { - "on": 1.0, - "off": 0.0, - "run": 1.0 - } - }, - { - "crease": 3, - "contour": 6, - "border": 0 - }, - { - "front": { - "on": 0.0, - "off": 5.0, - "run": 0.0 - } - }, - { - "crease": 2, - "contour": 6, - "border": 0 - }, + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], 0.010946561103835304 ] }, @@ -282,32 +254,92 @@ "name": "at scale 100 the box's front edge is a crease the camera sees (on 1); a strip 0.316% of the box's diagonal in front of it hides it (on 0, one crease fewer): O1 (nothing hides), O2 (the ray stops 0.03 units short) and O3 (ten times HIDE) read on 1", "ok": true, "detail": [ - { - "front": { - "on": 1.0, - "off": 0.0, - "run": 1.0 - } - }, - { - "crease": 3, - "contour": 6, - "border": 0 - }, - { - "front": { - "on": 0.0, - "off": 5.0, - "run": 0.0 - } - }, - { - "crease": 2, - "contour": 6, - "border": 0 - }, + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ], 1.0946561103835304 ] + }, + { + "name": "a box 1 across over a ground 20 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 1.6 times the gap)", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ] + ] + }, + { + "name": "a box 0.1 across over a ground 4 across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it (a margin of the ground's is 3.3 times the gap)", + "ok": true, + "detail": [ + [ + 1.0, + 3, + 6 + ], + [ + 0.0, + 2, + 6 + ] + ] + }, + { + "name": "a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", + "ok": true, + "detail": [ + [ + 0.0, + 2, + 6 + ], + 0.000832363492248106 + ] + }, + { + "name": "a box 2 across with two chips 0.05 across standing between the two margins in front of its edge: hidden, the margin is the chips' (O9 reads on 1)", + "ok": true, + "detail": [ + [ + 0.0, + 2, + 6 + ], + 0.0004949232003839765 + ] + }, + { + "name": "a camera 30 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1", + "ok": true, + "detail": [ + 1.0, + 3, + 6 + ] + }, + { + "name": "a camera 144 box diagonals off still reads the box's 3 creases and 6 contours and its front edge on 1 (O5 reads 2 contours)", + "ok": true, + "detail": [ + 1.0, + 3, + 6 + ] } ], "hostErrors": [], -- 2.47.3 From 3b19e8c8164fb824106faa61508446d69ef422e7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:30:34 +0100 Subject: [PATCH 09/13] brokkr_reference.pair: a point with no fitting crossing is skipped and named, the kink gate is gone; PLANAR between 0.041 and 0.36 aetheria-release:ruling:lift-skips-points-not-strokes. The global choice may give a point that met line b more than once no crossing, at SKIP (2.8) times the crease's median turn, the median never under TURN (0.061 rad), the turn read across the gap. "skipped" names the points; a lift that skips more than SHARE (0.24) of the points that met line b is refused, and no more than that are skipped in a row. KINK and "kink" are deleted. One _bend. 189 exact doubled-back strokes: 0 wrong, 0 refused, 15 skip their last point (was 15 refused). A cornered crease lifts 24 of 24 at each view (was refused at one). PLANAR 0.057 to 0.12, claimed by a panel reading 0.041; DECIDED's one-step separation is recorded as an exception to lodur:ruling:deterministic-bound-margin; S1 claimed by a direct _bend test. Co-Authored-By: Claude Fable 5.2 --- .../brokkr_reference/brokkr_actions.json | 2 +- surfaces/blender/brokkr_reference/core.py | 107 ++++++++------ surfaces/blender/tests/test_reference.py | 137 +++++++++++++----- 3 files changed, 165 insertions(+), 81 deletions(-) diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index acd418b..a2cc046 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -83,7 +83,7 @@ }, { "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).", + "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, the points skipped, and how far the built crease draws from each line (docs/reference.md).", "changesScene": true, "editModeSafe": false, "result": "brokkr_mesh_polish_result", diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 49e8818..41dc110 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -48,9 +48,11 @@ LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a vi BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best STEP = 0.1 # the band is walked in steps of this in log f FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) -PLANAR = 0.057 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.009, a panel with relief whose band does open at one end, and 0.36, marks with depth (tests/test_reference.py) -KINK = 3.1 # pair refuses a lift whose worst turn at a chosen crossing is more than this many times the crease's median turn (tests/test_reference.py holds the readings either side) -DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65) +PLANAR = 0.12 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.041, a panel with relief whose band does open at one end, and 0.36, marks with depth: separation 2.9 each side (tests/test_reference.py) +SKIP = 2.8 # pair: a point that met line b more than once may be given no crossing, at the cost of this many times the crease's median turn. On 189 exact doubled-back strokes 1.25 to 7 lift every one exactly with one point skipped in 15; 1.0 and 8 lift some wrong: the geometric mean, 2.8 each side (read with TURN out of the way, tests/test_reference.py) +TURN = 0.061 # radians: the median turn is never read as less than this, so a crease of straight runs (median turn 0) does not skip for nothing. The geometric mean of 0.0496, under which a cornered crease drops the points between two of its corners, and 0.0749, over which a wrong crossing of a gentle crease (median turn 0.025) is cheaper than its skip: separation 1.23 each side +SHARE = 0.24 # pair refuses a lift that skips more than this share of the points that met line b, and never skips more than this share in a row. The geometric mean of 4 of 23, the most skipped on 11340 noisy doubled-back strokes, and 8 of 24, a scribbled line b: separation 1.38 each side +DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65). An exception to lodur:ruling:deterministic-bound-margin: the two readings are one STEP apart, 1.105, and readings quantised in STEPs have no pair 1.2 apart with nothing between; a host that moves a band by a step fails the span assertion in tests/test_reference.py MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -404,37 +406,49 @@ def extended(points, by): def _bend(X0, X1, X2): - """The turn, in radians, of a crease that runs X0, X1, X2; a half turn where it stands still.""" - u, v = X1 - X0, X2 - X1 - along = np.linalg.norm(u) * np.linalg.norm(v) - return float(np.arccos(np.clip(u @ v / along, -1, 1))) if along > 1e-24 else math.pi + """The turn, in radians, of a crease that runs X0, X1, X2 (three numbers each); a half turn where it stands + still. Plain arithmetic: _smoothest reads it a million times on a long fold.""" + u, v = (X1[0] - X0[0], X1[1] - X0[1], X1[2] - X0[2]), (X2[0] - X1[0], X2[1] - X1[1], X2[2] - X1[2]) + along = math.sqrt((u[0] * u[0] + u[1] * u[1] + u[2] * u[2]) * (v[0] * v[0] + v[1] * v[1] + v[2] * v[2])) + return math.acos(max(-1.0, min(1.0, (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]) / along))) if along > 1e-24 else math.pi -def _smoothest(candidates): +def _smoothest(candidates, skip=None, run=0): """One candidate per point, chosen together: the choice whose curve turns least in all (the sum of _bend over - every three points in a row), found by dynamic programming over pairs of neighbouring choices, so no point is - settled before the points after it are read. Returns the index taken at each point; ties go to the earlier - candidate.""" + every three taken points in a row), found by dynamic programming over pairs of neighbouring taken points, so + no point is settled before the points after it are read. With `skip` (radians) a point that has more than one + candidate may take none, at that cost, up to `run` such points in a row: the turn is then read across the gap, + over the points that are taken, so a skip cannot hide a turn. Returns the index taken at each point, None where it is skipped; ties go to the + earlier candidate and to the choice reached first.""" m = len(candidates) - if m < 3: - return [0] * m - cost = {(j, k): 0.0 for j in range(len(candidates[0])) for k in range(len(candidates[1]))} - back = [] - for t in range(2, m): - new, via = {}, {} - for (h, j), c in cost.items(): - for k, X in enumerate(candidates[t]): - total = c + _bend(candidates[t - 2][h], candidates[t - 1][j], X) - if (j, k) not in new or total < new[j, k]: - new[j, k], via[j, k] = total, h - cost = new - back.append(via) - j, k = min(cost, key=lambda s: (cost[s], s)) - taken = [k, j] - for via in reversed(back): - j, k = via[j, k], j - taken.append(j) - return taken[::-1] + C = [[tuple(float(v) for v in X) for X in options] for options in candidates] + free = [skip is not None and len(options) > 1 for options in C] + + best = {} # (t, k, the taken point before it, its candidate) -> (cost, the state before) + for t in range(min(m, run + 1)): + for k in range(len(C[t])): + best[t, k, -1, -1] = (skip * t if t else 0.0, None) + if not free[t]: + break + end, least = None, math.inf + for t in range(m): + for state in [s for s in best if s[0] == t]: + cost, _ = best[state] + _, k, tp, kp = state + if m - 1 - t <= run and all(free[t + 1:]) and cost + (skip or 0.0) * (m - 1 - t) < least: + end, least = state, cost + (skip or 0.0) * (m - 1 - t) + for t2 in range(t + 1, min(m, t + run + 2)): + for k2, X in enumerate(C[t2]): + total = cost + (skip * (t2 - t - 1) if t2 > t + 1 else 0.0) + (_bend(C[tp][kp], C[t][k], X) if tp >= 0 else 0.0) + if (t2, k2, t, k) not in best or total < best[t2, k2, t, k][0]: + best[t2, k2, t, k] = (total, state) + if not free[t2]: + break + taken = [None] * m + while end is not None: + taken[end[0]] = end[1] + end = best[end][1] + return taken def pair(cam, frame, a, b, n=24, extend=0.2): @@ -446,13 +460,15 @@ def pair(cam, frame, a, b, n=24, extend=0.2): 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; "kink": the worst turn (_bend) at a point that had - a crossing to choose, over the crease's median turn}. 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: the crossings are - chosen together, as the choice whose crease turns least in all (_smoothest). That is the true crease wherever - every point's true crossing is among its crossings. Where one is not (the end of `a` mirrors the very end of - `b`, and only the doubled strokes are met) the smoothest crease still kinks there, and a kink over KINK is - refused. + "ambiguous": points whose line meets `b` more than once; "skipped": the points of `a` (their indices among + its n) that met `b` more than once and were given no crossing, left out}. 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: the crossings are chosen together, as the choice whose crease turns least in all (_smoothest). That is + the true crease wherever every point's true crossing is among its crossings. Where one is not (the end of `a` + mirrors the very end of `b`, and only the doubled strokes are met) every crossing of that point kinks the + crease, and the point is skipped instead: a skip costs SKIP times the crease's median turn (the median of the + choice with no skips, never under TURN), and only a point with a choice can be skipped. A lift that skips more + than SHARE of the points it had crossings for is refused, and the choice never skips more than that in a row. 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.""" @@ -474,13 +490,18 @@ def pair(cam, frame, a, b, n=24, extend=0.2): found.append(lifts) fold = lambda X: np.array([abs(X[0]), X[1], X[2]]) # noqa: E731 at = [i for i, lifts in enumerate(found) if lifts] - lifted = [found[i][k] for i, k in zip(at, _smoothest([[fold(X) for X in found[i]] for i in at]))] - bends = [(_bend(fold(lifted[t - 2]), fold(lifted[t - 1]), fold(lifted[t])), any(len(found[i]) > 1 for i in at[t - 2:t + 1])) for t in range(2, len(at))] - kink = max((bend for bend, chose in bends if chose), default=0.0) / max(float(np.median([bend for bend, _ in bends])), 1e-12) if bends else 0.0 - if kink > KINK: - raise ReferenceFitError(f"line b doubles back and the smoothest crease through its crossings still turns {kink:.1f} times its usual turn where a crossing was chosen (over {KINK} is refused): a point of line a has no true mirror among its crossings, most often at an end. Draw line b as one stroke that does not run beside itself") + folded = [[fold(X) for X in found[i]] for i in at] + taken = _smoothest(folded) + if any(len(options) > 1 for options in folded) and len(at) > 2: + whole = [folded[t][k] for t, k in enumerate(taken)] + usual = float(np.median([_bend(*whole[t - 2:t + 1]) for t in range(2, len(whole))])) + taken = _smoothest(folded, SKIP * max(usual, TURN), int(SHARE * len(at))) + skipped = [i for i, k in zip(at, taken) if k is None] + if len(skipped) > SHARE * len(at): + raise ReferenceFitError(f"line b doubles back and {len(skipped)} of the {len(at)} points of line a that meet it have no crossing that fits the crease (points {skipped}; over {SHARE:g} of them is refused). Draw line b as one stroke that does not run beside itself") + lifted = [found[i][k] for i, k in zip(at, taken) if k 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": sum(1 for lifts in found if len(lifts) > 1), "kink": float(kink), "unmatched": sum(1 for lifts in found if not lifts)} + "ambiguous": sum(1 for lifts in found if len(lifts) > 1), "skipped": skipped, "unmatched": sum(1 for lifts in found if not lifts)} def on_plane(cam, frame, line, point, normal, n=24): diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index e333c45..2c7972a 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -27,6 +27,7 @@ import re import sys import types import unittest +import unittest.mock from pathlib import Path SURFACE = Path(__file__).resolve().parents[1] @@ -291,12 +292,13 @@ class SolveTests(unittest.TestCase): 85 mm, 3 px off, read a band of four steps, 1.4918 times, the widest of 48 such solves, and are called determined; the same marks 5 px off read five steps, 1.6487, and are not. DECIDED 1.57 is the geometric mean, 1.05 from each: the readings are one step apart, 1.105, under the ruling's 1.2, and no nearer pair - exists. Mutants DECIDED 1.4 and 1.7 die here by which call flips; 2.5 too. PLANAR: a panel with relief - (planarity 0.009) seen square-on reads a band open at 4000 mm and so is reported open at both ends; marks - with depth read 0.36. PLANAR 0.057 is the geometric mean, 6.3 from each: PLANAR 0.001 and 0.008 leave the - panel's band at [38.6, 4000] and die here, PLANAR 1.0 dies at the oblique view. Unclaimed, no reading - between: mutants from 0.009 to 0.36 (0.03 and 0.3 pass every test); panels of planarity 0.03 and 0.06 - read closed bands 1.5 to 4 times wide, where PLANAR does nothing.""" + exists: an exception to the ruling, recorded at core.DECIDED (a band moved one step by a host fails the span + assertion here, loudly). Mutants DECIDED 1.4 and 1.7 die here by which call flips; 2.5 too; 1.5 and 1.6 are + unclaimed, inside the step. PLANAR: a panel with relief (planarity 0.041) seen square-on through 85 mm, + 3 px off, reads a band open at 4000 mm and so is reported open at both ends; marks with depth read 0.36. + PLANAR 0.12 is the geometric mean, 2.9 from each: PLANAR 0.03 leaves the panel's band at [84.4, 4000] and + dies here, as 0.001 and 0.008 do on the flatter panel (0.009); PLANAR 1.0 dies at the oblique view. + Unclaimed: PLANAR 0.3, which differs from shipped in none of 192 solves of panels 0.009 to 0.277 thick.""" for noise, span, determined in ((3.0, 1.4918, True), (5.0, 1.6487, False)): drawn = core.project(camera(self.points, 35, 20, 85), self.points) + np.random.default_rng(3).normal(0, noise, (13, 2)) s = core.solve(dict(zip(NAMES, self.points.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) @@ -304,11 +306,12 @@ class SolveTests(unittest.TestCase): self.assertIs(s["lens_determined"], determined) self.assertAlmostEqual(s["planarity"], 0.3615, delta=1e-3) relief = np.random.default_rng(77).uniform(-1, 1, 13) - panel = np.c_[self.points[:, :2], relief / np.ptp(relief) * 0.01 * np.ptp(self.points[:, :2], axis=0).max()] - drawn = core.project(camera(panel, 35, 90.0, 50), panel) + np.random.default_rng(0).normal(0, 1.0, (13, 2)) - s = core.solve(dict(zip(NAMES, panel.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) - self.assertAlmostEqual(s["planarity"], 0.009, delta=5e-4) - self.assertEqual((s["lens_band"], s["lens_determined"]), (list(core.LENS_MM), False)) + for depth, lens, noise, planarity in ((0.01, 50, 1.0, 0.009), (0.045, 85, 3.0, 0.041)): + panel = np.c_[self.points[:, :2], relief / np.ptp(relief) * depth * np.ptp(self.points[:, :2], axis=0).max()] + drawn = core.project(camera(panel, 35, 90.0, lens), panel) + np.random.default_rng(0).normal(0, noise, (13, 2)) + s = core.solve(dict(zip(NAMES, panel.tolist())), dict(zip(NAMES, drawn.tolist())), BOX) + self.assertAlmostEqual(s["planarity"], planarity, delta=5e-4) + self.assertEqual((s["lens_band"], s["lens_determined"]), (list(core.LENS_MM), False)) def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self): """exact-gate: each of _decidable's three tests reads a ratio (the marks' thinnest extent over their @@ -353,10 +356,13 @@ 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_smoothest_crossing, and the two after it - G1 each crossing chosen as it is reached (greedy) test_strokes_doubled_back_lift_exactly_or_are_refused - K1 no refusal; K2, K3 KINK 1.2 and 8 the same - Unclaimed: S1, a crease that stands still costs no turn (_bend's half turn read as 0), passes every test: no - fixture lifts two points to one place. + K1 no point skipped test_strokes_doubled_back_lift_exactly_with_a_point_skipped + K2, K3 SKIP 1.0 and 8 the same, where TURN is set to 0 + K5 a skip's turn not read across the gap the same + K4 a point with one crossing may be skipped test_a_cornered_crease_lifts_whole + T1, T2 TURN 0.04 and 0.09 the same; the doubled strokes + R1, R2 SHARE 0.15 and 0.4 test_a_scribbled_line_is_refused_by_its_share_of_skips + S1 a crease that stands still costs no turn test_a_crease_that_stands_still_is_a_half_turn H1 a crossing snapped to line b's point before it test_a_hand_traced_pair_lifts_within_a_bound 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 @@ -429,18 +435,10 @@ class LiftTests(unittest.TestCase): self.assertEqual((out["ambiguous"], out["unmatched"], len(out["crease"])), (10, 2, 22)) self.assertLess(self.off(out["crease"]), 4.7e-9) - def test_strokes_doubled_back_lift_exactly_or_are_refused(self): - """pair-global-choice: 189 strokes of line b doubled back beside themselves (seven stretches of the crease, - three offsets, the true stroke first, between or last, three views), `extend` 0. The crossings are chosen - together, so every stroke whose points all have their true crossing lifts exactly: 174, worst 9.7e-16 m. - In the other 15, all on the view 10 degrees above the crease, the last point of `a` meets only the doubled - strokes (its mirror is line b's very end), and they are refused by the kink that leaves: the worst turn - at a chosen crossing over the crease's median turn reads 7.7 to 66 on the 15 and at most 1.245 on the 174. - KINK 3.1 is the geometric mean of 1.245 and 7.71, separation 2.5 each side. G1 (each crossing - settled as it is reached) refuses strokes of the first view; K1 lifts the 15 wrong, 0.018 to 0.21 m off; - K2 (KINK 1.2) refuses strokes that lift exactly; K3 (KINK 8) lifts the strokes that read 7.7, 0.018 m off. - The lift bound is the folded-line test's.""" - n, wrong, refused = len(self.truth), [], [] + def doubled(self): + """189 strokes of line b doubled back beside themselves: seven stretches of the crease, three offsets, the + true stroke first, between or last, three views.""" + n = len(self.truth) for view, cam in enumerate(self.cams): a, b = self.traced(cam), self.traced(cam, -1) for start, end in ((0.1, 0.3), (0.3, 0.5), (0.3, 0.7), (0.1, 0.9), (0.5, 0.8), (0.0, 0.4), (0.6, 1.0)): @@ -451,16 +449,81 @@ class LiftTests(unittest.TestCase): d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * offset * np.ptp(b, axis=0).max() for which, line in (("first", np.vstack([b[:i1 + 1], back + d, out + 2 * d, b[i1 + 1:]])), ("last", np.vstack([b[:i0], out + d, back + 2 * d, b[i0:]])), ("between", np.vstack([b[:i0], out + d, back + 2 * d, out, b[i1 + 1:]]))): - try: - lifted = core.pair(cam, FRAME, a, line, extend=0.0) - except core.ReferenceFitError as refusal: - self.assertIn("doubles back", str(refusal)) - refused.append(view) - continue - if self.off(lifted["crease"]) > 2.8e-9: - wrong.append((view, start, end, offset, which, self.off(lifted["crease"]), lifted["kink"])) - self.assertEqual(wrong, []) - self.assertEqual(refused, [2] * 15) + yield (view, start, end, offset, which), cam, a, line + + def test_strokes_doubled_back_lift_exactly_with_a_point_skipped(self): + """pair-global-choice, aetheria-release:ruling:lift-skips-points-not-strokes: `extend` 0. The crossings are + chosen together, so every stroke whose points all have their true crossing lifts exactly with nothing + skipped: 174. In the other 15, all on the view 10 degrees above the crease, the last point of `a` meets + only the doubled strokes (its mirror is line b's very end); that point is skipped, it alone, and the other + 23 lift exactly: worst of the 189, 9.7e-16 m, none refused. Read twice: as shipped, where the crease's + median turn (0.025) is under TURN and a skip costs SKIP x TURN, 6.8 medians; and with TURN at 0, where it + costs SKIP medians and SKIP's own readings show: 1.25 to 7 read the same, 1.0 (K2) skips points that had + their true crossing and lifts strokes wrong, 0.008 m off, 8 (K3) keeps a wrong crossing, 0.018 m off: 2.8 + is the geometric mean, 2.8 each side. As shipped, TURN up to 0.0749 reads the same and 0.09 (T2) lifts + strokes wrong, 0.018 m off. K1 (no skip) lifts the 15 wrong; K5 (the turn not read across a skipped + point) skips where nothing is wrong. The lift bound is the folded-line test's.""" + for turn in (core.TURN, 0.0): + with unittest.mock.patch.object(core, "TURN", turn): + wrong, skipped = [], [] + for key, cam, a, line in self.doubled(): + lifted = core.pair(cam, FRAME, a, line, extend=0.0) + if self.off(lifted["crease"]) > 2.8e-9 or len(lifted["crease"]) + len(lifted["skipped"]) + lifted["unmatched"] != 24: + wrong.append((key, self.off(lifted["crease"]), lifted["skipped"])) + if lifted["skipped"]: + skipped.append((key[0], lifted["skipped"])) + self.assertEqual(wrong, [], turn) + self.assertEqual(skipped, [(2, [23])] * 15, turn) + + CORNERS = [[0.4, -1.0, 0.5], [0.7, -0.35, 0.55], [0.35, 0.15, 0.75], [0.6, 0.6, 0.7], [0.4, 1.0, 0.8]] + + def test_a_cornered_crease_lifts_whole(self): + """kink-refuses-exact-cornered-crease: a crease of four straight runs, corners of 1.0 to 1.2 radians, traced + exactly, no fold. Its median turn is 0 (1.5e-8), and at the first view three points between two corners + meet line b twice. All 24 lift at each view, 1.2e-15 m off, nothing skipped: the median is read as TURN. + With TURN under 0.0496 (T1 0.04) the three are skipped, which saves the 0.35 radians of the stretch + between the corners; K4 (a point with one crossing may be skipped) skips here too.""" + V = np.array(self.CORNERS) + truth = np.vstack([np.linspace(V[i], V[i + 1], 500, endpoint=False) for i in range(4)] + [V[-1:]]) + for cam, ambiguous in zip(self.cams, (3, 0, 0)): + out = core.pair(cam, FRAME, core.seen(cam, FRAME, truth), core.seen(cam, FRAME, truth * [-1, 1, 1])) + self.assertEqual((len(out["crease"]), out["ambiguous"], out["skipped"], out["unmatched"]), (24, ambiguous, [], 0)) + self.assertLess(float(core._off(np.array(out["crease"]), truth).max()), 1e-6) + + def test_a_scribbled_line_is_refused_by_its_share_of_skips(self): + """SHARE: line b scribbled over (six loops, 12% of its extent across) on the second view. Over the middle + two fifths 4 of the 23 points that meet it are skipped, 0.174, and the lift is given, with the four named; + over the whole line 8 of 24, 0.333, and it is refused. 4 of 23 is also the most skipped in 11340 noisy + doubled-back strokes (cut_report h4). SHARE 0.24 is the geometric mean, 1.38 each side: R1 (0.15) refuses + the first, R2 (0.4) gives the second. The share says how much of the stroke was left out, not that what + was kept is right: the first lift is 0.066 m off, the scribble's own width.""" + cam, n = self.cams[1], len(self.truth) + a, b = self.traced(cam), self.traced(cam, -1) + + def scribbled(start, end): + i0, i1 = int(start * (n - 1)), int(end * (n - 1)) + t = np.linspace(0, 1, i1 - i0 + 1) + d = np.gradient(b, axis=0)[i0:i1 + 1] + d /= np.linalg.norm(d, axis=1)[:, None] + wide = 0.12 * np.ptp(b, axis=0).max() + line = b.copy() + line[i0:i1 + 1] += np.stack([-d[:, 1], d[:, 0]], 1) * ((2 * np.abs((t * 6) % 1 - 0.5) - 0.5) * wide)[:, None] + d * (np.sin(12 * np.pi * t) * wide)[:, None] + return line + + out = core.pair(cam, FRAME, a, scribbled(0.3, 0.7), extend=0.0) + self.assertEqual((len(out["skipped"]), len(out["crease"]), out["unmatched"]), (4, 19, 1)) + with self.assertRaises(core.ReferenceFitError) as caught: + core.pair(cam, FRAME, a, scribbled(0.0, 1.0), extend=0.0) + self.assertIn("8 of the 24 points", str(caught.exception)) + + def test_a_crease_that_stands_still_is_a_half_turn(self): + """S1: two crossings that lift to one place are not a straight run. A retraced line a does lift a point + twice.""" + X, Y = np.array([0.4, 0.0, 0.5]), np.array([0.5, 0.2, 0.5]) + self.assertEqual(core._bend(X, X, Y), math.pi) + self.assertEqual(core._bend(X, Y, Y), math.pi) + self.assertAlmostEqual(core._bend(X, Y, 2 * Y - X), 0.0, delta=1e-7) + self.assertAlmostEqual(core._bend(X, Y, X), math.pi, delta=1e-7) def test_a_line_that_repeats_an_end_point_is_refused(self): """A doubled click at an end of line b leaves that end no direction to run on in: refused by name (it was a -- 2.47.3 From 72282df458b512f93d6fd666aeb81b71eba3cd34 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:30:34 +0100 Subject: [PATCH 10/13] brokkr_reference.flow_score: the hiding margin is the edge's own connected piece's; docs for skipped points A box joined into one mesh with a ground kept the whole mesh's margin and its edge was hidden only from 16% of the box's diagonal (finding hiding-margin-same-mesh). built_edges now measures the connected part of the mesh the edge lies on; the object met is still measured whole, and docs/reference.md says so. Live: reference_lift.py 32 of 32 with the joined-mesh check (mutant O10, the whole mesh's diagonal, fails it), reference.py 14 of 14, Blender 5.3 on Starfire. docs/reference.md: lift_pair's skipped points, SKIP, TURN, SHARE and the readings. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 23 +++++++++--- surfaces/blender/docs/reference.md | 37 ++++++++++++------- .../blender/tests/live/reference.result.json | 12 ++++-- surfaces/blender/tests/live/reference_lift.py | 21 +++++++++-- .../tests/live/reference_lift.result.json | 11 +++++- 5 files changed, 77 insertions(+), 27 deletions(-) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index d596b41..2cd7956 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -98,7 +98,7 @@ def record(context, name, box): core.numbers(box, 4, "box") if box.strip() else None) -HIDE = 1e-3 # of an object's diagonal: a sight line stops this share of the edge's own object short of the edge, so that the edge's own faces do not hide it; a surface nearer the edge than that hides it only from further than this share of its own object +HIDE = 1e-3 # of a diagonal: a sight line stops this share of the edge's own piece of mesh short of the edge, so that the edge's own faces do not hide it; a surface nearer the edge than that hides it only from further than this share of its own object def _diagonal(obj, placed, dg): @@ -111,9 +111,10 @@ def built_edges(context, cam, objects, angle): 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: a ray from the camera toward the point meets no surface nearer it than the hiding margin: HIDE of the diagonal of the edge's - own object or of the object met, the smaller of the two, so the margin is the same share of the parts involved - at any scale and whatever else the scene holds (a ground plane, a hull). Past the own object's margin the ray - is cast once more, and the first surface it meets there decides. `objects` are the meshes read; anything the + own piece (the connected part of its mesh it lies on: a box joined into one mesh with a ground is still a + box) or of the object met, the smaller of the two, so the margin is the same share of the parts involved at + any scale and whatever else the scene or the mesh holds (a ground plane, a hull). Past the own piece's margin + the ray is cast once more, and the first surface it meets there decides; the object met is measured whole. `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)) @@ -128,7 +129,6 @@ def built_edges(context, cam, objects, angle): for obj in objects: ev = obj.evaluated_get(dg) - short = HIDE * _diagonal(obj, obj.matrix_world, dg) me = ev.to_mesh() nv, ne, nl, nf = len(me.vertices), len(me.edges), len(me.loops), len(me.polygons) if not nf: @@ -155,8 +155,21 @@ def built_edges(context, cam, objects, angle): 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) + piece, shorts = np.arange(nv), {} # each vertex's connected piece, named by its least vertex + while True: + low = np.minimum(piece[ends[:, 0]], piece[ends[:, 1]]) + spread = piece.copy() + np.minimum.at(spread, ends[:, 0], low) + np.minimum.at(spread, ends[:, 1], low) + spread = spread[spread] + if (spread == piece).all(): + break + piece = spread for k in np.nonzero(crease | contour | (count == 1))[0]: a, b = co[ends[k, 0]], co[ends[k, 1]] + if piece[ends[k, 0]] not in shorts: + shorts[piece[ends[k, 0]]] = HIDE * float(np.linalg.norm(np.ptp(co[piece == piece[ends[k, 0]]], axis=0))) + short = shorts[piece[ends[k, 0]]] if sum(not hidden(a + t * (b - a), short) for t in (0.2, 0.5, 0.8)) >= 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)]) diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index d18a741..9ae88d5 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -117,7 +117,7 @@ and focal length trade against each other (a dolly zoom) and the picture barely those would be called best. It is an **equal-error band, not a confidence interval**: it says which lenses the marks cannot tell apart, and on probes a few such bands excluded the true lens. A band that ends at 4000 or at 4 was stopped by the bound. -- For flat marks (`planarity` under 0.057, `core.PLANAR`) a band that reaches one end of the range is reported as +- For flat marks (`planarity` under 0.12, `core.PLANAR`) a band that reaches one end of the range is reported as the whole range, 4 to 4000. What closes the other end of such a band is a tilt of the plane traded against the lens, and the marks' error sets that either way: a square-on plane's band read 309 to 4000 mm on one seed with the true lens at 50. This gives up the one-sided reading ("at least 300 mm") for flat marks; marks with depth @@ -158,7 +158,7 @@ x axis; the pair is triangulated as one point seen by the camera and by the came The report: `crease` (`[[x, y, z], ...]` in the frame, x >= 0, in the order of `line_a`), `side` (+1 or -1: the side of the frame `line_a` is on), `unmatched` (points of `line_a` whose line to the vanishing point never meets -`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `kink`, `cage`, `miss` and +`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `skipped`, `cage`, `miss` and `curve`. The camera is read back from the object (`core.camera_of`): a perspective camera with a horizontal sensor fit. The curve is for the eye; the report is the truth. @@ -167,16 +167,23 @@ a line folds back, the crease can: the crossings of all the points are chosen to crease turns least in all (the sum of its turns at each point, by dynamic programming), so no point is settled before the points after it are read. Wherever each point's true crossing is among its crossings, that is the true crease. Where it is not (most often the last point of `line_a`, whose mirror is the very end of `line_b`, meeting -only the doubled strokes) the smoothest crease still kinks at that point. `kink` is the worst turn at a point that -had a choice, over the crease's median turn, and a lift whose `kink` is over 3.1 (`core.KINK`) is refused: draw -`line_b` as one stroke. +only the doubled strokes) every crossing of that point kinks the crease, and the point is given none: it is left +out of `crease` and named in `skipped`, the indices of such points among the `samples` of `line_a`. Only a point +with more than one crossing can be skipped. A skip costs 2.8 (`core.SKIP`) times the crease's median turn, and the +turn is read across the gap, so a skip cannot hide a turn. The median is never read as less than 0.061 radians +(`core.TURN`), so a crease of straight runs and corners, whose median turn is nothing, lifts whole. A lift that +skips more than 0.24 (`core.SHARE`) of the points that met `line_b` is refused, and no more than that are skipped +in a row: draw `line_b` as one stroke. On 189 exact strokes of `line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three -views) 174 lift exactly, with `kink` at most 1.25, and 15 are refused, `kink` 7.7 to 66, all on the view 10 degrees -above the crease; none lifts wrong. On hand-traced lines the refusal is blunt: with the same folds drawn on -twelve-point traces 0.5 and 1.5 px off, it refuses 20% and 50% of the lifts the fold did not harm (108 of 540, 264 -of 533), and passes none of 27 and 3 of 34 that it did, the three within 1.8 cm of the unfolded lift. A trace's own wobble turns the crease as -much as a wrong crossing does, and no reading of the lift tells them apart. A lift with no ambiguous +views) every one lifts exactly, none refused; 15, all on the view 10 degrees above the crease, skip their last +point. On hand-traced lines (the same folds on traces 0.25 to 3 px off: twelve jittered points, thirty, and a slow +wobble; 11340 strokes) none is refused, 1824 skip a point or more, at most 4 of 23, and 475 lift more than 5 mm +worse than the same trace unfolded, 131 of them more than 20 mm: 21 of the 3780 wobbled, 130 of the twelve-point +and 324 of the thirty-point, where a 1 px tremor already stands in for a wrong crossing. A trace's own wobble +turns the crease as much as a wrong crossing does, and no reading of the lift tells them apart: `skipped` says +what was left out, not that the rest is right. A scribbled `line_b` can lift 0.07 m off with nothing skipped and +takes seconds. A lift with no ambiguous point has no choice anywhere and is never refused. A line whose first or last point is given twice is refused: that end of `line_b` has no direction to run on in. @@ -220,9 +227,11 @@ direction; `off` the mean distance to such an edge in % of the height, capped at share that is on. The edges themselves are not returned and not kept: they are computed on each call. The hiding test's sight line stops short of each point by a thousandth (`HIDE`) of the diagonal of the edge's own -object, so that the edge's own faces do not hide it. A surface of another object nearer the edge than that hides -it when it stands further off than a thousandth of its own diagonal: the margin is the smaller of the two objects', -whatever else the scene holds. A strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, 1 and +piece, the connected part of its mesh that it lies on, so that the edge's own faces do not hide it: a box joined +into one mesh with a ground 200 times its size keeps the box's margin. A surface nearer the edge than that hides +it when it stands further off than a thousandth of the diagonal of the object it belongs to, measured whole: the +margin is the smaller of the two, whatever else the scene holds. A greeble modelled into its hull's own connected +surface has the hull's margin, and a surface nearer it than a thousandth of the hull does not hide it. A strip 0.3% of a box's diagonal in front of an edge hides it at scales 0.01, 1 and 100, and with a ground 20 or 40 times the box among the meshes read; chips a fortieth of a box hide its edge from 0.05% of its diagonal. Past the own object's margin the first surface met decides. Edges read true from cameras to about 20000 diagonals off, where the ray's own rounding reaches the margin. The action writes nothing to the scene (its row says `changesScene` @@ -243,7 +252,7 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane -out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched, kink +out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched, skipped cage = core.cage_through(out["crease"]) # the column whose built crease passes through it score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution diff --git a/surfaces/blender/tests/live/reference.result.json b/surfaces/blender/tests/live/reference.result.json index 55664b6..757834d 100644 --- a/surfaces/blender/tests/live/reference.result.json +++ b/surfaces/blender/tests/live/reference.result.json @@ -12,7 +12,9 @@ "brokkr_mesh_polish.scrub_markings", "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", - "brokkr_reference.solve_camera" + "brokkr_reference.solve_camera", + "brokkr_reference.lift_pair", + "brokkr_reference.flow_score" ] }, { @@ -119,13 +121,15 @@ "brokkr_mesh_polish.scrub_markings", "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", - "brokkr_reference.solve_camera" + "brokkr_reference.solve_camera", + "brokkr_reference.lift_pair", + "brokkr_reference.flow_score" ], "record": { "lens": 50.02266319807241, "lens_band": [ - 50.02266319807241, - 50.02266319807241 + 45.26237741142627, + 61.09781880064287 ], "lens_at_bound": null, "rms": 0.03555833513434369, diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_lift.py index 2c453f1..f16031a 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_lift.py @@ -13,7 +13,8 @@ core.crease_run against Blender's own subdivision. times over: each reads the hidden edge as seen. O4, no margin at all, loses seen edges to their own faces here and at the first box). The margin is the objects' own: a box over a ground 20 and 40 times its size, a small box over a ground behind a long strip (O7, a share of the largest mesh - read), two chips before a large box (O9, no second cast). Cameras 30 and 144 diagonals off + read), two chips before a large box (O9, no second cast); a box, a ground and a strip joined + into one mesh, where the margin is the box's own connected piece's (O10, the whole mesh's). Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours at 144) blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- @@ -145,8 +146,8 @@ try: 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 + check("lift_pair: accepted, 24 points on the crease within 1 mm, on the frame's -x side, none ambiguous, skipped 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["skipped"] == [] 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", @@ -270,6 +271,20 @@ try: walled = front(staged, line, {}) check(f"a box {2 * half:g} across over a ground {ground:g} across, every mesh read: its front edge is seen, and a strip 1% of the box's diagonal in front hides it " f"(a margin of the ground's is {1e-3 * ground * math.sqrt(2.0) / (0.01 * DIAGONAL * half):.1f} times the gap)", bare == (1.0, 3, 6) and walled == (0.0, 2, 6), [bare, walled]) + # the box, the ground and the strip joined into one mesh: the margin is the box's own piece's (O10, the whole mesh's diagonal, reads on 1: the ground's margin is 16 times the gap) + staged, edge, line = stage(0.05, 20.0) + screen(staged, "Wall", edge.mean(0), 0.01 * DIAGONAL * 0.05, 0.02, 0.15) + bm = bmesh.new() + for obj in [o for o in bpy.data.objects if o.type == "MESH"]: + bm.from_mesh(obj.data) + bpy.data.objects.remove(obj) + mesh = bpy.data.meshes.new("Joined") + bm.to_mesh(mesh) + bm.free() + scene.collection.objects.link(bpy.data.objects.new("Joined", mesh)) + bpy.context.view_layer.update() + walled = front(staged, line, {}) + check("a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)", walled[0] == 0.0, walled) # a small box's edge behind a strip far longer than the box, over a ground: the margin is the box's, not the strip's or the ground's (O7, a share of the largest mesh read, reads on 1) staged, edge, line = stage(0.05, 4.0) gap = math.sqrt(1e-3 * DIAGONAL * 0.05 * 1e-3 * math.hypot(0.02, 4.0)) # the geometric mean of the box's margin and the strip's, 4.8 from each diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_lift.result.json index e80de0e..2cad035 100644 --- a/surfaces/blender/tests/live/reference_lift.result.json +++ b/surfaces/blender/tests/live/reference_lift.result.json @@ -23,7 +23,7 @@ "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", + "name": "lift_pair: accepted, 24 points on the crease within 1 mm, on the frame's -x side, none ambiguous, skipped or unmatched, no object made", "ok": true, "detail": [ "Operator brokkr_reference.lift_pair finished.", @@ -299,6 +299,15 @@ ] ] }, + { + "name": "a box 0.1 across, a ground 20 across and a strip 1% of the box's diagonal in front of the box's edge, all one mesh: hidden, the margin is the edge's own connected piece's (O10 reads on 1)", + "ok": true, + "detail": [ + 0.0, + 2, + 6 + ] + }, { "name": "a box 0.1 across over a ground 4 across, with a strip 4 long standing between the two margins in front of its edge: hidden, the margin is the smaller object's (O7 reads on 1)", "ok": true, -- 2.47.3 From 31f12227037ed58e9bda7114c7e4be910f1b9bb2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 00:30:57 +0100 Subject: [PATCH 11/13] tests/live/reference_lift.py: the header's mutant list rewrapped Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/tests/live/reference_lift.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_lift.py index f16031a..3798e5e 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_lift.py @@ -14,8 +14,9 @@ core.crease_run against Blender's own subdivision. own faces here and at the first box). The margin is the objects' own: a box over a ground 20 and 40 times its size, a small box over a ground behind a long strip (O7, a share of the largest mesh read), two chips before a large box (O9, no second cast); a box, a ground and a strip joined - into one mesh, where the margin is the box's own connected piece's (O10, the whole mesh's). Cameras 30 and 144 diagonals off - still read every edge (O5, HIDE at 1e-6, loses four contours at 144) + into one mesh, where the margin is the box's own connected piece's (O10, the whole mesh's). + Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours + at 144) blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- -- 2.47.3 From 4fcd97905f2ea9855da829a28fafb49645fa46e4 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 03:58:23 +0100 Subject: [PATCH 12/13] brokkr_reference: pair, lift_pair and the lift helpers deleted; the package solves cameras and scores lines Ruling aetheria-release:ruling:lift-pair-held-for-redesign, cut_spec cut-reference-lift.r2. Subtraction only: core.pair, on_plane, cage_through, drawn_off, matrix, extended, _bend, _smoothest, MIRROR, SKIP, TURN, SHARE, the lift_pair operator and action row, their tests and docs. solve, flow_score, built_edges, along, crease_run and the parsers are unchanged. tests/live/reference_lift.py is tests/live/reference_flow.py. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 67 +---- .../brokkr_reference/brokkr_actions.json | 69 ----- surfaces/blender/brokkr_reference/core.py | 154 +----------- surfaces/blender/docs/reference.md | 86 +------ .../{reference_lift.py => reference_flow.py} | 52 +--- ...result.json => reference_flow.result.json} | 0 surfaces/blender/tests/test_reference.py | 235 +----------------- 7 files changed, 35 insertions(+), 628 deletions(-) rename surfaces/blender/tests/live/{reference_lift.py => reference_flow.py} (78%) rename surfaces/blender/tests/live/{reference_lift.result.json => reference_flow.result.json} (100%) diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index 2cd7956..4f93a0b 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -1,6 +1,5 @@ -"""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. +"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points, +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 @@ -8,10 +7,9 @@ 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 (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. +core.camera_of reads one back (flow_score takes 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 and scores. 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."} @@ -176,59 +174,6 @@ def built_edges(context, cam, objects, angle): 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) - try: - out = core.pair(cam, F, a, b, n=self.samples, extend=self.extend) - except core.ReferenceFitError as refusal: - raise Refused(str(refusal)) from None - 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""" @@ -259,7 +204,7 @@ class BROKKR_REFERENCE_OT_flow_score(PolishOperator): "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) +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index a2cc046..9bfe98f 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -81,75 +81,6 @@ } ] }, - { - "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, the points skipped, 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).", diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 41dc110..f5b7fe4 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -25,15 +25,10 @@ focal length trade against each other (a dolly zoom), and "lens_band" says how f in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders 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. +A traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-to-world matrix. - 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 @@ -49,9 +44,6 @@ BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple o STEP = 0.1 # the band is walked in steps of this in log f FINE = 1.0 # pixels: no mark is placed truer than this, so the band is never judged against a smaller error (exact marks fit every lens of a flat view to 1e-6 px and would call one of them best) PLANAR = 0.12 # marks thinner than this share of their spread (their planarity) are near a plane: a band of theirs that is open at one end of LENS_MM is reported open at both. The geometric mean of 0.041, a panel with relief whose band does open at one end, and 0.36, marks with depth: separation 2.9 each side (tests/test_reference.py) -SKIP = 2.8 # pair: a point that met line b more than once may be given no crossing, at the cost of this many times the crease's median turn. On 189 exact doubled-back strokes 1.25 to 7 lift every one exactly with one point skipped in 15; 1.0 and 8 lift some wrong: the geometric mean, 2.8 each side (read with TURN out of the way, tests/test_reference.py) -TURN = 0.061 # radians: the median turn is never read as less than this, so a crease of straight runs (median turn 0) does not skip for nothing. The geometric mean of 0.0496, under which a cornered crease drops the points between two of its corners, and 0.0749, over which a wrong crossing of a gentle crease (median turn 0.025) is cheaper than its skip: separation 1.23 each side -SHARE = 0.24 # pair refuses a lift that skips more than this share of the points that met line b, and never skips more than this share in a row. The geometric mean of 4 of 23, the most skipped on 11340 noisy doubled-back strokes, and 8 of 24, a scribbled line b: separation 1.38 each side DECIDED = 1.57 # a lens is determined when its band is inside LENS_MM and spans no more than this factor. A band's span is a whole number of STEPs: this is the geometric mean of four steps (1.49, the widest that marks with depth 3 px off read) and five (1.65). An exception to lodur:ruling:deterministic-bound-margin: the two readings are one STEP apart, 1.105, and readings quantised in STEPs have no pair 1.2 apart with nothing between; a host that moves a band by a step fails the span assertion in tests/test_reference.py MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead QUARTER = math.pi / 2 @@ -374,16 +366,7 @@ 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] +# --- traced lines and built edges ------------------------------------------------------------------------------------- def resampled(points, n): @@ -394,125 +377,6 @@ def resampled(points, 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. Refuses one whose first or last point is - given twice.""" - 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] - if not (head.any() and tail.any()): - raise ReferenceFitError(f"a line to run on past its ends repeats its {'last' if head.any() else 'first'} point, so that end has no direction (line b of a pair is run on): drop the repeated point") - return np.vstack([p[0] + head / np.linalg.norm(head) * by * length, p, p[-1] + tail / np.linalg.norm(tail) * by * length]) - - -def _bend(X0, X1, X2): - """The turn, in radians, of a crease that runs X0, X1, X2 (three numbers each); a half turn where it stands - still. Plain arithmetic: _smoothest reads it a million times on a long fold.""" - u, v = (X1[0] - X0[0], X1[1] - X0[1], X1[2] - X0[2]), (X2[0] - X1[0], X2[1] - X1[1], X2[2] - X1[2]) - along = math.sqrt((u[0] * u[0] + u[1] * u[1] + u[2] * u[2]) * (v[0] * v[0] + v[1] * v[1] + v[2] * v[2])) - return math.acos(max(-1.0, min(1.0, (u[0] * v[0] + u[1] * v[1] + u[2] * v[2]) / along))) if along > 1e-24 else math.pi - - -def _smoothest(candidates, skip=None, run=0): - """One candidate per point, chosen together: the choice whose curve turns least in all (the sum of _bend over - every three taken points in a row), found by dynamic programming over pairs of neighbouring taken points, so - no point is settled before the points after it are read. With `skip` (radians) a point that has more than one - candidate may take none, at that cost, up to `run` such points in a row: the turn is then read across the gap, - over the points that are taken, so a skip cannot hide a turn. Returns the index taken at each point, None where it is skipped; ties go to the - earlier candidate and to the choice reached first.""" - m = len(candidates) - C = [[tuple(float(v) for v in X) for X in options] for options in candidates] - free = [skip is not None and len(options) > 1 for options in C] - - best = {} # (t, k, the taken point before it, its candidate) -> (cost, the state before) - for t in range(min(m, run + 1)): - for k in range(len(C[t])): - best[t, k, -1, -1] = (skip * t if t else 0.0, None) - if not free[t]: - break - end, least = None, math.inf - for t in range(m): - for state in [s for s in best if s[0] == t]: - cost, _ = best[state] - _, k, tp, kp = state - if m - 1 - t <= run and all(free[t + 1:]) and cost + (skip or 0.0) * (m - 1 - t) < least: - end, least = state, cost + (skip or 0.0) * (m - 1 - t) - for t2 in range(t + 1, min(m, t + run + 2)): - for k2, X in enumerate(C[t2]): - total = cost + (skip * (t2 - t - 1) if t2 > t + 1 else 0.0) + (_bend(C[tp][kp], C[t][k], X) if tp >= 0 else 0.0) - if (t2, k2, t, k) not in best or total < best[t2, k2, t, k][0]: - best[t2, k2, t, k] = (total, state) - if not free[t2]: - break - taken = [None] * m - while end is not None: - taken[end[0]] = end[1] - end = best[end][1] - return taken - - -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; "skipped": the points of `a` (their indices among - its n) that met `b` more than once and were given no crossing, left out}. 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: the crossings are chosen together, as the choice whose crease turns least in all (_smoothest). That is - the true crease wherever every point's true crossing is among its crossings. Where one is not (the end of `a` - mirrors the very end of `b`, and only the doubled strokes are met) every crossing of that point kinks the - crease, and the point is skipped instead: a skip costs SKIP times the crease's median turn (the median of the - choice with no skips, never under TURN), and only a point with a choice can be skipped. A lift that skips more - than SHARE of the points it had crossings for is refused, and the choice never skips more than that in a row. - - 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) - fold = lambda X: np.array([abs(X[0]), X[1], X[2]]) # noqa: E731 - at = [i for i, lifts in enumerate(found) if lifts] - folded = [[fold(X) for X in found[i]] for i in at] - taken = _smoothest(folded) - if any(len(options) > 1 for options in folded) and len(at) > 2: - whole = [folded[t][k] for t, k in enumerate(taken)] - usual = float(np.median([_bend(*whole[t - 2:t + 1]) for t in range(2, len(whole))])) - taken = _smoothest(folded, SKIP * max(usual, TURN), int(SHARE * len(at))) - skipped = [i for i, k in zip(at, taken) if k is None] - if len(skipped) > SHARE * len(at): - raise ReferenceFitError(f"line b doubles back and {len(skipped)} of the {len(at)} points of line a that meet it have no crossing that fits the crease (points {skipped}; over {SHARE:g} of them is refused). Draw line b as one stroke that does not run beside itself") - lifted = [found[i][k] for i, k in zip(at, taken) if k 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": sum(1 for lifts in found if len(lifts) > 1), "skipped": skipped, "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) @@ -535,15 +399,6 @@ def crease_run(points): 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) @@ -552,11 +407,6 @@ def _off(points, line): 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 diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index 9ae88d5..93bdc69 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -1,18 +1,18 @@ -# Reference views: the camera a picture was drawn through, and lines lifted through it +# Reference views: the camera a picture was drawn through, and traced lines scored against the build `surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet, a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through -it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene. +it lays over the image pixel for pixel and a line traced on the image can be scored against the build's edges. It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish` first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the -three operators agents may run (`solve_camera`, `lift_pair`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may +two operators agents may run (`solve_camera`, `flow_score`); the arithmetic is `core.py` (numpy only, tested without Blender), which a script may import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's `hostResult`. -The package takes points and traced lines and gives cameras, creases and scores. The images, the marks on them, traces and masks belong to whoever +The package takes points and traced lines and gives cameras and scores. The images, the marks on them, traces and masks belong to whoever made them; nothing here opens an image. ## Conventions @@ -139,72 +139,6 @@ place, not about a lift made in the view's own frame. pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model). -## lift_pair: a crease from two traced lines - -A line traced on the view is two numbers a point; a crease in the scene is three. `lift_pair` takes the third from -symmetry: two traced lines that are one crease and its mirror image, on a part symmetric about the x = 0 plane of -its frame. A point of one line and its mirror on the other 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. - -| field | | -| --- | --- | -| `camera_name` | the camera object the view is seen through; `solve_camera` stands one | -| `box` | `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 | -| `frame_name` | an object whose `matrix_world` is the part's frame; its x = 0 is the mirror plane | -| `line_a`, `line_b` | `u,v u,v ...`, the crease as traced on one side and its mirror image on the other | -| `samples` | points lifted, evenly along `line_a` (default 24) | -| `extend` | `line_b` is run on straight past its ends by this share of its length (default 0.2), to find mirrors for the ends of `line_a` | -| `curve_name` | a poly curve to create or update along the crease on `line_a`'s side, parented to the frame; absent draws none | - -The report: `crease` (`[[x, y, z], ...]` in the frame, x >= 0, in the order of `line_a`), `side` (+1 or -1: the side -of the frame `line_a` is on), `unmatched` (points of `line_a` whose line to the vanishing point never meets -`line_b`; they are left out), `ambiguous` (points whose line meets `line_b` more than once), `skipped`, `cage`, `miss` and -`curve`. The camera is read back from the object (`core.camera_of`): a perspective camera with a horizontal sensor -fit. The curve is for the eye; the report is the truth. - -Every lifted point draws back onto both traced lines exactly, so the drawing cannot tell two crossings apart. Where -a line folds back, the crease can: the crossings of all the points are chosen together, as the choice whose lifted -crease turns least in all (the sum of its turns at each point, by dynamic programming), so no point is settled -before the points after it are read. Wherever each point's true crossing is among its crossings, that is the true -crease. Where it is not (most often the last point of `line_a`, whose mirror is the very end of `line_b`, meeting -only the doubled strokes) every crossing of that point kinks the crease, and the point is given none: it is left -out of `crease` and named in `skipped`, the indices of such points among the `samples` of `line_a`. Only a point -with more than one crossing can be skipped. A skip costs 2.8 (`core.SKIP`) times the crease's median turn, and the -turn is read across the gap, so a skip cannot hide a turn. The median is never read as less than 0.061 radians -(`core.TURN`), so a crease of straight runs and corners, whose median turn is nothing, lifts whole. A lift that -skips more than 0.24 (`core.SHARE`) of the points that met `line_b` is refused, and no more than that are skipped -in a row: draw `line_b` as one stroke. - -On 189 exact strokes of `line_b` doubled back beside themselves (a tenth to nine tenths of the crease, three -views) every one lifts exactly, none refused; 15, all on the view 10 degrees above the crease, skip their last -point. On hand-traced lines (the same folds on traces 0.25 to 3 px off: twelve jittered points, thirty, and a slow -wobble; 11340 strokes) none is refused, 1824 skip a point or more, at most 4 of 23, and 475 lift more than 5 mm -worse than the same trace unfolded, 131 of them more than 20 mm: 21 of the 3780 wobbled, 130 of the twelve-point -and 324 of the thirty-point, where a 1 px tremor already stands in for a wrong crossing. A trace's own wobble -turns the crease as much as a wrong crossing does, and no reading of the lift tells them apart: `skipped` says -what was left out, not that the rest is right. A scribbled `line_b` can lift 0.07 m off with nothing skipped and -takes seconds. A lift with no ambiguous -point has no choice anywhere and is never refused. A line whose first or last point is given twice is refused: that end of -`line_b` has no direction to run on in. - -`cage` is the column of cage points whose hard crease, as Blender's Subdivision modifier builds it at one level, -passes through the lifted crease at the cage's own points (`core.cage_through`, `core.crease_run`). The built -crease is not the cage: with Limit Surface on (the modifier's default, and what kitbash shells use) a cage point is -built at (1, 4, 1) / 6 of itself and its neighbours along the column, the ends staying; a cage laid on the lifted -points would be built inside every bend. With Limit Surface off the weights differ and `cage` is not that -column. `miss` is the mean distance in pixels from where the camera draws that built crease to each traced line -(`line_b` run on by `extend`). - -How far to trust it: the lift is as sure as the frame and as the angle between the line of sight and the mirror -plane. Seen nearly along the mirror plane the two sight lines are nearly parallel, and a degree of the frame's turn -moves the crease a long way in depth. On twelve-point traces 1.5 px off, three views of a 2 m crease lifted within -0.6% of its length. On the Orchid's concept render (a hand trace of the upper petals' inboard edges, eight hand -marks, the frame fitted to a generated mesh's own mirror plane, 34 degrees between sight and mirror plane) the -lifted creases stood a mean 0.9% and 1.7% of the hull's length from that mesh, 4% at worst, at a petal's tip, and -moved 0.6% between the ends of the lens band. A wrong frame is not reported: the lift cannot see it. - -One traced line with no mirror is lifted onto a plane of the frame by `core.on_plane` (no action). - ## flow_score: traced lines against built edges `flow_score` says how much of each traced line the build already carries as an edge. It reads the evaluated meshes @@ -215,7 +149,8 @@ by its winding does not count as seen, so a cage with flipped normals shows no c | field | | | --- | --- | -| `camera_name`, `box` | as for `lift_pair` | +| `camera_name` | the camera object the view is seen through (`solve_camera` stands one) | +| `box` | `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 | | `height` | the figure's height in the box's pixels; an edge within 1% of it is near. 0 (default) is the box's height | | `lines` | `tag: u,v u,v ...; tag: u,v u,v ...` | | `objects` | `name; name; ...`, the meshes whose edges are read; absent is every mesh the render shows. Everything the scene shows hides | @@ -252,14 +187,13 @@ cam = core.solve(world, pixels, box, model="auto") # dicts by name; the u_v = core.project(cam, points) # where it draws world points origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane -out = core.pair(cam, frame, line_a, line_b) # crease, side, ambiguous, unmatched, skipped -cage = core.cage_through(out["crease"]) # the column whose built crease passes through it +run = core.crease_run(column) # the hard crease Blender builds from a cage column score = core.along(line, segments, height) # on, off, run against [u0, v0, u1, v1] segments params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution cam2 = core.camera_of(params, box) # and back ``` The tests are `tests/test_reference.py` (no Blender), `tests/live/reference.py` (a known scene rendered, solved -through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_lift.py` -(`crease_run` against Blender's own subdivision, a crease lifted through `lift_pair`, a box and a folded sheet -scored by `flow_score`; `reference_lift.result.json` is its last run). +through the action and rendered again; `reference.result.json` is its last run) and `tests/live/reference_flow.py` +(`crease_run` against Blender's own subdivision, a box and a folded sheet scored by `flow_score`; +`reference_flow.result.json` is its last run). diff --git a/surfaces/blender/tests/live/reference_lift.py b/surfaces/blender/tests/live/reference_flow.py similarity index 78% rename from surfaces/blender/tests/live/reference_lift.py rename to surfaces/blender/tests/live/reference_flow.py index 3798e5e..ad03265 100644 --- a/surfaces/blender/tests/live/reference_lift.py +++ b/surfaces/blender/tests/live/reference_flow.py @@ -1,10 +1,8 @@ -"""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. +"""Live proof, in a background Blender, of brokkr_reference.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 back edge 0 (it faces away, so it is never read), 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). Then the box alone at @@ -18,7 +16,7 @@ core.crease_run against Blender's own subdivision. Cameras 30 and 144 diagonals off still read every edge (O5, HIDE at 1e-6, loses four contours at 144) - blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_lift.py -- + blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_flow.py -- Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses without them). is an absolute path: it writes .result.json and exits 1 when a check failed. Not part @@ -64,7 +62,7 @@ for module in ("brokkr_mesh_polish", "brokkr_reference"): from brokkr_reference import core # noqa: E402 target = bt.BrokkrBlenderTarget(bpy) -target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-lift-live-")) +target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-flow-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]]} @@ -105,7 +103,7 @@ def traced(camera, points, scale=1.0, corner=(0.0, 0.0)): try: - check("host file admitted", not R["hostErrors"] and {"brokkr_reference.lift_pair", "brokkr_reference.flow_score"} <= set(R["hostRows"]), R["hostRows"]) + check("host file admitted", not R["hostErrors"] and "brokkr_reference.flow_score" in R["hostRows"], R["hostRows"]) scene = bpy.context.scene scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100 @@ -131,49 +129,13 @@ try: 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 --------------------- + # --- the camera every flow_score check below is seen through ------------------------------------------------------- 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, skipped 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["skipped"] == [] 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"), - ({"line_b": " ".join(traced(truth, world(-1)).split()[:1] * 2 + traced(truth, world(-1)).split()[1:])}, "repeats its first point")): - 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() @@ -216,7 +178,7 @@ try: """A box of half-width `half` standing on z = 0, alone or over a square ground `ground` across, and a camera: the first box's, scaled with the box, or one `far` box diagonals off with the lens grown to match. Returns the camera, the box's front edge, and its line as the camera draws it.""" - for obj in [o for o in bpy.data.objects if o.type in ("MESH", "CURVE")]: + for obj in [o for o in bpy.data.objects if o.type == "MESH"]: bpy.data.objects.remove(obj) name = f"Staged {half:g} {ground:g} {far:g}" staged = bpy.data.objects.new(name, bpy.data.cameras.new(name)) diff --git a/surfaces/blender/tests/live/reference_lift.result.json b/surfaces/blender/tests/live/reference_flow.result.json similarity index 100% rename from surfaces/blender/tests/live/reference_lift.result.json rename to surfaces/blender/tests/live/reference_flow.result.json diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index 2c7972a..56540c8 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -27,7 +27,6 @@ import re import sys import types import unittest -import unittest.mock from pathlib import Path SURFACE = Path(__file__).resolve().parents[1] @@ -221,15 +220,15 @@ class SolveTests(unittest.TestCase): core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs) self.addCleanup(setattr, core, "lm", lm) plane = np.c_[self.points[:, :2], np.zeros(13)] - on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) - square_on = on_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) + in_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist())) + square_on = in_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist())) line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist())) cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"), (({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"), ((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"), ((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"), ((line, self.pixels), {}, "world points lie on one line"), - (on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) + (in_plane, {"model": "free"}, "one plane, which does not decide the centre"), (in_plane, {"model": "free", "lens": 50.0}, "does not decide the centre")) for args, kwargs, said in cases: with self.assertRaises(core.ReferenceFitError) as caught: core.solve(*args, BOX, **kwargs) @@ -341,221 +340,17 @@ class SolveTests(unittest.TestCase): self.assertIn(said, str(refusal)) -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_smoothest_crossing, and the two after it - K1 no point skipped test_strokes_doubled_back_lift_exactly_with_a_point_skipped - K2, K3 SKIP 1.0 and 8 the same, where TURN is set to 0 - K5 a skip's turn not read across the gap the same - K4 a point with one crossing may be skipped test_a_cornered_crease_lifts_whole - T1, T2 TURN 0.04 and 0.09 the same; the doubled strokes - R1, R2 SHARE 0.15 and 0.4 test_a_scribbled_line_is_refused_by_its_share_of_skips - S1 a crease that stands still costs no turn test_a_crease_that_stands_still_is_a_half_turn - H1 a crossing snapped to line b's point before it test_a_hand_traced_pair_lifts_within_a_bound +class FlowTests(unittest.TestCase): + """The crease Blender builds from a cage column, the flow score and the line parsers. Mutants, each run once: 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, H1: twelve points a line, each 1.5 px off (a hand's trace). The worst of three views - reads 0.0122 m, 0.6% of the crease's 2.05 m; with each crossing snapped to the traced point before it - instead of taken where the lines cross (H1) 0.277 m. The bound is their geometric mean, separation 4.8 - each side.""" - 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.058) - - def test_a_folded_line_takes_the_smoothest_crossing(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 8.9e-16 m off the true crease, the first crossing kept (N2) - 0.00892 m: the bound is their geometric mean, separation 3.2e6 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"]), 2.8e-9) - - def test_a_fold_at_the_far_end_is_settled(self): - """pair-folded-line: line b's last two fifths are drawn three times over, out, back and out again beside - themselves, so the last points of `a` meet it more than once and have no lifted point after them. Shipped - reads 7.2e-16 m and the first crossing kept (N2) 0.0302 m: the bound is their geometric mean, separation - 6.5e6 each side.""" - cam = self.cams[0] - b = self.traced(cam, -1) - v = b[-1] - b[1199] - d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * 0.06 * np.ptp(b, axis=0).max() - out = core.pair(cam, FRAME, self.traced(cam), np.vstack([b[:1199], b[1199:] + d, b[:1198:-1] + 2 * d, b[1199:]]), extend=0.0) - self.assertEqual((out["ambiguous"], out["unmatched"], len(out["crease"])), (10, 2, 22)) - self.assertLess(self.off(out["crease"]), 4.7e-9) - - def doubled(self): - """189 strokes of line b doubled back beside themselves: seven stretches of the crease, three offsets, the - true stroke first, between or last, three views.""" - n = len(self.truth) - for view, cam in enumerate(self.cams): - a, b = self.traced(cam), self.traced(cam, -1) - for start, end in ((0.1, 0.3), (0.3, 0.5), (0.3, 0.7), (0.1, 0.9), (0.5, 0.8), (0.0, 0.4), (0.6, 1.0)): - i0, i1 = int(start * (n - 1)), int(end * (n - 1)) - v = b[i1] - b[i0] - out, back = b[i0:i1 + 1], b[i1:i0 - 1 if i0 else None:-1] - for offset in (0.01, 0.03, 0.06): - d = np.array([-v[1], v[0]]) / np.linalg.norm(v) * offset * np.ptp(b, axis=0).max() - for which, line in (("first", np.vstack([b[:i1 + 1], back + d, out + 2 * d, b[i1 + 1:]])), ("last", np.vstack([b[:i0], out + d, back + 2 * d, b[i0:]])), - ("between", np.vstack([b[:i0], out + d, back + 2 * d, out, b[i1 + 1:]]))): - yield (view, start, end, offset, which), cam, a, line - - def test_strokes_doubled_back_lift_exactly_with_a_point_skipped(self): - """pair-global-choice, aetheria-release:ruling:lift-skips-points-not-strokes: `extend` 0. The crossings are - chosen together, so every stroke whose points all have their true crossing lifts exactly with nothing - skipped: 174. In the other 15, all on the view 10 degrees above the crease, the last point of `a` meets - only the doubled strokes (its mirror is line b's very end); that point is skipped, it alone, and the other - 23 lift exactly: worst of the 189, 9.7e-16 m, none refused. Read twice: as shipped, where the crease's - median turn (0.025) is under TURN and a skip costs SKIP x TURN, 6.8 medians; and with TURN at 0, where it - costs SKIP medians and SKIP's own readings show: 1.25 to 7 read the same, 1.0 (K2) skips points that had - their true crossing and lifts strokes wrong, 0.008 m off, 8 (K3) keeps a wrong crossing, 0.018 m off: 2.8 - is the geometric mean, 2.8 each side. As shipped, TURN up to 0.0749 reads the same and 0.09 (T2) lifts - strokes wrong, 0.018 m off. K1 (no skip) lifts the 15 wrong; K5 (the turn not read across a skipped - point) skips where nothing is wrong. The lift bound is the folded-line test's.""" - for turn in (core.TURN, 0.0): - with unittest.mock.patch.object(core, "TURN", turn): - wrong, skipped = [], [] - for key, cam, a, line in self.doubled(): - lifted = core.pair(cam, FRAME, a, line, extend=0.0) - if self.off(lifted["crease"]) > 2.8e-9 or len(lifted["crease"]) + len(lifted["skipped"]) + lifted["unmatched"] != 24: - wrong.append((key, self.off(lifted["crease"]), lifted["skipped"])) - if lifted["skipped"]: - skipped.append((key[0], lifted["skipped"])) - self.assertEqual(wrong, [], turn) - self.assertEqual(skipped, [(2, [23])] * 15, turn) - - CORNERS = [[0.4, -1.0, 0.5], [0.7, -0.35, 0.55], [0.35, 0.15, 0.75], [0.6, 0.6, 0.7], [0.4, 1.0, 0.8]] - - def test_a_cornered_crease_lifts_whole(self): - """kink-refuses-exact-cornered-crease: a crease of four straight runs, corners of 1.0 to 1.2 radians, traced - exactly, no fold. Its median turn is 0 (1.5e-8), and at the first view three points between two corners - meet line b twice. All 24 lift at each view, 1.2e-15 m off, nothing skipped: the median is read as TURN. - With TURN under 0.0496 (T1 0.04) the three are skipped, which saves the 0.35 radians of the stretch - between the corners; K4 (a point with one crossing may be skipped) skips here too.""" - V = np.array(self.CORNERS) - truth = np.vstack([np.linspace(V[i], V[i + 1], 500, endpoint=False) for i in range(4)] + [V[-1:]]) - for cam, ambiguous in zip(self.cams, (3, 0, 0)): - out = core.pair(cam, FRAME, core.seen(cam, FRAME, truth), core.seen(cam, FRAME, truth * [-1, 1, 1])) - self.assertEqual((len(out["crease"]), out["ambiguous"], out["skipped"], out["unmatched"]), (24, ambiguous, [], 0)) - self.assertLess(float(core._off(np.array(out["crease"]), truth).max()), 1e-6) - - def test_a_scribbled_line_is_refused_by_its_share_of_skips(self): - """SHARE: line b scribbled over (six loops, 12% of its extent across) on the second view. Over the middle - two fifths 4 of the 23 points that meet it are skipped, 0.174, and the lift is given, with the four named; - over the whole line 8 of 24, 0.333, and it is refused. 4 of 23 is also the most skipped in 11340 noisy - doubled-back strokes (cut_report h4). SHARE 0.24 is the geometric mean, 1.38 each side: R1 (0.15) refuses - the first, R2 (0.4) gives the second. The share says how much of the stroke was left out, not that what - was kept is right: the first lift is 0.066 m off, the scribble's own width.""" - cam, n = self.cams[1], len(self.truth) - a, b = self.traced(cam), self.traced(cam, -1) - - def scribbled(start, end): - i0, i1 = int(start * (n - 1)), int(end * (n - 1)) - t = np.linspace(0, 1, i1 - i0 + 1) - d = np.gradient(b, axis=0)[i0:i1 + 1] - d /= np.linalg.norm(d, axis=1)[:, None] - wide = 0.12 * np.ptp(b, axis=0).max() - line = b.copy() - line[i0:i1 + 1] += np.stack([-d[:, 1], d[:, 0]], 1) * ((2 * np.abs((t * 6) % 1 - 0.5) - 0.5) * wide)[:, None] + d * (np.sin(12 * np.pi * t) * wide)[:, None] - return line - - out = core.pair(cam, FRAME, a, scribbled(0.3, 0.7), extend=0.0) - self.assertEqual((len(out["skipped"]), len(out["crease"]), out["unmatched"]), (4, 19, 1)) - with self.assertRaises(core.ReferenceFitError) as caught: - core.pair(cam, FRAME, a, scribbled(0.0, 1.0), extend=0.0) - self.assertIn("8 of the 24 points", str(caught.exception)) - - def test_a_crease_that_stands_still_is_a_half_turn(self): - """S1: two crossings that lift to one place are not a straight run. A retraced line a does lift a point - twice.""" - X, Y = np.array([0.4, 0.0, 0.5]), np.array([0.5, 0.2, 0.5]) - self.assertEqual(core._bend(X, X, Y), math.pi) - self.assertEqual(core._bend(X, Y, Y), math.pi) - self.assertAlmostEqual(core._bend(X, Y, 2 * Y - X), 0.0, delta=1e-7) - self.assertAlmostEqual(core._bend(X, Y, X), math.pi, delta=1e-7) - - def test_a_line_that_repeats_an_end_point_is_refused(self): - """A doubled click at an end of line b leaves that end no direction to run on in: refused by name (it was a - LinAlgError out of the triangulation). A repeat inside either line, or at an end of line a, is harmless.""" - cam = self.cams[0] - a, b = self.traced(cam), self.traced(cam, -1) - for line, which, extend in ((np.vstack([b[:1], b]), "first", 0.2), (np.vstack([b, b[-1:]]), "last", 0.2), (np.vstack([b[:1], b]), "first", 0.0)): - with self.assertRaises(core.ReferenceFitError) as caught: - core.pair(cam, FRAME, a, line, extend=extend) - self.assertIn(f"repeats its {which} point", str(caught.exception)) - for one, other in ((np.vstack([a[:1], a]), b), (a, np.vstack([b[:500], b[500:501], b[500:]]))): - out = core.pair(cam, FRAME, one, other) - self.assertEqual(len(out["crease"]), 24) - self.assertLess(self.off(out["crease"]), 1e-6) - - 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) + N5 (back-facing creases counted) is claimed by tests/live/reference_flow.py.""" 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 + [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_flow.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 @@ -565,13 +360,6 @@ class LiftTests(unittest.TestCase): 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]] @@ -656,8 +444,8 @@ 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") - 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) + self.assertEqual([row["name"] for row in self.document["actions"]], ["brokkr_reference.solve_camera", "brokkr_reference.flow_score"]) + self.assertEqual(source.count("bl_idname = "), 2) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -673,12 +461,9 @@ 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})): + for intent, bad in ((flow, {"angle": 0}), (flow, {"lines": ""}), (flow, {"camera_name": "x" * 64})): with self.assertRaises(at.IntentInvalid): at.validate({**intent, **bad}, self.host) -- 2.47.3 From 7c5e77b37d1faa236c416fe71092b4929241968e Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 03:58:58 +0100 Subject: [PATCH 13/13] tests/live: reference_flow and reference rerun in Blender 5.3 after the lift deletion Both pass; every surviving check's detail is unchanged but the host rows, which no longer list lift_pair. Co-Authored-By: Claude Fable 5.2 --- .../blender/tests/live/reference.result.json | 2 - .../tests/live/reference_flow.result.json | 72 ------------------- 2 files changed, 74 deletions(-) diff --git a/surfaces/blender/tests/live/reference.result.json b/surfaces/blender/tests/live/reference.result.json index 757834d..cbe1785 100644 --- a/surfaces/blender/tests/live/reference.result.json +++ b/surfaces/blender/tests/live/reference.result.json @@ -13,7 +13,6 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", "brokkr_reference.solve_camera", - "brokkr_reference.lift_pair", "brokkr_reference.flow_score" ] }, @@ -122,7 +121,6 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", "brokkr_reference.solve_camera", - "brokkr_reference.lift_pair", "brokkr_reference.flow_score" ], "record": { diff --git a/surfaces/blender/tests/live/reference_flow.result.json b/surfaces/blender/tests/live/reference_flow.result.json index 2cad035..e382f40 100644 --- a/surfaces/blender/tests/live/reference_flow.result.json +++ b/surfaces/blender/tests/live/reference_flow.result.json @@ -13,7 +13,6 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", "brokkr_reference.solve_camera", - "brokkr_reference.lift_pair", "brokkr_reference.flow_score" ] }, @@ -22,68 +21,6 @@ "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, skipped 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": "lift_pair refuses line_b: failed, saying 'repeats its first point'", - "ok": true, - "detail": "Error: a line to run on past its ends repeats its first point, so that end has no direction (line b of a pair is run on): drop the repeated point" - }, { "name": "fixture: both of the sheet's faces look away from the camera, and their fold is 90 degrees or so", "ok": true, @@ -361,7 +298,6 @@ "brokkr_mesh_polish.cut_parts", "brokkr_mesh_polish.pick", "brokkr_reference.solve_camera", - "brokkr_reference.lift_pair", "brokkr_reference.flow_score" ], "BUILT": [ @@ -411,14 +347,6 @@ 4.0 ] ], - "lift": { - "off": 9.701819854982612e-06, - "through": 8.333333333387927e-06, - "miss": { - "line_a": 0.004, - "line_b": 0.001 - } - }, "flow": { "lines": { "front": { -- 2.47.3