brokkr_reference: pair, lift_pair and the lift helpers deleted; PR 36 lands as flow_score and the honest lens band #36
8 changed files with 1271 additions and 72 deletions
|
|
@ -1,4 +1,5 @@
|
|||
"""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,
|
||||
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 +7,18 @@ 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 (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."}
|
||||
|
||||
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 +80,131 @@ 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)
|
||||
|
||||
|
||||
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):
|
||||
"""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 nearer it than the hiding margin: HIDE of the diagonal of the edge's
|
||||
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))
|
||||
|
||||
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)
|
||||
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)
|
||||
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)])
|
||||
return out
|
||||
|
||||
|
||||
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_flow_score)
|
||||
|
||||
|
||||
def register():
|
||||
|
|
|
|||
|
|
@ -80,6 +80,59 @@
|
|||
"doc": "pixels across the frame the box becomes when camera_name is given"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,7 +23,13 @@ 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 traced line is pixels; a part's points are given in its frame, a 4 x 4 frame-to-world matrix.
|
||||
|
||||
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
|
||||
along(line, segments, height) the flow score: how much of a traced line has a seen edge along it
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
|
@ -36,6 +42,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.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)
|
||||
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
|
||||
|
||||
|
|
@ -194,24 +203,30 @@ 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 _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 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; 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]
|
||||
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, 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")
|
||||
return axes[2], float(w[2] / w[0])
|
||||
|
||||
|
||||
def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)):
|
||||
|
|
@ -227,18 +242,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), "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 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, unless `lens` is held and the model is upright, rolled or square."""
|
||||
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]
|
||||
|
|
@ -254,43 +280,49 @@ 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, 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))
|
||||
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])
|
||||
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])))),
|
||||
"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)}}
|
||||
|
||||
|
||||
|
|
@ -334,6 +366,81 @@ 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 and built edges -------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
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 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 _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 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 +467,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
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
# Reference views: the camera a picture was drawn through
|
||||
# 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
|
||||
one operator agents may run; 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 gives cameras. 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
|
||||
|
|
@ -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:
|
||||
|
||||
|
|
@ -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,9 +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, 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, 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.
|
||||
|
||||
`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
|
||||
|
||||
|
|
@ -85,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.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
|
||||
keep it.
|
||||
- `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
|
||||
bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix.
|
||||
|
|
@ -107,6 +139,39 @@ 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).
|
||||
|
||||
## 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` | 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 |
|
||||
| `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's sight line stops short of each point by a thousandth (`HIDE`) of the diagonal of the edge's own
|
||||
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`
|
||||
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 +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
|
||||
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) 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_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).
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@
|
|||
"brokkr_mesh_polish.scrub_markings",
|
||||
"brokkr_mesh_polish.cut_parts",
|
||||
"brokkr_mesh_polish.pick",
|
||||
"brokkr_reference.solve_camera"
|
||||
"brokkr_reference.solve_camera",
|
||||
"brokkr_reference.flow_score"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
|
@ -119,13 +120,14 @@
|
|||
"brokkr_mesh_polish.scrub_markings",
|
||||
"brokkr_mesh_polish.cut_parts",
|
||||
"brokkr_mesh_polish.pick",
|
||||
"brokkr_reference.solve_camera"
|
||||
"brokkr_reference.solve_camera",
|
||||
"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,
|
||||
|
|
|
|||
276
surfaces/blender/tests/live/reference_flow.py
Normal file
276
surfaces/blender/tests/live/reference_flow.py
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
"""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)
|
||||
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). 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)
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference_flow.py -- <out>
|
||||
|
||||
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
|
||||
without them). <out> is an absolute path: it writes <out>.result.json and exits 1 when a check failed. Not part
|
||||
of the unittest run: it needs Blender.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bmesh
|
||||
import bpy
|
||||
import numpy as np
|
||||
from bpy_extras.object_utils import world_to_camera_view
|
||||
from mathutils import Euler, Matrix, Vector
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not os.path.isabs(OUT):
|
||||
raise SystemExit(f"<out> must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory")
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_reference"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
from brokkr_reference import core # noqa: E402
|
||||
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-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]]}
|
||||
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.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
|
||||
|
||||
# --- 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
|
||||
|
||||
# --- 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()
|
||||
bpy.context.view_layer.update()
|
||||
box = "100,50,1700,1250" # the same view as an image twice the frame's size, its corner at 100, 50
|
||||
|
||||
# --- 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 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",
|
||||
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"])
|
||||
|
||||
# --- 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 == "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))
|
||||
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 * 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)]) * 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)
|
||||
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()
|
||||
|
||||
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", 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])
|
||||
# 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
|
||||
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:])
|
||||
|
||||
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)
|
||||
385
surfaces/blender/tests/live/reference_flow.result.json
Normal file
385
surfaces/blender/tests/live/reference_flow.result.json
Normal file
|
|
@ -0,0 +1,385 @@
|
|||
{
|
||||
"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.flow_score"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "crease_run stands where Blender builds the creased column, within 1e-4 m",
|
||||
"ok": true,
|
||||
"detail": 4.76837158203125e-07
|
||||
},
|
||||
{
|
||||
"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 back edge, both its faces turned away, is not read: 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."
|
||||
},
|
||||
{
|
||||
"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": [
|
||||
[
|
||||
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": [
|
||||
[
|
||||
1.0,
|
||||
3,
|
||||
6
|
||||
],
|
||||
[
|
||||
0.0,
|
||||
2,
|
||||
6
|
||||
],
|
||||
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": [
|
||||
[
|
||||
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, 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,
|
||||
"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": [],
|
||||
"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.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
|
||||
]
|
||||
],
|
||||
"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
|
||||
}
|
||||
|
|
@ -15,6 +15,8 @@ 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
|
||||
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
|
||||
|
||||
|
|
@ -117,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
|
||||
|
|
@ -211,31 +214,172 @@ 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 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)
|
||||
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()))
|
||||
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, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane"))
|
||||
(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)
|
||||
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."""
|
||||
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.assertEqual((solved["planarity"], solved["lens_determined"]), (0.0, True))
|
||||
self.assertIsNone(self.auto["plane"])
|
||||
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_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: 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)
|
||||
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)
|
||||
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
|
||||
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)
|
||||
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])
|
||||
thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # 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"}))
|
||||
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"))
|
||||
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))
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy")
|
||||
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
|
||||
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_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
|
||||
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_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):
|
||||
|
|
@ -300,13 +444,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.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")
|
||||
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 +461,11 @@ 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)
|
||||
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 ((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 +476,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"):
|
||||
|
|
|
|||
Loading…
Reference in a new issue