tests/live/reference.py: a known scene rendered, solved through the action, rendered again
1 - IoU of the two silhouettes 0.000168 (0.6489 with shift_y flipped); Blender 5.3.0. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
d6b8896e00
commit
3cf4234edb
2 changed files with 329 additions and 0 deletions
183
surfaces/blender/tests/live/reference.py
Normal file
183
surfaces/blender/tests/live/reference.py
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
"""Live proof, in a background Blender, that the brokkr_reference row is admitted by Brokkr as a host action and
|
||||
that solve_camera, through run_intent, finds the camera a known scene was rendered through: three boxes rendered
|
||||
at a 50 mm camera cropped off-axis, their corners marked where Blender's own projection draws them (to a tenth of
|
||||
a pixel), the camera solved and stood as a second camera object, and the scene rendered again through it. The two
|
||||
silhouettes must agree. Not part of the unittest run: it needs Blender.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference.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, <out>.truth.png and <out>.solved.png, and
|
||||
exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names the
|
||||
check before it, and the result file is written whatever happened.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import traceback
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bmesh
|
||||
import bpy
|
||||
import numpy as np
|
||||
from bpy_extras.object_utils import world_to_camera_view
|
||||
from mathutils import Euler, Matrix, Vector
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not os.path.isabs(OUT):
|
||||
raise SystemExit(f"<out> must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory")
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_reference"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
from brokkr_reference import core # noqa: E402
|
||||
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-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
|
||||
|
||||
|
||||
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 silhouette(camera, path):
|
||||
"""Render through `camera` with a transparent film and return where the scene covers the frame."""
|
||||
scene = bpy.context.scene
|
||||
scene.camera = camera
|
||||
scene.render.filepath = path
|
||||
bpy.ops.render.render(write_still=True)
|
||||
image = bpy.data.images.load(path)
|
||||
alpha = np.array(image.pixels[:], dtype=np.float32).reshape(image.size[1], image.size[0], 4)[:, :, 3]
|
||||
bpy.data.images.remove(image)
|
||||
return alpha > 0.5
|
||||
|
||||
|
||||
def drawn(camera, point):
|
||||
"""The frame pixel (u, v down) Blender's own projection gives a world point."""
|
||||
x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(point))
|
||||
return x * WIDTH, (1.0 - y) * HEIGHT
|
||||
|
||||
|
||||
def params_of(camera):
|
||||
data, render = camera.data, bpy.context.scene.render
|
||||
return {"matrix_world": [list(row) for row in camera.matrix_world], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y,
|
||||
"sensor_width": data.sensor_width, "sensor_fit": data.sensor_fit, "resolution": [render.resolution_x, render.resolution_y]}
|
||||
|
||||
|
||||
try:
|
||||
check("host file admitted", not R["hostErrors"] and "brokkr_reference.solve_camera" in R["hostRows"], R["hostRows"])
|
||||
scene = bpy.context.scene
|
||||
scene.render.engine = "BLENDER_WORKBENCH"
|
||||
scene.render.film_transparent = True
|
||||
scene.render.image_settings.file_format = "PNG"
|
||||
scene.render.image_settings.color_mode = "RGBA"
|
||||
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
|
||||
|
||||
# --- the known scene: a hull, a tower off its middle and a wing, none mirrored, so no camera but one draws it --------
|
||||
bm = bmesh.new()
|
||||
for size, place in (((1.6, 4.0, 0.8), (0.0, 0.0, 0.4)), ((0.6, 0.8, 1.2), (0.3, -1.0, 1.4)), ((1.8, 1.0, 0.2), (1.7, 0.6, 0.5))):
|
||||
bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Translation(place) @ Matrix.Diagonal((*size, 1.0)))
|
||||
mesh = bpy.data.meshes.new("Known")
|
||||
bm.to_mesh(mesh)
|
||||
bm.free()
|
||||
scene.collection.objects.link(bpy.data.objects.new("Known", mesh))
|
||||
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, truth.data.shift_x, truth.data.shift_y = 50.0, 36.0, "HORIZONTAL", 0.08, -0.05
|
||||
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()
|
||||
first = silhouette(truth, OUT + ".truth.png")
|
||||
check("fixture: the scene covers part of the frame and touches no edge", 0.05 < first.mean() < 0.6 and not (first[0].any() or first[-1].any() or first[:, 0].any() or first[:, -1].any()), float(first.mean()))
|
||||
|
||||
corners = {f"v{v.index}": tuple(v.co) for v in mesh.vertices}
|
||||
marks = {k: drawn(truth, p) for k, p in corners.items()}
|
||||
world = "; ".join(f"{k}={p[0]:.4f},{p[1]:.4f},{p[2]:.4f}" for k, p in corners.items())
|
||||
pixels = "; ".join(f"{k}={u:.1f},{v:.1f}" for k, (u, v) in marks.items())
|
||||
box = f"0,0,{WIDTH},{HEIGHT}"
|
||||
|
||||
# --- camera_of reads the scene's own camera: the record draws what Blender draws ------------------------------------
|
||||
record = core.camera_of(params_of(truth))
|
||||
off = float(np.abs(core.project(record, list(corners.values())) - np.array(list(marks.values()))).max())
|
||||
check("camera_of(the truth camera) draws each corner where Blender does, within 0.01 px", off < 0.01, off)
|
||||
|
||||
# --- compute only ----------------------------------------------------------------------------------------------------
|
||||
before = sorted(o.name for o in bpy.data.objects)
|
||||
receipt, only = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box)
|
||||
check("compute only: accepted, the record in the receipt, no object made", receipt["status"] == "accepted" and only and only["camera"] is None
|
||||
and sorted(o.name for o in bpy.data.objects) == before and len(only["residuals"]) == 24, [receipt["message"], only and only["model"]])
|
||||
check("auto takes the free model on a view cropped off-axis", only and only["model"] == "free", only and only["tried"])
|
||||
|
||||
# --- stood as a camera, and the scene rendered again through it ---------------------------------------------------
|
||||
scene.render.resolution_x, scene.render.resolution_y = 320, 200 # the action sets the frame, not the caller
|
||||
receipt, solved = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", camera_name="Solved", width=WIDTH)
|
||||
stood = bpy.data.objects.get("Solved")
|
||||
check("solve_camera with camera_name: accepted, a camera object, the render size set to the box", receipt["status"] == "accepted" and stood is not None
|
||||
and stood.type == "CAMERA" and (scene.render.resolution_x, scene.render.resolution_y) == (WIDTH, HEIGHT), receipt["message"])
|
||||
R["record"] = {k: solved[k] for k in ("lens", "lens_band", "lens_at_bound", "rms", "median", "left_out", "model", "c", "azimuth", "elevation", "distance", "roll")}
|
||||
place = float((stood.matrix_world.translation - truth.matrix_world.translation).length)
|
||||
check("the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound",
|
||||
abs(solved["lens"] - 50.0) < 1.0 and place < 0.1 and solved["rms"] < 0.2 and solved["lens_at_bound"] is None, [solved["lens"], place, solved["rms"]])
|
||||
check("the centre is solved: the truth's shifts within 0.005 of a frame width", abs(stood.data.shift_x - 0.08) < 0.005 and abs(stood.data.shift_y + 0.05) < 0.005,
|
||||
[stood.data.shift_x, stood.data.shift_y])
|
||||
worst = max(float(np.hypot(*np.subtract(drawn(stood, p), marks[k]))) for k, p in corners.items())
|
||||
check("Blender's projection through the stood camera draws each corner within 0.5 px of its mark", worst < 0.5, worst)
|
||||
second = silhouette(stood, OUT + ".solved.png")
|
||||
miss = 1.0 - float((first & second).sum() / (first | second).sum())
|
||||
R["iouMiss"] = miss
|
||||
# 1 - IoU of the two silhouettes. Shipped 0.000168; with shift_y's sign flipped in core.blender (M5) 0.6489: the bound is their geometric mean.
|
||||
check("the re-render's silhouette matches the first: 1 - IoU under 0.0105", miss < 0.0105, miss)
|
||||
|
||||
# --- again under the same name updates the one camera; a held lens is held ------------------------------------------
|
||||
receipt, held = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", lens=85, camera_name="Solved", width=400)
|
||||
check("a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300", receipt["status"] == "accepted"
|
||||
and [o.name for o in bpy.data.objects if o.type == "CAMERA"] == ["Solved", "Truth"] and abs(stood.data.lens - 85.0) < 1e-4
|
||||
and held["lens_band"] == [85.0, 85.0] and (scene.render.resolution_x, scene.render.resolution_y) == (400, 300), [receipt["message"], held and held["lens"]])
|
||||
|
||||
# --- refusals are failed receipts that name the cause ----------------------------------------------------------------
|
||||
five = "; ".join(pixels.split("; ")[:5])
|
||||
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=five, box=box)
|
||||
check("five points: failed, naming the count", receipt["status"] == "failed" and "5 points" in receipt["message"], receipt["message"])
|
||||
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, camera_name="Known")
|
||||
check("camera_name of a mesh object: failed, nothing changed", receipt["status"] == "failed" and "not a camera" in receipt["message"]
|
||||
and bpy.data.objects["Known"].type == "MESH", receipt["message"])
|
||||
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box="0,0,0,600")
|
||||
check("a box of no width: failed, naming it", receipt["status"] == "failed" and "no width" in receipt["message"], receipt["message"])
|
||||
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
|
||||
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
|
||||
|
||||
R["ok"] = all(c["ok"] for c in R["checks"])
|
||||
for c in R["checks"]:
|
||||
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
|
||||
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
|
||||
sys.exit(0 if R["ok"] else 1)
|
||||
146
surfaces/blender/tests/live/reference.result.json
Normal file
146
surfaces/blender/tests/live/reference.result.json
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
{
|
||||
"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"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "fixture: the scene covers part of the frame and touches no edge",
|
||||
"ok": true,
|
||||
"detail": 0.1361375
|
||||
},
|
||||
{
|
||||
"name": "camera_of(the truth camera) draws each corner where Blender does, within 0.01 px",
|
||||
"ok": true,
|
||||
"detail": 6.941722509168358e-05
|
||||
},
|
||||
{
|
||||
"name": "compute only: accepted, the record in the receipt, no object made",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
"Operator brokkr_reference.solve_camera finished.",
|
||||
"free"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "auto takes the free model on a view cropped off-axis",
|
||||
"ok": true,
|
||||
"detail": {
|
||||
"upright": {
|
||||
"rms": 1.380259942769221,
|
||||
"left_out": 1.5572430492976839,
|
||||
"lens": 48.08928208959338
|
||||
},
|
||||
"rolled": {
|
||||
"rms": 0.6797349192884168,
|
||||
"left_out": 0.8350092431422779,
|
||||
"lens": 48.499059377417225
|
||||
},
|
||||
"free": {
|
||||
"rms": 0.03555833513434369,
|
||||
"left_out": 0.04252972975472319,
|
||||
"lens": 50.02266319807241
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "solve_camera with camera_name: accepted, a camera object, the render size set to the box",
|
||||
"ok": true,
|
||||
"detail": "Operator brokkr_reference.solve_camera finished."
|
||||
},
|
||||
{
|
||||
"name": "the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
50.02266319807241,
|
||||
0.004567543465755453,
|
||||
0.03555833513434369
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "the centre is solved: the truth's shifts within 0.005 of a frame width",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
0.079900361597538,
|
||||
-0.051553647965192795
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Blender's projection through the stood camera draws each corner within 0.5 px of its mark",
|
||||
"ok": true,
|
||||
"detail": 0.03400179965902824
|
||||
},
|
||||
{
|
||||
"name": "the re-render's silhouette matches the first: 1 - IoU under 0.0105",
|
||||
"ok": true,
|
||||
"detail": 0.00016831152933971527
|
||||
},
|
||||
{
|
||||
"name": "a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300",
|
||||
"ok": true,
|
||||
"detail": [
|
||||
"Operator brokkr_reference.solve_camera finished.",
|
||||
85.0
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "five points: failed, naming the count",
|
||||
"ok": true,
|
||||
"detail": "Error: 5 points are named in both world and pixels; six are needed"
|
||||
},
|
||||
{
|
||||
"name": "camera_name of a mesh object: failed, nothing changed",
|
||||
"ok": true,
|
||||
"detail": "Error: 'Known' is an object that is not a camera."
|
||||
},
|
||||
{
|
||||
"name": "a box of no width: failed, naming it",
|
||||
"ok": true,
|
||||
"detail": "Error: box [0.0, 0.0, 0.0, 600.0] has no width: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0"
|
||||
}
|
||||
],
|
||||
"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"
|
||||
],
|
||||
"record": {
|
||||
"lens": 50.02266319807241,
|
||||
"lens_band": [
|
||||
50.02266319807241,
|
||||
50.02266319807241
|
||||
],
|
||||
"lens_at_bound": null,
|
||||
"rms": 0.03555833513434369,
|
||||
"median": 0.036713200453055594,
|
||||
"left_out": 0.04252972975472319,
|
||||
"model": "free",
|
||||
"c": [
|
||||
336.07971210679585,
|
||||
258.7570824524072
|
||||
],
|
||||
"azimuth": 137.66552423487752,
|
||||
"elevation": 19.81349852084873,
|
||||
"distance": 11.315569478894277,
|
||||
"roll": -1.8445361216036547
|
||||
},
|
||||
"iouMiss": 0.00016831152933971527,
|
||||
"ok": true
|
||||
}
|
||||
Loading…
Reference in a new issue