From e41d51282c0bbd7d9c9038554514c975821783f9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 08:54:52 +0100 Subject: [PATCH] brokkr_reference.block_plate: a plate's first free cage from traces naming two consecutive corners, solved by fit_runs with a plane and fairness for its prior (cut trace-block) fit_runs takes its prior as rows (A, b); fit_sheet passes none, which is the identity it had. triangulate, plate_sheet and block_plate after fit_sheet; the operator, its action row, docs/reference.md "block_plate", BlockTests and tests/fixtures/spectre_plates.json. Where the spec was silent or could not be built as written: - a mirrored plate's centre stands in the half, not on x = 0: a face of three seam points is its own reflection and brokkr_kitbash's parser refuses it. The seam's sides keep their centre faces and lose only the skirt. - views under 9.7 degrees apart (the geometric mean of 19 and 5) do not start a corner; that is what refuses a 5 degree plate with no plane. - block_plate takes the cage's parser as an argument: core imports nothing. - SPECTRE's traces close no outline; the fixture closes them with edges of the fitted cage, marked. Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/brokkr_reference/__init__.py | 60 ++- .../brokkr_reference/brokkr_actions.json | 57 +++ surfaces/blender/brokkr_reference/core.py | 350 +++++++++++++++++- surfaces/blender/docs/reference.md | 69 ++++ .../tests/fixtures/spectre_plates.json | 1 + surfaces/blender/tests/test_reference.py | 246 +++++++++++- 6 files changed, 776 insertions(+), 7 deletions(-) create mode 100644 surfaces/blender/tests/fixtures/spectre_plates.json diff --git a/surfaces/blender/brokkr_reference/__init__.py b/surfaces/blender/brokkr_reference/__init__.py index d106882..7a3b619 100644 --- a/surfaces/blender/brokkr_reference/__init__.py +++ b/surfaces/blender/brokkr_reference/__init__.py @@ -14,6 +14,8 @@ cameras, scores and a fitted sheet. The edges flow_score reads are computed on e fit_shell reads a shell's request through brokkr_kitbash (the sheet's one parser) and returns a sheet; it writes nothing. brokkr_kitbash.shell is the cage's one writer: the caller applies the fitted sheet with it. +block_plate returns a plate's first sheet from traces of its outline, checked by the same parser, and the traces as +fit_shell takes them; it writes nothing either. """ 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."} @@ -263,7 +265,63 @@ class BROKKR_REFERENCE_OT_fit_shell(PolishOperator): return {"object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} -classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell) +class BROKKR_REFERENCE_OT_block_plate(PolishOperator): + """Block a plate's first free cage from traces of its outline through solved cameras, each trace naming the two + corners it runs between, and say what decided each corner's depth; nothing is written""" + bl_idname = "brokkr_reference.block_plate" + bl_label = "Block Plate From Traces" + frame_object: bpy.props.StringProperty(name="Frame", maxlen=63, description="An empty or object, unscaled, whose place in the world is the plate's frame") + plate: bpy.props.StringProperty(name="Plate", maxlen=2000, description="JSON {corners: [names in the outline's order], mirror, seam: [corners on x = 0]}") + traces: bpy.props.StringProperty(name="Traces", maxlen=12000, description="A JSON array of {camera, box, frame, from, to, side, line: [[u, v], ...]}") + plane: bpy.props.StringProperty(name="Plane", maxlen=200, description="'' for the plane through the corners the views decide, or 'x,y,z; nx,ny,nz' in the frame") + share: bpy.props.FloatProperty(name="Share", default=0.1, min=0.0009, max=10.0, description="A crown point this share of the plate's extent off the plane costs what one pixel of miss does") + tol: bpy.props.FloatProperty(name="Tolerance", default=core.TOL, min=0.09, max=100.0, description="Pixels: nine tenths of every trace must lie this near its built side, or the side gains a point") + + def work(self, context): + try: + import brokkr_kitbash + except ImportError as error: + raise Refused(f"block_plate needs the brokkr_kitbash add-on beside this one ({error}).") from None + obj = bpy.data.objects.get(self.frame_object) + if obj is None or obj.name not in context.scene.objects: + raise Refused(f"frame_object {self.frame_object!r} is not an object of this scene.") + if max(abs(v - 1.0) for v in obj.matrix_world.to_scale()) > 1e-6: + raise Refused(f"frame_object {obj.name!r} is scaled {tuple(round(v, 6) for v in obj.matrix_world.to_scale())}: a plate is in metres of its frame. Apply or clear the scale.") + try: + plate, traces = json.loads(self.plate), json.loads(self.traces) + except ValueError as error: + raise Refused(f"plate and traces must be JSON ({error}).") from None + if not isinstance(traces, list) or not all(isinstance(trace, dict) for trace in traces): + raise Refused("traces must be a JSON array of objects {camera, box, frame, from, to, side, line}.") + plane = None + if self.plane.strip(): + halves = self.plane.split(";") + try: + if len(halves) != 2: + raise core.ReferenceFitError(f"plane {self.plane.strip()!r} is not 'x,y,z; nx,ny,nz'") + plane = {"point": core.numbers(halves[0], 3, "plane's point"), "normal": core.numbers(halves[1], 3, "plane's normal")} + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}.") from None + own, views = [list(row) for row in obj.matrix_world], [] + for k, trace in enumerate(traces): + box = trace.get("box") + if box is not None and not (isinstance(box, list) and len(box) == 4 and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in box)): + raise Refused(f"traces[{k}].box must be [u0, v0, u1, v1], or absent for the render's own frame.") + if not isinstance(trace.get("camera"), str): + raise Refused(f"traces[{k}].camera must name a camera object.") + try: + views.append((record(context, trace["camera"], "" if box is None else ",".join(repr(float(v)) for v in box)), trace.get("frame") or own)) + except (Refused, core.ReferenceFitError) as refusal: + raise Refused(f"traces[{k}]: {refusal}") from None + started = time.perf_counter() + try: + out = core.block_plate(views, plate, traces, brokkr_kitbash.core.sheet, plane=plane, share=self.share, tol=self.tol) + except core.ReferenceFitError as refusal: + raise Refused(f"{refusal}. Nothing changed.") from None + return {"frame_object": obj.name, **out, "seconds": round(time.perf_counter() - started, 3)} + + +classes = (BROKKR_REFERENCE_OT_solve_camera, BROKKR_REFERENCE_OT_flow_score, BROKKR_REFERENCE_OT_fit_shell, BROKKR_REFERENCE_OT_block_plate) def register(): diff --git a/surfaces/blender/brokkr_reference/brokkr_actions.json b/surfaces/blender/brokkr_reference/brokkr_actions.json index a1d4856..38499c6 100644 --- a/surfaces/blender/brokkr_reference/brokkr_actions.json +++ b/surfaces/blender/brokkr_reference/brokkr_actions.json @@ -174,6 +174,63 @@ "doc": "pixels: nine tenths of every trace must lie this near its built run, or the fit is refused" } ] + }, + { + "name": "brokkr_reference.block_plate", + "doc": "Block a plate's first free cage from traces of its outline, each seen through a scene camera and naming the two consecutive corners it runs between: the only correspondence is a trace's ends to its corners. The crown (the corners and each side's points between) is solved until the sides as built draw on the traces; a side whose trace is not explained gains a point, up to 6. Depth comes from the views where two see a corner 9.7 degrees or more apart, from x = 0 for a mirrored plate's seam corners, and otherwise from a plane: the one given, or the one through the corners the views and the seam decide. Each corner says which (decided_by views, mirror or plane; views means the prior's share is under 0.2). A corner one view sees is refused when the plane stands over 66 degrees off that view. Returns the sheet for brokkr_kitbash.shell, checked by its parser, and fit_traces for brokkr_reference.fit_shell (left_out lists the traces fit_shell cannot state: another frame, or a partner's side -1). Writes nothing (docs/reference.md).", + "changesScene": true, + "editModeSafe": false, + "result": "brokkr_mesh_polish_result", + "fields": [ + { + "name": "frame_object", + "type": "string", + "required": true, + "minLength": 1, + "maxLength": 63, + "doc": "an empty or object, unscaled, whose place in the world is the plate's frame" + }, + { + "name": "plate", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 2000, + "doc": "JSON {corners: [names, in the outline's order], mirror: true or false, seam: [the corners on x = 0 of a mirrored plate, two or more next to each other]}; side i runs from corner i to corner i + 1 and is one hard crease" + }, + { + "name": "traces", + "type": "string", + "required": true, + "minLength": 2, + "maxLength": 12000, + "doc": "a JSON array of {camera, box, frame, from, to, side, line}: camera a camera object's name; box [u0,v0,u1,v1], its frame on the image, absent for the render's own; frame a 4 x 4 (rows), the part's pose in that view, absent for frame_object's; from and to two consecutive corners; side 1, or -1 for the mirrored half or the partner across the frame's x = 0; line [[u,v],...] drawn from `from` to `to`" + }, + { + "name": "plane", + "type": "string", + "required": false, + "maxLength": 200, + "default": "", + "doc": "'' for the plane through the corners the views and the seam decide, or 'x,y,z; nx,ny,nz' in the frame: a point of the plane and its normal" + }, + { + "name": "share", + "type": "number", + "minimum": 0.001, + "maximum": 10, + "default": 0.1, + "doc": "the prior: a crown point this share of the corners' extent off the plane costs what one pixel of miss does" + }, + { + "name": "tol", + "type": "number", + "minimum": 0.1, + "maximum": 100, + "default": 5.2, + "doc": "pixels: nine tenths of every trace must lie this near its built side, or the side gains a point" + } + ] } ] } diff --git a/surfaces/blender/brokkr_reference/core.py b/surfaces/blender/brokkr_reference/core.py index 69549b4..970adee 100644 --- a/surfaces/blender/brokkr_reference/core.py +++ b/surfaces/blender/brokkr_reference/core.py @@ -37,6 +37,13 @@ only where the built runs explain every trace; docs/reference.md, "fit_shell", s fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol) the moved cage and the report fit_sheet(document, cage, frame, traces, cams, share, tol) the same for a sheet's named runs: the fitted sheet + +A plate's first cage is blocked from traces of its outline, each naming the two corners it runs between: the crown +is solved by fit_runs with a plane and fairness for its prior; docs/reference.md, "block_plate". + + triangulate(obs, seam) where sight lines meet, and how far apart they stand + plate_sheet(crown, corners, flare, drop, dome, mirror, seam, facing) the crown, skirt and centre free-cage document + block_plate(views, plate, traces, parse, plane, share, tol) the blocked sheet and what decided each corner """ from __future__ import annotations @@ -527,7 +534,7 @@ def _hard_runs(cage, runs): "more hard edges meet, or on the rim") -def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): +def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL, prior_rows=None): """Move a cage's points until its hard runs, as built and as cameras draw them, lie on their traces. views [(camera record, frame)]: the frame is the 4 x 4 that carries the cage to the world @@ -538,7 +545,10 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): movable (vertices, 3) of bool: the coordinates that may move. Only authored vertices move mirror_of per vertex, the authored vertex it mirrors across x = 0, or itself: a mirrored half is the same parameters seen again, x negated - share the prior: a move of share x diag from the cage as given costs what one pixel of miss does + share the prior's weight: a prior row that reads share x diag metres costs what one pixel of miss does + prior_rows (A, b) in metres over the movable coordinates, in the order of movable's True entries: the prior is + the rows A p - b. None is the identity, A = I and b the cage as given: a move from where each + point was blocked. block_plate gives distances to a plane and a side's second differences instead tol pixels: PART in a hundred of each trace must lie this near its built run as drawn The residual per run is the pixel distance from each built point (crease_run LEVELS times, drawn through the @@ -581,6 +591,9 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): prepared.append((run["name"], views[run["view"]], line, W, source, np.stack([flip[chain], np.ones(len(chain)), np.ones(len(chain))], 1), column.reshape(-1, 3)[source])) # the parameter column of each chain point's coordinate, -1 where held p0 = V0.ravel()[index] + A0, b0 = (np.eye(len(p0)), p0) if prior_rows is None else (np.asarray(prior_rows[0], float), np.asarray(prior_rows[1], float)) + if A0.ndim != 2 or A0.shape != (len(b0), len(p0)): + raise ReferenceFitError(f"prior_rows must be (A, b) with a column of A per movable coordinate ({len(p0)}) and a row per entry of b") def terms(p): """(residual, Jacobian, each run's built points as drawn) at parameters p.""" @@ -603,7 +616,7 @@ def fit_runs(views, cage, runs, movable, mirror_of, share, diag, tol=TOL): res += [dist, u[0] - line[0], u[-1] - line[-1]] rows.append(block) drawn.append((u, dist)) - return np.concatenate(res + [prior * (p - p0)]), np.vstack(rows + [prior * np.eye(len(p))]), drawn + return np.concatenate(res + [prior * (A0 @ p - b0)]), np.vstack(rows + [prior * A0]), drawn p, lam, rounds = p0.copy(), 1e-3, 0 r, J, drawn = terms(p) @@ -730,6 +743,337 @@ def fit_sheet(document, cage, frame, traces, cams, share=0.1, tol=TOL): return {"sheet": out, "traces": report["traces"], "points": points} +# --- a plate's first cage from its traces ------------------------------------------------------------------------------ + +FAIR = 0.2 # a side's second differences of this share of its chord cost what one pixel of miss does (0.02 held a bowed side straight; docs/reference.md) +K_MAX = 6 # points a side grows to before its trace is refused as fit_runs refuses it +SQUARE = 0.4 # the cosine between a plane's normal and a sight line under which a trace is not lifted onto it: past 66 degrees the lift stretches over 2.5 times +PARALLAX = 9.7 # degrees between a corner's widest pair of sight lines under which the views do not start it: the geometric mean of 19, where a plate blocks from its views, and 5, where its corners land 0.25 to 1.5 m off (tests/test_reference.py BlockTests) +VIEWS = 0.2 # a prior_share under this: the views decide the point (fit_shell's line) +FLARE, DROP, DOME = 0.06, 0.07, 0.02 # metres: a plate's skirt out from and back of its crown, and its centre's rise +TRACE_KEYS = ("camera", "box", "frame", "from", "to", "side", "line") + + +def _unit(v): + v = np.asarray(v, float) + return v / max(float(np.linalg.norm(v)), 1e-12) + + +def _partner(frame, side): + """The frame a trace's side is seen through: the part's own, or for side -1 its reflection across the frame's + x = 0 (the mirrored half of a plate, or the plate's partner on the other limb).""" + F = np.array(frame, float) + if side == -1: + F[:3, 0] = -F[:3, 0] + return F + + +def _sight(cam, frame, pixel): + """A pixel's line of sight (origin, unit direction) in a frame's own coordinates.""" + o, d = ray(cam, pixel) + inv = np.linalg.inv(np.asarray(frame, float)) + return inv[:3, :3] @ o + inv[:3, 3], _unit(inv[:3, :3] @ d) + + +def triangulate(obs, seam=False): + """Where sight lines meet. `obs` is [(camera record, frame, side, pixel)]: the pixel each view draws one point + of the frame at, side -1 a view of the point's reflection across x = 0. The midpoint of the sight lines, then + Gauss-Newton on the reprojection; `seam` holds the point on x = 0, which one view then decides. Returns (the + point in the frame, parallax_deg: the angle between the widest pair of sight lines, the worst reprojection miss + in pixels, m_per_px: the most one pixel of error moves the point). One sight line and no seam is no point.""" + frames = [_partner(frame, side) for _, frame, side, _ in obs] + rays = [_sight(cam, F, pixel) for (cam, _, _, pixel), F in zip(obs, frames)] + free = [1, 2] if seam else [0, 1, 2] + if len(rays) < 2 and not seam: + raise ReferenceFitError("one sight line meets nothing: a point is triangulated from two or more views, or held on the mirror plane") + A, b = np.zeros((3, 3)), np.zeros(3) + for o, d in rays: + P = np.eye(3) - np.outer(d, d) + A, b = A + P, b + P @ o + X = np.zeros(3) + X[free] = np.linalg.lstsq(A[:, free], b, rcond=None)[0] + + def terms(X): + drawn = [_drawn(cam, F, X[None]) for (cam, _, _, _), F in zip(obs, frames)] + if any(seen_ is None for seen_ in drawn): + raise ReferenceFitError("the sight lines meet behind a camera") + return np.concatenate([seen_[0][0] - np.asarray(pixel, float) for seen_, (_, _, _, pixel) in zip(drawn, obs)]), np.vstack([seen_[1][0] for seen_ in drawn])[:, free] + + for _ in range(10): + r, J = terms(X) + X[free] -= np.linalg.lstsq(J, r, rcond=None)[0] + r, J = terms(X) + parallax = max((math.degrees(math.acos(min(1.0, abs(float(a[1] @ c[1]))))) for a in rays for c in rays), default=0.0) + return X, parallax, float(np.abs(r).max()), float(math.sqrt(max(np.linalg.eigvalsh(np.linalg.pinv(J.T @ J)).max(), 0.0))) + + +def plate_sheet(crown, corners, flare=FLARE, drop=DROP, dome=DOME, mirror=False, seam=(), facing=None): + """The free-cage document of a plate whose raised outline is `crown`, a closed ring of points in the plate's + frame: the crown ring (vertices 0 to n - 1, in the ring's order), a skirt ring `flare` out from it and `drop` + back of it (the chamfered wall), and one centre vertex `dome` proud of the ring's middle. Every crown side is + creased 1; `corners` (ring indices) are pinned 1 on crown and skirt, so the crown between two corners is one + hard run, and the points between them are free to round it. The centre is the cage's pole unless the ring has + four points. `facing` is a direction the outer face looks along; the ring is taken as wound that way, or the + sheet is flipped. + + mirror: `seam` names the ring's points on x = 0 (one unbroken stretch of it). The crown between them is the + crease the two halves meet at: it has no skirt, the skirt of its two ends stands on x = 0, and those ends are + poles (six edges meet there once the half is reflected). The centre stands in the half, not on the plane: a + face of three points of x = 0 is its own reflection and the cage's parser refuses it.""" + P = np.asarray(crown, float) + n, seam = len(P), set(seam) if mirror else set() + Q = np.roll(P, -1, axis=0) + normal = _unit(np.cross(P, Q).sum(0)) # Newell's: the ring's own facing, counter-clockwise seen from where it points + flip = facing is not None and float(normal @ np.asarray(facing, float)) < 0 + out_ = -normal if flip else normal + middle = P.mean(0) + walled = [i for i in range(n) if not (i in seam and (i - 1) % n in seam and (i + 1) % n in seam)] # a point inside the seam has no skirt + skirt = {} + for i in walled: + away = (P[i] - middle) - out_ * ((P[i] - middle) @ out_) + back = out_.copy() + if i in seam: + away[0], back[0] = 0.0, 0.0 + point = P[i] + _unit(away) * flare - back * drop + if i in seam: + point[0] = 0.0 + skirt[i] = point + under = {i: n + m for m, i in enumerate(walled)} + centre = n + len(walled) + verts = [[round(float(x), 6) + 0.0 for x in p] for p in list(P) + [skirt[i] for i in walled] + [middle + out_ * dome]] + faces, creases = [], [] + for i in range(n): + j = (i + 1) % n + faces.append([i, j, centre]) + creases.append([i, j, 1.0]) + if not (i in seam and j in seam): + faces.append([under[i], under[j], j, i]) + pinned = [[i, 1.0] for i in corners] + [[under[i], 1.0] for i in corners if i in under] + poles = ([] if n == 4 else [centre]) + sorted(i for i in seam if i in under) + document = {"verts": verts, "faces": faces, "creases": creases, "corners": pinned, "poles": sorted(poles), "rim": 0.0} + if mirror: + document["mirror"] = True + if flip: + document["flip"] = True + return document + + +def block_plate(views, plate, traces, parse, plane=None, share=0.1, tol=TOL): + """A plate's first cage from traces of its outline across solved views; docs/reference.md, "block_plate". + + plate {"corners": [names, in loop order], "mirror": bool, "seam": [corner names on x = 0]}: side i runs from + corner i to corner i + 1 and is one hard crease of the crown + traces [{"from", "to": two consecutive corners, "side": 1, or -1 for the mirrored half or partner, "line": + [[u, v], ...] drawn from `from` to `to`}]; "camera", "box" and "frame" are the caller's and are echoed + views per trace, (camera record, the 4 x 4 that carries the plate's coordinates to the world as that view + poses the part): the plate's own frame, or the trace's "frame" where it states one + parse brokkr_kitbash.core.sheet, the cage's one parser: every sheet built here goes through it + plane {"point", "normal"} in the plate's coordinates, or None for the plane through the corners the views + or the seam decide + + The one correspondence is a trace's two ends to its named corners. The crown's points (the corners and each + side's points between them) are solved by fit_runs: its residual on every trace, and for a prior each crown + point's distance to the plane (one pixel per share x diag, diag the corners' extent) and each side's second + differences (one pixel per FAIR x the side's chord). A distance to a plane does not resist a move in the + plane, so the views decide wherever they see. A side starts as its two corners; a side with a trace not + explained gains a point and the plate is solved again, to K_MAX points. Skirt and centre are rebuilt from the + solved crown (plate_sheet). Returns {"sheet", "fit_traces", "left_out", "corners", "sides", "plane", "rounds"}; + raises ReferenceFitError naming the field for everything it refuses.""" + if not isinstance(plate, dict) or set(plate) - {"corners", "mirror", "seam"}: + raise ReferenceFitError("plate must be {corners, mirror, seam}") + names, mirror, seam_names = plate.get("corners"), plate.get("mirror", False), plate.get("seam", []) + if not isinstance(names, list) or len(names) < 3 or not all(isinstance(name, str) and name for name in names) or len(set(names)) != len(names): + raise ReferenceFitError("plate.corners must be three or more different names, in the outline's order") + if not isinstance(mirror, bool): + raise ReferenceFitError(f"plate.mirror must be true or false, not {mirror!r}") + N, at = len(names), {name: i for i, name in enumerate(names)} + if not isinstance(seam_names, list) or any(name not in at for name in seam_names) or len(set(seam_names)) != len(seam_names): + raise ReferenceFitError("plate.seam must name corners of plate.corners, none twice") + held = {at[name] for name in seam_names} + if mirror != bool(held) or (mirror and (not 2 <= len(held) < N or sum(1 for i in held if (i + 1) % N not in held) != 1)): + raise ReferenceFitError("plate.seam must name two or more corners next to each other in the outline, and not all of them, on a mirrored plate, and none otherwise: " + "the halves meet along the sides between them. A plate that only has a partner across x = 0 is not mirrored: trace the partner with side -1") + if not isinstance(traces, list) or not traces: + raise ReferenceFitError("traces must be an array of one or more {camera, box, frame, from, to, side, line}") + if len(views) != len(traces): + raise ReferenceFitError(f"views must be one (camera, frame) a trace: {len(views)} for {len(traces)} traces") + seen_by, per_side, runs_of, frames = [dict() for _ in names], [[] for _ in names], [], [] + for k, trace in enumerate(traces): + where = f"traces[{k}]" + if not isinstance(trace, dict) or set(trace) - set(TRACE_KEYS): + raise ReferenceFitError(f"{where} must be {{camera, box, frame, from, to, side, line}}") + a, b, side = trace.get("from"), trace.get("to"), trace.get("side", 1) + if a not in at or b not in at: + raise ReferenceFitError(f"{where}.from and .to must name corners of plate.corners, not {a!r} and {b!r}") + step = (at[b] - at[a]) % N + if step not in (1, N - 1): + raise ReferenceFitError(f"{where}.from {a!r} and .to {b!r} are not consecutive corners: a trace is one side of the outline, drawn from one corner to the next") + if side not in (1, -1) or isinstance(side, bool): + raise ReferenceFitError(f"{where}.side must be 1, or -1 for the mirrored half or partner, not {side!r}") + cam, frame = views[k] + if cam is None: + raise ReferenceFitError(f"{where}.camera {trace.get('camera')!r} is no camera of this plate") + try: + F = np.array(frame, float) + except (TypeError, ValueError): + F = np.zeros(0) + if F.shape != (4, 4) or not np.isfinite(F).all() or np.abs(F[:3, :3].T @ F[:3, :3] - np.eye(3)).max() > 1e-6 or np.abs(F[3] - [0, 0, 0, 1]).max() > 1e-9: + raise ReferenceFitError(f"{where}.frame must be a 4 x 4 that only turns and moves the part: a scaled or sheared frame is not metres of the plate") + try: + line = np.array(trace.get("line"), float) + except (TypeError, ValueError): + line = np.zeros(0) + if line.ndim != 2 or line.shape[1] != 2 or len(line) < 2 or not np.isfinite(line).all() or np.linalg.norm(np.diff(line, axis=0), axis=1).sum() < 1e-9: + raise ReferenceFitError(f"{where}.line must be two or more [u, v] points, not all in one place") + F = _partner(F, side) + frames.append(F) + i = at[a] if step == 1 else at[b] + per_side[i].append(k) + runs_of.append((i, step == 1)) + view = (json.dumps([cam["C"], cam["R"], cam["f"], cam["c"]], default=float), F.tobytes()) + for corner, pixel in ((at[a], line[0]), (at[b], line[-1])): + seen_by[corner].setdefault(view, (cam, F, [], k))[2].append(pixel) + for i, name in enumerate(names): + if not seen_by[i]: + raise ReferenceFitError(f"plate.corners[{i}] {name!r}: no trace ends at it. Every corner is the end of a traced side") + for i, name in enumerate(names): + if not per_side[i]: + raise ReferenceFitError(f"the side from {name!r} to {names[(i + 1) % N]!r} is traced in no view: every side of the outline is traced, or the plate is given fewer corners") + lines = sum(len(json.dumps(trace.get("line"), separators=(",", ":"))) for trace in traces) + size = 44 * (2 * N * (K_MAX - 1) + 1) + 34 * N * (K_MAX - 1) + lines + 90 * len(traces) + 150 * N + 400 + if size > RESULT_LIMIT: + raise ReferenceFitError(f"traces: the sheet and its report could be about {size} characters, over the {RESULT_LIMIT} a receipt carries: nothing was solved. " + "Trace with fewer points, or block the plate as two") + + start, parallax, decided = np.zeros((N, 3)), np.zeros(N), np.zeros(N, bool) + obs = [[(cam, F, 1, np.mean(pixels, axis=0)) for cam, F, pixels, _ in seen_by[i].values()] for i in range(N)] + for i in range(N): + if i in held or len(obs[i]) >= 2: + start[i], parallax[i], _, _ = triangulate(obs[i], seam=i in held) + decided[i] = i in held or parallax[i] >= PARALLAX + if plane is None: + if decided.sum() < 3: + raise ReferenceFitError(f"plane: none was given, and {', '.join(repr(names[i]) for i in np.flatnonzero(~decided))} are seen by one view only (or by views under " + f"{PARALLAX:g} degrees apart): three corners the views or the seam decide make the plane. Give plane, or trace those corners in another view") + point = start[decided].mean(0) + _, spread, axes = np.linalg.svd(start[decided] - point) + if spread[1] < 1e-6 * max(spread[0], 1e-12): + raise ReferenceFitError("plane: none was given, and the corners the views decide stand in one line. Give plane") + normal, source = axes[2], "corners" + else: + try: + point, normal = np.array(plane["point"], float), np.array(plane["normal"], float) + fine = point.shape == (3,) and normal.shape == (3,) and np.isfinite(point).all() and np.isfinite(normal).all() and np.linalg.norm(normal) > 1e-9 + except (TypeError, ValueError, KeyError): + fine = False + if not fine: + raise ReferenceFitError("plane must be {point: [x, y, z], normal: [x, y, z]} in the plate's frame, the normal not zero") + normal, source = _unit(normal), "given" + for i in np.flatnonzero(~decided): + lifted = [] + for cam, F, pixels, k in seen_by[i].values(): + o, d = _sight(cam, F, np.mean(pixels, axis=0)) + square = abs(float(normal @ d)) + if square < SQUARE: + raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r}: the plane stands {math.degrees(math.acos(square)):.0f} degrees off square-on to the view of traces[{k}], the " + f"only depth this corner has. A trace lifted onto it stretches past {1 / SQUARE:g} times: turn plane to the face the view shows, or trace the corner in another view") + lifted.append(o + d * (((point - o) @ normal) / (d @ normal))) + start[i] = np.mean(lifted, axis=0) + free_ = [i for i in range(N) if i not in held] + + def crossed(corners_, what): + side_ = 1.0 if sum(1 for i in free_ if corners_[i, 0] > 0) * 2 >= len(free_) else -1.0 + for i in free_: + if mirror and corners_[i, 0] * side_ <= 0: + raise ReferenceFitError(f"plate.corners[{i}] {names[i]!r} {what} at x = {corners_[i, 0]:.3f}, across the mirror plane from the plate's other corners. A corner on the " + "plane is named in plate.seam; one off it is traced where the views agree which side it is on") + + crossed(start, "starts") + diag = float(np.linalg.norm(np.ptp(start, axis=0))) + toward = _sight(views[0][0], frames[0], np.asarray(traces[0]["line"], float)[0])[0] - start.mean(0) + count, solves = [2] * N, 0 + while True: + solves += 1 + first = np.concatenate([[0], np.cumsum([k - 1 for k in count])]) # ring index of each corner; first[N] is the ring's size + n = int(first[N]) + ring = np.concatenate([np.linspace(start[i], start[(i + 1) % N], count[i])[:-1] for i in range(N)]) + chains = [[int(first[i]) + m for m in range(count[i] - 1)] + [int(first[i + 1]) % n] for i in range(N)] + on_seam = {v for i in range(N) if i in held and (i + 1) % N in held for v in chains[i]} | {int(first[i]) for i in held} + build = lambda crown: plate_sheet(crown, [int(first[i]) for i in range(N)], mirror=mirror, seam=sorted(on_seam), facing=toward) # noqa: E731 + + def parsed(document): + try: + return parse(document) + except Exception as refusal: # the parser's own error type is its package's + raise ReferenceFitError(f"sheet: the cage's parser does not take the plate as blocked ({refusal})") from None + + cage = parsed(build(ring)) + movable = np.zeros((len(cage.V), 3), bool) + movable[:n] = True + movable[sorted(on_seam), 0] = False + index = np.flatnonzero(movable.ravel()) + column = np.full(movable.size, -1) + column[index] = np.arange(len(index)) + column = column.reshape(-1, 3) + V0, A, b = np.asarray(cage.V, float), [], [] + + def row(parts, weight): + """One prior row: weight x the sum of factor x coordinate over `parts`, the held coordinates on its right side.""" + line_, right = np.zeros(len(index)), 0.0 + for v, c, factor in parts: + if column[v, c] >= 0: + line_[column[v, c]] += weight * factor + else: + right -= weight * factor * V0[v, c] + A.append(line_) + b.append(right) + + for v in range(n): + row([(v, c, normal[c]) for c in range(3)], 1.0) + b[-1] += float(normal @ point) + for i, chain in enumerate(chains): + fair = share * diag / (FAIR * max(float(np.linalg.norm(start[(i + 1) % N] - start[i])), 1e-9)) + for m in range(1, len(chain) - 1): + for c in range(3): + row([(chain[m - 1], c, 1.0), (chain[m], c, -2.0), (chain[m + 1], c, 1.0)], fair) + runs = [{"name": f"traces[{k}]", "chain": chains[i] if forward else chains[i][::-1], "view": k, "line": trace["line"]} for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of))] + try: + V, report = fit_runs([(cam, F) for (cam, _), F in zip(views, frames)], cage, runs, movable, cage.mirror_of, share, diag, tol, prior_rows=(np.array(A), np.array(b))) + except ReferenceFitError as refusal: + rows = getattr(refusal, "traces", None) + if rows is None: + raise + grow = sorted({runs_of[k][0] for k, row_ in enumerate(rows) if row_["unexplained_px"] > tol}) + full = [i for i in grow if count[i] >= K_MAX] + if full: + error = ReferenceFitError(f"the side from {names[full[0]]!r} to {names[(full[0] + 1) % N]!r} is not explained at {K_MAX} points, the most a side is given: {refusal}") + error.traces = rows + raise error from None + for i in grow: + count[i] += 1 + continue + break + crown = V[:n] + crossed(crown[first[:N]], "ends") + document = build(crown) + parsed(document) + by_vertex = {row_["vertex"]: row_ for row_ in report["points"]} + corners = [] + for i, name in enumerate(names): + row_ = by_vertex[int(first[i])] + corners.append({"name": name, "decided_by": "mirror" if i in held else "views" if row_["prior_share"] < VIEWS else "plane", "parallax_deg": round(float(parallax[i]), 1), + "m_per_px": round(row_["m_per_px"], 4), "prior_share": round(row_["prior_share"], 3)}) + sides = [{"from": names[i], "to": names[(i + 1) % N], "points": count[i], "traces": [report["traces"][k] for k in per_side[i]]} for i in range(N)] + fit_traces, left_out = [], [] + for k, (trace, (i, forward)) in enumerate(zip(traces, runs_of)): + if (trace.get("side", 1) == -1 and not mirror) or trace.get("frame") is not None: + left_out.append(k) # fit_shell takes one frame, the shell's own, and side -1 only as a mirrored sheet's other half + continue + fit_traces.append({**{key: trace[key] for key in ("camera", "box") if key in trace}, "run": {"verts": chains[i] if forward else chains[i][::-1]}, "side": trace.get("side", 1), "line": trace["line"]}) + return {"sheet": document, "fit_traces": fit_traces, "left_out": left_out, "corners": corners, "sides": sides, + "plane": {"point": [round(float(x), 6) for x in point], "normal": [round(float(x), 6) for x in normal], "from": source}, "rounds": solves} + + # --- fields ---------------------------------------------------------------------------------------------------------- diff --git a/surfaces/blender/docs/reference.md b/surfaces/blender/docs/reference.md index bbde414..f55cf6e 100644 --- a/surfaces/blender/docs/reference.md +++ b/surfaces/blender/docs/reference.md @@ -274,6 +274,72 @@ fitted; a run's depth with no mirror partner, no second view and no mirror plane The acceptance reads nine tenths of a trace: it passes a short doubled stretch and a tip that stands off, and reports both as `worst_px`. `m_per_px` is a sensitivity to one pixel, not an error bound. +## block_plate: a plate's first cage from its traces + +`fit_shell` refines a cage somebody blocked. `brokkr_reference.block_plate` makes the first one. A plate is a +closed outline of named corners in order; side i runs from corner i to corner i + 1 and is one hard crease of the +plate's crown. A trace is one side drawn in one view, `{camera, box, frame, from, to, side, line}`: `from` and `to` +are two consecutive corners and the line is drawn from the one to the other. That is the only correspondence +there is: a trace's two ends are its two corners. Every other point of the crown is placed by `fit_shell`'s +residual, the pixel distance from the side as built to the trace. Nothing matches a point of one trace to a +point of another. + +`frame_object` is the plate's frame. A trace's `frame` is the part's pose in that view where it differs (a limb +swung, a hull pitched); `side` -1 is a view of the plate's reflection across the frame's x = 0, which is the +other half of a mirrored plate or the same plate on the partner limb. `plate` is `{corners, mirror, seam}`. On a +mirrored plate `seam` names the corners on x = 0, two or more next to each other: they are held there, the sides +between them lie on it, and one view decides them. + +Where a corner's depth comes from, in this order: + +- **the views**, where two or more see it and its sight lines stand 9.7 degrees or more apart. Under that the + triangulation is not used as a start: at 5 degrees corners of a 1.2 m plate landed 0.25 to 1.5 m off. +- **the mirror plane**, for a seam corner. +- **a plane**, for the rest: `plane` (`x,y,z; nx,ny,nz`, a point and the normal, in the frame), or with none given + the plane through the corners the views and the seam decide, three or more. A corner one view sees is lifted + onto it, and refused when the plane stands more than 66 degrees off square-on to that view: the lift stretches + past 2.5 times there. + +The crown is then solved by the same solver as `fit_shell`, with a different prior: each crown point's distance +to the plane costs a pixel per `share` x the corners' extent, and each side's second differences a pixel per 0.2 +x its chord. A distance to a plane does not resist a move in the plane, so the views decide wherever they see, +and a view that sees nothing along its own sight line leaves that to the plane. A side starts as its two +corners. After each solve a side with a trace not explained (the same nine tenths within `tol`) gains one point +and the plate is solved again, to six points a side; past that it is refused as `fit_shell` refuses a trace. + +The cage is the crown ring, a skirt 0.06 m out and 0.07 m back of it, and one centre vertex: every crown side +creased 1, the named corners pinned, the centre the declared pole unless the crown has four points. On a +mirrored plate the seam's sides have no skirt and the seam's two ends are poles too. The skirt and centre are +rebuilt from the solved crown and never solved. The sheet goes through `brokkr_kitbash`'s parser before it is +returned, and `brokkr_kitbash.shell` builds it; `block_plate` writes nothing. + +The report: `sheet`; `fit_traces`, the traces as `fit_shell` takes them (each side a run of authored vertices), +and `left_out`, the traces `fit_shell` cannot state (one with its own `frame`, or a partner's side -1 on a plate +that is not mirrored); per corner `decided_by` (`views` when the prior's share is under 0.2, `mirror` on the seam, +else `plane`), `parallax_deg`, `m_per_px` and `prior_share`; per side its points and each trace's readings; +`plane` with `from` `given` or `corners`; `rounds`, the solves it took. + +Refused, naming the field: a corner no trace ends at, a side traced in no view, a trace whose corners are not +consecutive, an unknown camera, a scaled frame, a seam that is not one stretch of the outline, no plane where +fewer than three corners are decided, the 66 degrees, a mirrored plate's corner that starts or ends across x = 0 +from the others (name it in `seam`, or trace it where the views agree), a side not explained at six points, a +sheet the cage's parser does not take, and a result that could pass the 16000 characters a receipt carries. + +Measured (`tests/test_reference.py` BlockTests, Python 3.13 on Starfire). SPECTRE's roof from no blocking: the +ridge, traced in the side view alone, 7.3 mm at most from the cage `fit_shell` had fitted from a hand blocking; +the brow, traced in the hero's mirrored half and the side 62.8 degrees apart, a median of 8.4 mm and 78.6 mm at +most from it, in four points; 0.05 s. A twisted pentagon 1.2 m across with sides bowed 8% toward the camera, +17.6 m off at 663 px: 39 and 52 mm from the truth at 60 degrees with traces 0.5 and 1.5 px off, every corner +decided by the views; 65 and 135 mm at 19 degrees, where the plane already has 0.30 to 0.38 of each corner. At +that range and lens two views 19 degrees apart do not decide a corner by this report's own line. + +What it gives up. One outline loop a plate: a plate that wraps a corner is two plates, and creases inside the +outline are not blocked. A bend smaller than `tol` is built straight: the bowed pentagon's 56 mm bow reads under +2 px and stays in the error above. Fairness holds a grown side flatter than its trace while the trace still +reads as explained: a plate whose sides bow 35% of their length ended 42 mm off its truth from exact traces, and +`fit_shell` on the returned `fit_traces` moved it 74 mm back. The plane through the decided corners is a guess +at a twisted plate, and where one view sees a corner the plane is all the depth it has: `decided_by` says so. + ## What it cannot do It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and @@ -281,6 +347,8 @@ no other pose. It does not find the points; marking them is the caller's. Points points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the subject is the right size: a build twice too large is the same picture from twice as far. +`block_plate` blocks one outline loop a plate and no crease inside it. + ## From a script ```python @@ -291,6 +359,7 @@ origin, direction = core.ray(cam, (u, v)) # a pixel's line of point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane run = core.crease_run(column) # the hard crease Blender builds from a cage column fit = core.fit_sheet(sheet, cage, frame, traces, cams) # the fitted sheet and its report; cage is brokkr_kitbash.core.sheet(sheet) +out = core.block_plate(views, plate, traces, parse) # a plate's first sheet and what decided each corner; parse is brokkr_kitbash.core.sheet 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 diff --git a/surfaces/blender/tests/fixtures/spectre_plates.json b/surfaces/blender/tests/fixtures/spectre_plates.json new file mode 100644 index 0000000..75bbce6 --- /dev/null +++ b/surfaces/blender/tests/fixtures/spectre_plates.json @@ -0,0 +1 @@ +{"note":"SPECTRE's roof and cheek as plates. Cameras: spectre_skel.cameras() at nibu/fable-spectre-2 74fc241, solved by this repo's brokkr_reference.core; frames: the hull pitched about the waist by spectre_skel.PITCH (hero 3 degrees, side 0). Traces marked hand are spectre_skel.TRACES (roof brow and ridge, cheek chine); a trace marked fitted-edge is the straight edge between two vertices of spectre_fits.json's fitted cage drawn through the camera, standing in for a side nobody traced, so the outline closes. reference is spectre_fits.json's fitted cage along the traced runs: a fit from a hand blocking, not ground truth.","cameras":{"hero":{"C":[-9.721115556958573,18.859090658741355,5.242272804029844],"R":[[-0.862189601405842,-0.5065857195259607,0.0],[0.034125232508362004,-0.05807984607580026,0.9977285201827507],[-0.5054350202883507,0.8602311551276064,0.06736319480204615]],"f":1785.0,"c":[378.0,353.0]},"side":{"C":[60.84416742645475,1.422308134553987,3.13474760877321],"R":[[3.061616997868383e-16,1.0,0.0],[0.011634411213376642,-3.5620111131064444e-18,0.9999323179474289],[0.9999323179474289,-3.0614097813457806e-16,-0.011634411213376642]],"f":2200.0,"c":[892.0,532.0]}},"frames":{"hero":[[1.0,0.0,0.0,0.0],[0.0,0.9986295347545738,0.052335956242943835,-0.2773805680876023],[0.0,-0.052335956242943835,0.9986295347545738,0.007263465800758873],[0.0,0.0,0.0,1.0]],"side":[[1.0,0.0,0.0,0.0],[0.0,1.0,0.0,0.0],[0.0,-0.0,1.0,0.0],[0.0,0.0,0.0,1.0]]},"plates":{"roof":{"plate":{"corners":["ridge_rear","nose","brow_rear"],"mirror":true,"seam":["ridge_rear","nose"]},"traces":[{"view":"side","from":"ridge_rear","to":"nose","side":1,"line":[[883,400],[898,408],[930,426],[958,441]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"nose","side":-1,"line":[[487,47],[443,92],[427,126],[400,128],[360,135],[325,142]],"source":"hand"},{"view":"side","from":"brow_rear","to":"nose","side":1,"line":[[883,404],[900.7,413.6],[919,423.6],[938.6,436.4],[958.6,443]],"source":"hand"},{"view":"hero","from":"brow_rear","to":"ridge_rear","side":-1,"line":[[487.1,47.1],[424.7,35.3]],"source":"fitted-edge"},{"view":"side","from":"brow_rear","to":"ridge_rear","side":1,"line":[[883.0,404.1],[883.0,399.9]],"source":"fitted-edge"}],"reference":{"ridge":[[0.0,1.173941,7.498167],[0.0,2.063931,7.015758],[0.0,2.624251,6.687296],[0.0,3.079302,6.461668],[0.0,3.280227,6.334663]],"brow":[[0.776479,1.177565,7.327593],[0.653669,2.30313,6.743599],[0.929821,2.609515,6.428508],[0.197231,2.908778,6.436474],[0.0,3.280227,6.334663]]}},"cheek":{"plate":{"corners":["chine_rear","jaw","chin"],"mirror":true,"seam":["jaw","chin"]},"traces":[{"view":"hero","from":"chine_rear","to":"jaw","side":-1,"line":[[472,169],[438,180],[390,170],[312,182]],"source":"hand"},{"view":"side","from":"chine_rear","to":"jaw","side":1,"line":[[919,447],[945,456.5],[961,459]],"source":"hand"},{"view":"side","from":"jaw","to":"chin","side":1,"line":[[965.6,456.7],[957.7,463.1]],"source":"fitted-edge"},{"view":"hero","from":"chin","to":"chine_rear","side":-1,"line":[[331.3,199.5],[472.1,167.8]],"source":"fitted-edge"},{"view":"side","from":"chin","to":"chine_rear","side":1,"line":[[957.7,463.1],[921.1,451.0]],"source":"fitted-edge"}],"reference":{"chine":[[1.097992,2.211844,6.0315],[0.924701,2.658187,5.897007],[0.340462,2.978516,6.057156],[0.0,3.458134,5.926945]]}}}} \ No newline at end of file diff --git a/surfaces/blender/tests/test_reference.py b/surfaces/blender/tests/test_reference.py index db8af73..1f06e16 100644 --- a/surfaces/blender/tests/test_reference.py +++ b/surfaces/blender/tests/test_reference.py @@ -717,6 +717,241 @@ class FitTests(unittest.TestCase): core.fit_sheet(sheet_, kit.sheet(sheet_), FIT_FRAME, traces, cams) +EYE = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] +PLATE = [f"c{i}" for i in range(5)] +ON_Y = {"point": [0, 0, 0], "normal": [0, 1, 0]} + + +def plate_camera(azimuth, distance=17.6, f=663.0): + """A camera `distance` off the origin, level, turned `azimuth` degrees from looking along +y: Paladin's hero's + lens and range (663 px, 17.6 m).""" + a = math.radians(azimuth) + C = distance * np.array([math.sin(a), -math.cos(a), 0.0]) + right = np.cross(-C / distance, [0, 0, 1.0]) + right /= np.linalg.norm(right) + return {"C": C.tolist(), "R": np.stack([right, np.cross(right, -C / distance), C / distance]).tolist(), "f": f, "c": [500.0, 500.0]} + + +def pentagon(bow, lateral=0.0, twist=0.15): + """The sides of a pentagon plate 1.2 m across facing -y, as five-point cage chains: its corners `twist` metres + off the plane y = 0 (a twisted plate), each side bowed `bow` of its length toward -y, which a view from there + sees end on, and `lateral` of it outward in the plate.""" + angles = [2 * math.pi * i / 5 + 0.3 for i in range(5)] + P = np.array([[0.6 * math.cos(t), twist * math.cos(2 * t), 0.6 * math.sin(t)] for t in angles]) + s, sides = np.linspace(0, 1, 5)[:, None], [] + for a, b in zip(P, np.roll(P, -1, axis=0)): + sides.append(a + s * (b - a) + np.sin(math.pi * s) * np.linalg.norm(b - a) * (bow * np.array([0, -1.0, 0]) + lateral * (a + b) / np.linalg.norm(a + b))) + return sides + + +def plate_traces(cams, sides, sigma=0.0, seed=7): + """(views, traces) of a plate's sides as built, drawn through each camera in 12 points, `sigma` px of noise.""" + rng, views, traces = np.random.default_rng(seed), [], [] + for i, side in enumerate(sides): + for k, cam in enumerate(cams): + u = core.resampled(core.project(cam, core.crease_run(core.crease_run(side))), 12) + traces.append({"camera": f"View{k}", "from": PLATE[i], "to": PLATE[(i + 1) % 5], "side": 1, "line": (u + rng.normal(0, sigma, u.shape)).tolist()}) + views.append((cam, EYE)) + return views, traces + + +def crown_chains(out): + """Per side of a block_plate report, its crown vertices in the sheet.""" + n, first, chains = sum(side["points"] - 1 for side in out["sides"]), 0, [] + for side in out["sides"]: + chains.append([(first + m) % n for m in range(side["points"])]) + first += side["points"] - 1 + return chains + + +def off_run(out, chain, truth): + """The furthest a blocked side as built stands from a true cage chain as built, metres.""" + built = core.crease_run(core.crease_run(np.array(out["sheet"]["verts"])[chain])) + return core._off(built, core.resampled(core.crease_run(core.crease_run(np.asarray(truth, float))), 400)) + + +def off_plate(out, sides): + return max(float(off_run(out, chain, side).max()) for chain, side in zip(crown_chains(out), sides)) + + +def blocked_plate(views, traces, **more): + return core.block_plate(views, {"corners": PLATE}, traces, kit.sheet, **more) + + +@unittest.skipIf(np is None, "numpy") +class BlockTests(unittest.TestCase): + """block_plate: a plate's first cage from traces of its outline. Bounds follow + lodur:ruling:deterministic-bound-margin; the other numbers are tolerances round a known truth. Mutants, each + run once on a copy: + M1 no end terms test_spectre_roof_and_cheek + M2 a point prior (fit_shell's) for the plane distance test_one_view_and_a_plane_block_a_bowed_plate + M3 a seam corner's x free test_spectre_roof_and_cheek + M5 the 66 degree guard off test_a_plane_far_off_square_on_to_its_one_view_is_refused + M6 no growth (K_MAX 2) test_a_side_grows_until_its_trace_is_explained, test_spectre_roof_and_cheek + M4 no fairness test_spectre_roof_and_cheek + + M4 is claimed by one reading, SPECTRE's brow (a median of 8.4 mm with fairness, 19.8 without), against a + reference that is itself a fit. Against a known truth it reads the other way: the bowed plate of + test_a_side_grows_until_its_trace_is_explained ends 41.6 mm off with fairness and 12.1 without, the one-view + bowed plate 85.1 mm with it and 2.7 without, the twisted plate at 19 degrees and 1.5 px 135.1 either way. FAIR + 0.2 came from five-point chains under noise (research probe-synthetic-sensitivity); a side grown only as far + as its trace asks has less for fairness to hold. + + The twisted, bowed plate does not block within 1.35 x noise x m_per_px, the probe's figure for five-point + chains: its bow toward the first camera is 56 mm, under 2 px at 60 degrees, the default tol explains it with a + straight side, and what is left is the bow (test_a_twisted_bowed_plate_blocks_from_two_views).""" + + def test_a_twisted_bowed_plate_blocks_from_two_views(self): + """block-synthetic. Views 60 and 19 degrees apart, traces 0.5 and 1.5 px off: every trace is explained with + two points a side, and the crown as built ends 39.3, 52.1 (60 degrees) and 65.0, 135.1 mm (19) from the + truth, 1.46 to 4.23 times noise x the worst corner's m_per_px. At 60 degrees every corner is decided by the + views (prior_share 0.138 at most, under core.VIEWS by 1.45); at 19 the plane has 0.30 to 0.38 of each.""" + sides = pentagon(0.08) + for apart, sigma, most, by in ((60, 0.5, 0.06, "views"), (60, 1.5, 0.08, "views"), (19, 0.5, 0.1, "plane"), (19, 1.5, 0.2, "plane")): + out = blocked_plate(*plate_traces([plate_camera(0), plate_camera(apart)], sides, sigma)) + self.assertLess(off_plate(out, sides), most, (apart, sigma)) + self.assertEqual({corner["decided_by"] for corner in out["corners"]}, {by}, (apart, sigma)) + self.assertLess(max(abs(corner["parallax_deg"] - apart) for corner in out["corners"]), 1.5) + self.assertEqual(out["plane"]["from"], "corners") + kit.sheet(out["sheet"]) + + def test_views_5_degrees_apart_take_their_depth_from_a_plane_or_are_refused(self): + """block-low-parallax. At 5 degrees the corners triangulate 0.25 to 1.5 m off (the probe): under + core.PARALLAX the views start no corner. With a plane every corner is decided by it (prior_share 0.795 to + 0.838); with none the plate is refused naming the corners.""" + views, traces = plate_traces([plate_camera(0), plate_camera(5)], pentagon(0.08), 0.5) + out = blocked_plate(views, traces, plane=ON_Y) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) + self.assertGreater(min(corner["prior_share"] for corner in out["corners"]), 0.7) + self.assertEqual(out["plane"]["from"], "given") + with self.assertRaisesRegex(core.ReferenceFitError, r"^plane: none was given, and 'c0', 'c1', 'c2', 'c3', 'c4' are seen by one view only"): + blocked_plate(views, traces) + + def test_a_side_grows_until_its_trace_is_explained(self): + """block-growth, M6. A straight-sided plate blocks with its corners alone, 1.9 mm from the truth (the plane + draws its twisted corners in). Sides bowed 35% of their length in the plate grow to three points and every + trace reads under 1 px; M6 refuses the plate, its first side not explained at two points. The grown crown + ends 41.6 mm off: fairness holds the bow in while the traces stay explained (M4, in the class's notes).""" + cams = [plate_camera(0), plate_camera(60)] + out = blocked_plate(*plate_traces(cams, pentagon(0.0))) + self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([2] * 5, 1, 11)) + self.assertLess(off_plate(out, pentagon(0.0)), 0.004) + sides = pentagon(0.08, 0.35) + out = blocked_plate(*plate_traces(cams, sides)) + self.assertEqual(([side["points"] for side in out["sides"]], out["rounds"], len(out["sheet"]["verts"])), ([3] * 5, 2, 21)) + self.assertLess(max(trace["unexplained_px"] for side in out["sides"] for trace in side["traces"]), core.TOL / 1.2) + self.assertLess(off_plate(out, sides), 0.06) + + def test_one_view_and_a_plane_block_a_bowed_plate(self): + """M2. A flat plate in the plane it is given, its sides bowed 35% in the plate, traced exactly in one view + 30 degrees off square-on: every corner is decided by the plane, the sides grow to three points and the + crown ends 85.1 mm off the truth. M2, which holds each point where it was started instead of to the plane, + ends 109.7 mm off: the bound is their geometric mean, separation 1.14 each side (1.29 across), the least + the ruling takes.""" + sides = pentagon(0.0, 0.35, twist=0.0) + out = blocked_plate(*plate_traces([plate_camera(30)], sides), plane=ON_Y) + self.assertEqual([corner["decided_by"] for corner in out["corners"]], ["plane"] * 5) + self.assertEqual([corner["parallax_deg"] for corner in out["corners"]], [0.0] * 5) + self.assertEqual([side["points"] for side in out["sides"]], [3] * 5) + self.assertLess(off_plate(out, sides), 0.0966) + + def test_a_plane_far_off_square_on_to_its_one_view_is_refused(self): + """M5: the guard promoted from the Paladin harness (paladin_limbs.plate, the 8 m pauldron). One view 64 + degrees off the plane's normal blocks the plate on it; at 68 degrees (cosine 0.375, under core.SQUARE) the + plate is refused naming the corner, the trace and the angle. M5 blocks it.""" + sides = pentagon(0.0, twist=0.0) + out = blocked_plate(*plate_traces([plate_camera(64)], sides), plane=ON_Y) + self.assertLess(off_plate(out, sides), 1e-4) + with self.assertRaisesRegex(core.ReferenceFitError, r"^plate\.corners\[0\] 'c0': the plane stands 67 degrees off square-on to the view of traces\[0\]"): + blocked_plate(*plate_traces([plate_camera(68)], sides), plane=ON_Y) + + def spectre(self, name): + fixture = json.loads((Path(__file__).resolve().parent / "fixtures" / "spectre_plates.json").read_text(encoding="utf-8")) + plate = fixture["plates"][name] + traces = [{"camera": trace["view"], **{key: trace[key] for key in ("from", "to", "side", "line")}, **({"frame": fixture["frames"]["hero"]} if trace["view"] == "hero" else {})} for trace in plate["traces"]] + return fixture, plate, core.block_plate([(fixture["cameras"][trace["view"]], fixture["frames"][trace["view"]]) for trace in plate["traces"]], plate["plate"], traces, kit.sheet) + + def test_spectre_roof_and_cheek(self): + """block-spectre, M1, M3, M6. SPECTRE's roof and cheek from no blocking (tests/fixtures/spectre_plates.json: + the brow, ridge and chine are hand traces, the sides nobody traced are edges of the fitted cage). Roof: the + brow's free corner is decided by the views (62.8 degrees, prior_share 0.054), the ridge's two by the mirror + plane; the ridge, traced in the side view alone, is built 7.3 mm at most from the fitted ridge and the brow + a median of 8.4 mm from the fitted brow (78.6 at most), in four points. M1 reads 27.7 and 18.9 (M4 19.8 on the brow): the bounds + are the geometric means, separations 1.95 and 1.50 each side. Cheek: the jaw, where the two hand traces + disagree by 0.27 m, stays on x = 0. M3 lands the roof's nose at x = -0.049 and the jaw at -0.140 and the + cage's parser refuses both; M1 puts the cheek's skirt across the plane and it is refused; M6 refuses both + at two points a side.""" + fixture, plate, out = self.spectre("roof") + self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("ridge_rear", "mirror"), ("nose", "mirror"), ("brow_rear", "views")]) + self.assertLess(out["corners"][2]["prior_share"], core.VIEWS / 1.2) + self.assertGreater(out["corners"][2]["parallax_deg"], 60) + ridge, brow, rear = crown_chains(out) + self.assertEqual([side["points"] for side in out["sides"]], [2, 4, 2]) + self.assertLess(float(off_run(out, ridge, plate["reference"]["ridge"]).max()), 0.0142) + self.assertLess(float(np.median(off_run(out, brow, plate["reference"]["brow"]))), 0.0126) + verts = np.array(out["sheet"]["verts"]) + self.assertEqual(float(np.abs(verts[ridge, 0]).max()), 0.0) + self.assertEqual(out["left_out"], [1, 3]) # the hero poses the hull 3 degrees down: fit_shell has one frame + self.assertEqual([trace["run"] for trace in out["fit_traces"]], [{"verts": ridge}, {"verts": brow[::-1]}, {"verts": rear}]) + fixture, plate, out = self.spectre("cheek") + self.assertEqual([(corner["name"], corner["decided_by"]) for corner in out["corners"]], [("chine_rear", "views"), ("jaw", "mirror"), ("chin", "mirror")]) + chine, seam, _ = crown_chains(out) + self.assertEqual([float(x) for x in np.array(out["sheet"]["verts"])[seam, 0]], [0.0, 0.0]) + self.assertEqual(out["sheet"]["mirror"], True) + self.assertEqual(out["sheet"]["poles"], [seam[0], seam[1], len(out["sheet"]["verts"]) - 1]) + + def test_the_blocking_goes_to_the_parser_and_to_fit_shell(self): + """block-then-fit without Blender (tests/live/reference_block.py builds it): the sheet is one the cage's + parser takes, fit_traces name each side as a run of authored vertices, and fit_sheet takes both. On the + straight plate fit_shell's own prior moves no point 5 mm (2.2 at most: the plane had drawn the twisted + corners in); on the bowed plate it moves the grown points up to 74 mm, back toward the bow fairness held in.""" + cams = [plate_camera(0), plate_camera(60)] + for sides, most in ((pentagon(0.0), 0.005), (pentagon(0.08, 0.35), 0.09)): + views, traces = plate_traces(cams, sides) + out = blocked_plate(views, traces) + self.assertEqual((len(out["fit_traces"]), out["left_out"]), (10, [])) + self.assertEqual(set(out["fit_traces"][0]), {"camera", "run", "side", "line"}) + fit = core.fit_sheet(out["sheet"], kit.sheet(out["sheet"]), EYE, out["fit_traces"], [cam for cam, _ in views]) + self.assertLess(max(point["moved_m"] for point in fit["points"]), most) + self.assertLess(len(json.dumps(out, separators=(",", ":"))), core.RESULT_LIMIT) + + def test_block_refusals_name_their_field(self): + """block-refusals.""" + cams = [plate_camera(0), plate_camera(60)] + views, traces = plate_traces(cams, pentagon(0.0)) + + def refused(pattern, views_=views, traces_=traces, plate=None, parse=None, **more): + with self.assertRaisesRegex(core.ReferenceFitError, pattern): + core.block_plate(views_, plate or {"corners": PLATE}, traces_, parse or kit.sheet, **more) + + keep = [k for k, trace in enumerate(traces) if trace["from"] != "c2"] + refused(r"^the side from 'c2' to 'c3' is traced in no view", [views[k] for k in keep], [traces[k] for k in keep]) + keep = [k for k, trace in enumerate(traces) if trace["from"] not in ("c1", "c2")] + refused(r"^plate\.corners\[2\] 'c2': no trace ends at it", [views[k] for k in keep], [traces[k] for k in keep]) + refused(r"^traces\[0\]\.from 'c0' and \.to 'c2' are not consecutive corners", traces_=[{**traces[0], "to": "c2"}] + traces[1:]) + refused(r"^traces\[0\]\.from and \.to must name corners", traces_=[{**traces[0], "to": "c9"}] + traces[1:]) + refused(r"^traces\[3\]\.camera 'View1' is no camera of this plate", views[:3] + [(None, EYE)] + views[4:]) + refused(r"^traces\[1\]\.frame must be a 4 x 4 that only turns and moves", views[:1] + [(cams[1], (2 * np.eye(4)).tolist())] + views[2:]) + refused(r"^traces\[2\]\.side must be 1, or -1", traces_=traces[:2] + [{**traces[2], "side": 2}] + traces[3:]) + refused(r"^traces\[2\]\.line must be two or more", traces_=traces[:2] + [{**traces[2], "line": [[1, 2]]}] + traces[3:]) + refused(r"^traces\[2\] must be \{camera, box, frame, from, to, side, line\}", traces_=traces[:2] + [{**traces[2], "run": {}}] + traces[3:]) + refused(r"^plate\.corners must be three or more different names", plate={"corners": ["a", "b"]}) + refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "mirror": True, "seam": ["c0"]}) + refused(r"^plate\.seam must name two or more corners next to each other", plate={"corners": PLATE, "seam": ["c0", "c1"]}) + refused(r"^plane must be \{point: \[x, y, z\], normal: \[x, y, z\]\}", plane={"point": [0, 0, 0], "normal": [0, 0, 0]}) + + def no(document): + raise kit.KitError("sheet.verts[0] is not to its taste") + + refused(r"^sheet: the cage's parser does not take the plate as blocked \(sheet\.verts\[0\] is not to its taste\)", parse=no) + long = [{**trace, "line": core.resampled(np.array(trace["line"]), 160).round(1).tolist()} for trace in traces] + refused(r"^traces: the sheet and its report could be about \d+ characters, over the 16000", traces_=long) + # a mirrored plate's corner drawn across the mirror plane from the others + P, names = np.array([[0, 0, 0.5], [0, 0, -0.5], [0.5, 0.1, -0.4], [-0.05, 0.1, 0.4]]), ["a", "b", "c", "d"] + mirrored = [{"from": names[i], "to": names[(i + 1) % 4], "side": 1, "line": core.project(cam, P[[i, (i + 1) % 4]]).tolist()} for i in range(4) for cam in cams] + refused(r"^plate\.corners\[3\] 'd' starts at x = -0\.050, across the mirror plane", [(cam, EYE) for _ in range(4) for cam in cams], mirrored, {"corners": names, "mirror": True, "seam": ["a", "b"]}) + + @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} @@ -780,8 +1015,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.flow_score", "brokkr_reference.fit_shell"]) - 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", "brokkr_reference.fit_shell", "brokkr_reference.block_plate"]) + self.assertEqual(source.count("bl_idname = "), 4) for row in self.document["actions"]: self.assertIn(f'bl_idname = "{row["name"]}"', source) self.assertEqual(row.get("result"), "brokkr_mesh_polish_result") @@ -807,6 +1042,11 @@ class HostFileTests(unittest.TestCase): for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"object_name": "x" * 64}): with self.assertRaises(at.IntentInvalid): at.validate({**fit, **bad}, self.host) + block = {**self.envelope, "action": "brokkr_reference.block_plate", "frame_object": "Frame", "plate": "{}", "traces": "[{}]"} + self.assertEqual((at.validate(block, self.host)["share"], at.validate(block, self.host)["tol"], at.validate(block, self.host)["plane"]), (0.1, core.TOL, "")) + for bad in ({"tol": 0}, {"share": 11}, {"traces": ""}, {"plate": ""}, {"frame_object": "x" * 64}, {"plane": "x" * 201}): + with self.assertRaises(at.IntentInvalid): + at.validate({**block, **bad}, self.host) class OwnershipTests(unittest.TestCase): @@ -827,7 +1067,7 @@ class OwnershipTests(unittest.TestCase): decided by matching trace points to each other.""" for path in (SURFACE / "brokkr_reference").glob("*.py"): text = path.read_text(encoding="utf-8") - self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane", text), path.name) + self.assertIsNone(re.search(r"def pair|_smoothest|cage_through|on_plane|epipolar", text), path.name) self.assertIsNone(re.search(r"SHELL\] *=|kit_shell\"\] *=|\.data\.vertices|foreach_set|from_pydata", text), path.name) def test_no_other_package_names_this_one(self):