mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 18:22:25 +00:00
feat: export Director cameras for Blender
This commit is contained in:
1 parent
f2c6ff082d
commit
9f32bf3d92
12 files changed
+1536
-1
No files matched your search
@@ -0,0 +1,266 @@
|
||||
"""Import camera-only GEV JSON. Python validation needs no Blender installation.
|
||||
|
||||
Blender console: import camera_import; camera_import.import_file('/path/camera.json')
|
||||
CLI: blender --background --factory-startup --disable-autoexec --threads 1
|
||||
--python tools/blender/camera_import.py -- camera.json output.blend
|
||||
No image, geometry, network access or rendering is performed.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
SCHEMA = "gev.camera-manifest.v1"
|
||||
MAX_BYTES = 64 * 1024 * 1024
|
||||
MAX_FRAMES = 100000
|
||||
|
||||
|
||||
def _number(value, label, low, high, integer=False):
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
||||
raise ValueError(f"{label}: expected a finite number")
|
||||
if not low <= value <= high or (integer and int(value) != value):
|
||||
raise ValueError(f"{label}: outside supported range")
|
||||
return int(value) if integer else value
|
||||
|
||||
|
||||
def _text(value, label):
|
||||
if not isinstance(value, str) or not value.strip() or len(value) > 4096:
|
||||
raise ValueError(f"{label}: expected a nonempty string")
|
||||
return value
|
||||
|
||||
|
||||
def _near(actual, expected, label, tolerance=1e-8):
|
||||
if not math.isclose(actual, expected, rel_tol=1e-10, abs_tol=tolerance):
|
||||
raise ValueError(f"{label}: does not match the declared timing or projection")
|
||||
|
||||
|
||||
def _vector(value, label):
|
||||
if not isinstance(value, list) or len(value) != 3:
|
||||
raise ValueError(f"{label}: expected three coordinates")
|
||||
for component in value:
|
||||
_number(component, label, -100001, 100001)
|
||||
return value
|
||||
|
||||
|
||||
def _dot(a, b):
|
||||
return sum(x * y for x, y in zip(a, b))
|
||||
|
||||
|
||||
def _cross(a, b):
|
||||
return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]
|
||||
|
||||
|
||||
def _frame_at(seconds, rate):
|
||||
value = seconds * rate
|
||||
return (round(value) if abs(value - round(value)) < 1e-9 else math.ceil(value)) + 1
|
||||
|
||||
|
||||
def validate_manifest(data):
|
||||
"""Validate the complete data before importing bpy or mutating a scene."""
|
||||
if not isinstance(data, dict) or data.get("schema") != SCHEMA:
|
||||
raise ValueError("Unsupported GEV camera manifest schema")
|
||||
source = data["source"]
|
||||
_text(source["sceneId"], "scene ID")
|
||||
if source.get("sampling") != "director-seek-authored-timing":
|
||||
raise ValueError("Unsupported camera sampling semantics")
|
||||
coordinates = data["coordinates"]
|
||||
required = {"units": "meters", "axes": "east-north-up", "heightDatum": "WGS84-ellipsoid", "cameraAxes": "X-right,Y-up,-Z-forward"}
|
||||
if any(coordinates.get(key) != value for key, value in required.items()):
|
||||
raise ValueError("Explicit ENU meters, WGS84 ellipsoid and Blender camera axes required")
|
||||
origin = coordinates["origin"]
|
||||
for key, low, high in [("lat", -90, 90), ("lon", -180, 180), ("height", -12000, 1e9)]:
|
||||
_number(origin[key], f"origin.{key}", low, high)
|
||||
timeline = data["timeline"]
|
||||
fps = timeline["fps"]
|
||||
for key in ["numerator", "denominator"]:
|
||||
_number(fps[key], f"fps.{key}", 1, 1000000, integer=True)
|
||||
rate = _number(fps["numerator"] / fps["denominator"], "fps", 1, 240)
|
||||
for key in ["width", "height"]:
|
||||
_number(timeline[key], key, 4, 16384, integer=True)
|
||||
if timeline["pixelAspect"] != [1, 1] or any(isinstance(value, bool) for value in timeline["pixelAspect"]):
|
||||
raise ValueError("Only square pixels are supported")
|
||||
if timeline["frameStart"] != 1 or isinstance(timeline["frameStart"], bool):
|
||||
raise ValueError("Timeline must start at frame 1")
|
||||
count = _number(timeline["frameEnd"], "frameEnd", 1, MAX_FRAMES, integer=True)
|
||||
_number(timeline["durationSec"], "durationSec", 0, 100000)
|
||||
if count != _frame_at(timeline["durationSec"], rate) - 1:
|
||||
raise ValueError("Frame count differs from declared duration and fps")
|
||||
camera = data["camera"]
|
||||
if camera["projection"] != "perspective" or camera["sensorFit"] != "HORIZONTAL":
|
||||
raise ValueError("Only a perspective horizontal-sensor camera is supported")
|
||||
sensor = _number(camera["sensorWidthMm"], "sensorWidthMm", 1, 100)
|
||||
hfov = _number(camera["horizontalFovRadians"], "horizontalFovRadians", math.pi/180, math.pi*179/180)
|
||||
lens = _number(camera["lensMm"], "lensMm", 1, 10000)
|
||||
_near(lens, sensor / (2 * math.tan(hfov / 2)), "lens")
|
||||
_near(_number(camera["verticalFovRadians"], "verticalFovRadians", 0, math.pi), 2 * math.atan(math.tan(hfov / 2) * timeline["height"] / timeline["width"]), "vertical FOV")
|
||||
shots = data["shots"]
|
||||
if not isinstance(shots, list) or not 1 <= len(shots) <= count:
|
||||
raise ValueError("Expected bounded nonempty shots")
|
||||
ids = set()
|
||||
elapsed = 0
|
||||
rounding = 0
|
||||
for shot in shots:
|
||||
shot_id = _text(shot["id"], "shot ID")
|
||||
if shot_id in ids:
|
||||
raise ValueError("Duplicate shot ID")
|
||||
ids.add(shot_id)
|
||||
for key in ["startTimeSec", "endTimeSec", "durationSec", "holdSec"]:
|
||||
_number(shot[key], key, 0, 100000)
|
||||
if shot["durationSec"] <= 0:
|
||||
raise ValueError("Shot duration must be positive")
|
||||
_near(shot["startTimeSec"], elapsed, "shot start")
|
||||
increment = shot["durationSec"] + shot["holdSec"] - rounding
|
||||
next_time = elapsed + increment
|
||||
rounding = next_time - elapsed - increment
|
||||
elapsed = next_time
|
||||
_near(shot["endTimeSec"], elapsed, "shot end")
|
||||
for key, expected in [("frameStart", _frame_at(shot["startTimeSec"], rate)), ("frameEndExclusive", _frame_at(elapsed, rate))]:
|
||||
_number(shot[key], key, 1, count + 1, integer=True)
|
||||
if shot[key] != expected:
|
||||
raise ValueError("Shot frame boundaries do not match timing")
|
||||
if shot["frameStart"] >= shot["frameEndExclusive"]:
|
||||
raise ValueError("Shot has no sampled frames")
|
||||
_near(elapsed, timeline["durationSec"], "total duration")
|
||||
frames = data["frames"]
|
||||
if not isinstance(frames, list) or len(frames) != count:
|
||||
raise ValueError("Frame count differs from frame samples")
|
||||
shot_index = 0
|
||||
for index, sample in enumerate(frames, start=1):
|
||||
if sample["frame"] != index or isinstance(sample["frame"], bool):
|
||||
raise ValueError("Frames must be sequential integers starting at 1")
|
||||
_near(_number(sample["timeSec"], "timeSec", 0, 100000), (index - 1) * fps["denominator"] / fps["numerator"], "sample time")
|
||||
while index >= shots[shot_index]["frameEndExclusive"] and shot_index < len(shots) - 1:
|
||||
shot_index += 1
|
||||
if sample["shotId"] != shots[shot_index]["id"]:
|
||||
raise ValueError("Sample references the wrong shot")
|
||||
location = _vector(sample["position"], "position")
|
||||
if _dot(location, location) > 100000**2 + 0.01:
|
||||
raise ValueError("Camera exceeds 100 km local-origin limit")
|
||||
basis = sample["basisColumns"]
|
||||
if not isinstance(basis, list) or len(basis) != 3:
|
||||
raise ValueError("Expected three camera basis columns")
|
||||
x, y, z = [_vector(column, "basis") for column in basis]
|
||||
for column in [x, y, z]:
|
||||
_near(_dot(column, column), 1, "unit camera axis", 1e-6)
|
||||
for a, b in [(x, y), (y, z), (z, x)]:
|
||||
_near(_dot(a, b), 0, "orthogonal camera axes", 1e-6)
|
||||
_near(_dot(_cross(x, y), z), 1, "right-handed camera basis", 1e-6)
|
||||
return data
|
||||
|
||||
|
||||
def read_manifest(path):
|
||||
"""Read bounded JSON only. No imports, URLs or expressions are evaluated."""
|
||||
with Path(path).open("rb") as stream:
|
||||
payload = stream.read(MAX_BYTES + 1)
|
||||
if len(payload) > MAX_BYTES:
|
||||
raise ValueError("Camera manifest exceeds 64 MiB")
|
||||
return validate_manifest(json.loads(payload))
|
||||
|
||||
|
||||
def import_manifest(data):
|
||||
"""Create a new scene with editable per-shot cameras; preserve existing scenes."""
|
||||
validate_manifest(data)
|
||||
import bpy
|
||||
from mathutils import Matrix, Vector
|
||||
|
||||
scene = bpy.data.scenes.new(f"GEV {data['source'].get('sceneTitle') or data['source']['sceneId']}")
|
||||
scene.unit_settings.system = "METRIC"
|
||||
scene.unit_settings.scale_length = 1.0
|
||||
timeline = data["timeline"]
|
||||
rate = timeline["fps"]["numerator"] / timeline["fps"]["denominator"]
|
||||
scene.render.fps = round(rate)
|
||||
scene.render.fps_base = round(rate) / rate
|
||||
scene.render.resolution_x = int(timeline["width"])
|
||||
scene.render.resolution_y = int(timeline["height"])
|
||||
scene.render.resolution_percentage = 100
|
||||
scene.render.pixel_aspect_x = scene.render.pixel_aspect_y = 1.0
|
||||
scene.frame_start = 1
|
||||
scene.frame_end = int(timeline["frameEnd"])
|
||||
scene["gev_schema"] = SCHEMA
|
||||
scene["gev_source"] = json.dumps(data["source"], ensure_ascii=False)
|
||||
scene["gev_coordinates"] = json.dumps(data["coordinates"], ensure_ascii=False)
|
||||
scene["gev_timeline"] = json.dumps(timeline)
|
||||
root = bpy.data.objects.new("GEV ENU origin", None)
|
||||
scene.collection.objects.link(root)
|
||||
cameras = {}
|
||||
for shot in data["shots"]:
|
||||
camera_data = bpy.data.cameras.new(f"GEV {shot['id']}")
|
||||
camera_data.type = "PERSP"
|
||||
camera_data.sensor_fit = "HORIZONTAL"
|
||||
camera_data.sensor_width = data["camera"]["sensorWidthMm"]
|
||||
camera_data.lens = data["camera"]["lensMm"]
|
||||
camera_data.clip_start = 0.01
|
||||
camera_data.clip_end = 200000
|
||||
camera = bpy.data.objects.new(f"GEV {shot['id']}", camera_data)
|
||||
camera.rotation_mode = "QUATERNION"
|
||||
camera.parent = root
|
||||
camera["gev_shot"] = json.dumps(shot, ensure_ascii=False)
|
||||
camera["gev_scene_id"] = data["source"]["sceneId"]
|
||||
scene.collection.objects.link(camera)
|
||||
cameras[shot["id"]] = camera
|
||||
marker = scene.timeline_markers.new(f"GEV {shot['id']}", frame=int(shot["frameStart"]))
|
||||
marker.camera = camera
|
||||
previous = {}
|
||||
for sample in data["frames"]:
|
||||
camera = cameras[sample["shotId"]]
|
||||
# Manifest vectors are columns, while mathutils.Matrix accepts rows.
|
||||
basis = Matrix(sample["basisColumns"]).transposed()
|
||||
rotation = basis.to_quaternion().normalized()
|
||||
old = previous.get(sample["shotId"])
|
||||
if old is not None and rotation.dot(old) < 0:
|
||||
rotation.negate()
|
||||
previous[sample["shotId"]] = rotation.copy()
|
||||
camera.location = Vector(sample["position"])
|
||||
camera.rotation_quaternion = rotation
|
||||
camera.keyframe_insert(data_path="location", frame=sample["frame"])
|
||||
camera.keyframe_insert(data_path="rotation_quaternion", frame=sample["frame"])
|
||||
# Blender defaults to Bezier, which would alter motion between sampled frames.
|
||||
for camera in cameras.values():
|
||||
action = camera.animation_data.action
|
||||
if hasattr(action, "layers") and action.layers:
|
||||
for layer in action.layers:
|
||||
for strip in layer.strips:
|
||||
bag = strip.channelbag(camera.animation_data.action_slot)
|
||||
for curve in bag.fcurves if bag else []:
|
||||
for key in curve.keyframe_points:
|
||||
key.interpolation = "LINEAR"
|
||||
else:
|
||||
for curve in action.fcurves:
|
||||
for key in curve.keyframe_points:
|
||||
key.interpolation = "LINEAR"
|
||||
scene.camera = cameras[data["shots"][0]["id"]]
|
||||
if bpy.context.window:
|
||||
bpy.context.window.scene = scene
|
||||
scene.frame_set(1)
|
||||
return scene
|
||||
|
||||
|
||||
def import_file(path):
|
||||
"""Import a camera JSON file into a new Blender scene without rendering."""
|
||||
return import_manifest(read_manifest(path))
|
||||
|
||||
|
||||
def new_blend_output(path):
|
||||
"""Require Blender's final extension before checking overwrite protection."""
|
||||
output = Path(path).resolve()
|
||||
if output.suffix != '.blend':
|
||||
raise ValueError('Output must end in lowercase .blend')
|
||||
if output.exists():
|
||||
raise FileExistsError('Output already exists; choose a new .blend path')
|
||||
return output
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
args = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
|
||||
if len(args) != 2:
|
||||
raise SystemExit("Usage: blender --background --factory-startup --disable-autoexec --threads 1 --python camera_import.py -- camera.json output.blend")
|
||||
output = new_blend_output(args[1])
|
||||
import_file(args[0])
|
||||
import bpy
|
||||
preview = bpy.context.preferences.filepaths.file_preview_type
|
||||
try:
|
||||
bpy.context.preferences.filepaths.file_preview_type = 'NONE'
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(output.resolve()), check_existing=False)
|
||||
finally:
|
||||
bpy.context.preferences.filepaths.file_preview_type = preview
|
||||
print("CAMERA_IMPORT_OK")
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Synthetic CPU-only Blender import, projection and .blend round-trip check.
|
||||
|
||||
blender --background --factory-startup --disable-autoexec --threads 1
|
||||
--python tools/blender/check_import.py -- fixture-directory
|
||||
No renderer or GPU context is requested. All landmarks are synthetic empties.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import bpy
|
||||
from bpy_extras.object_utils import world_to_camera_view
|
||||
from mathutils import Vector
|
||||
|
||||
spec = importlib.util.spec_from_file_location("camera_import", Path(__file__).with_name("camera_import.py"))
|
||||
importer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(importer)
|
||||
args = sys.argv[sys.argv.index("--") + 1:]
|
||||
if len(args) != 1:
|
||||
raise SystemExit("Expected one fixture directory")
|
||||
directory = Path(args[0])
|
||||
reference = json.loads((directory / "projection-reference.json").read_text())
|
||||
original_names = set(bpy.data.scenes.keys())
|
||||
original_settings = {scene.name: (scene.render.resolution_x, scene.render.resolution_y, scene.frame_end) for scene in bpy.data.scenes}
|
||||
bpy.context.preferences.filepaths.file_preview_type = 'NONE'
|
||||
|
||||
|
||||
def block(scene, name, center, size):
|
||||
"""Tiny owned synthetic blockout, so the saved rig has an editable set."""
|
||||
x, y, z = center
|
||||
sx, sy, sz = [value / 2 for value in size]
|
||||
vertices = [(x+dx*sx, y+dy*sy, z+dz*sz) for dx, dy, dz in [(-1,-1,-1),(1,-1,-1),(1,1,-1),(-1,1,-1),(-1,-1,1),(1,-1,1),(1,1,1),(-1,1,1)]]
|
||||
faces = [(0,3,2,1),(4,5,6,7),(0,1,5,4),(1,2,6,5),(2,3,7,6),(3,0,4,7)]
|
||||
mesh = bpy.data.meshes.new(name)
|
||||
mesh.from_pydata(vertices, [], faces)
|
||||
mesh.update()
|
||||
obj = bpy.data.objects.new(name, mesh)
|
||||
scene.collection.objects.link(obj)
|
||||
|
||||
|
||||
cases = []
|
||||
for case in reference["cases"]:
|
||||
manifest = importer.read_manifest(directory / case["manifest"])
|
||||
scene = importer.import_manifest(manifest)
|
||||
# All validation occurs before bpy mutation.
|
||||
malformed = json.loads(json.dumps(manifest))
|
||||
malformed["frames"][-1]["basisColumns"][0] = [2, 0, 0]
|
||||
names = set(bpy.data.scenes.keys())
|
||||
objects = set(bpy.data.objects.keys())
|
||||
try:
|
||||
importer.import_manifest(malformed)
|
||||
raise AssertionError("Malformed transform was accepted")
|
||||
except ValueError:
|
||||
assert set(bpy.data.scenes.keys()) == names
|
||||
assert set(bpy.data.objects.keys()) == objects
|
||||
for index, point in enumerate(case["checks"][0]["points"]):
|
||||
landmark = bpy.data.objects.new(f"Synthetic landmark {index}", None)
|
||||
landmark.location = point["position"]
|
||||
scene.collection.objects.link(landmark)
|
||||
block(scene, 'Synthetic ground, no map data', [0, 0, -1], [1400, 1400, 2])
|
||||
for index in [0, 6, 9]:
|
||||
sample = manifest['frames'][index]
|
||||
point = case['checks'][index]['points'][0]['position']
|
||||
direction = [(point[i]-sample['position'][i])/100 for i in range(3)]
|
||||
distance = -sample['position'][2]/direction[2]
|
||||
center = [sample['position'][i]+direction[i]*distance for i in range(2)] + [10]
|
||||
block(scene, f'Synthetic block {index}', center, [24, 24, 20])
|
||||
cases.append((case, manifest, scene.name))
|
||||
|
||||
# JSON may spell an integer-valued number as 1920.0. Blender RNA requires ints.
|
||||
float_case = dict(reference['cases'][0], name='integer-valued JSON floats')
|
||||
float_manifest = importer.read_manifest(directory / float_case['manifest'])
|
||||
for key in ['width', 'height', 'frameEnd']:
|
||||
float_manifest['timeline'][key] = float(float_manifest['timeline'][key])
|
||||
for shot in float_manifest['shots']:
|
||||
shot['frameStart'] = float(shot['frameStart'])
|
||||
float_scene = importer.import_manifest(float_manifest)
|
||||
cases.append((float_case, float_manifest, float_scene.name))
|
||||
|
||||
|
||||
def check_all():
|
||||
max_error = 0.0
|
||||
projection_count = 0
|
||||
for case, manifest, scene_name in cases:
|
||||
scene = bpy.data.scenes[scene_name]
|
||||
bpy.context.window.scene = scene
|
||||
bpy.context.view_layer.update()
|
||||
metadata = json.loads(scene["gev_source"])
|
||||
assert metadata["sceneId"] == manifest["source"]["sceneId"]
|
||||
assert json.loads(scene["gev_coordinates"]) == manifest["coordinates"]
|
||||
assert json.loads(scene["gev_timeline"]) == manifest["timeline"]
|
||||
assert scene.frame_start == 1 and scene.frame_end == len(manifest["frames"])
|
||||
expected_rate = manifest["timeline"]["fps"]["numerator"] / manifest["timeline"]["fps"]["denominator"]
|
||||
assert abs(scene.render.fps / scene.render.fps_base - expected_rate) < 2e-6
|
||||
assert scene.unit_settings.scale_length == 1
|
||||
assert scene.render.resolution_x == manifest["timeline"]["width"]
|
||||
assert scene.render.resolution_y == manifest["timeline"]["height"]
|
||||
cameras = {json.loads(obj["gev_shot"])["id"]: obj for obj in scene.objects if "gev_shot" in obj}
|
||||
assert set(cameras) == {shot["id"] for shot in manifest["shots"]}
|
||||
for shot in manifest["shots"]:
|
||||
assert json.loads(cameras[shot["id"]]["gev_shot"]) == shot
|
||||
for item in case["checks"]:
|
||||
scene.frame_set(item["frame"])
|
||||
active = scene.camera
|
||||
camera = cameras[item["shotId"]]
|
||||
assert active == camera, "Timeline marker selected the wrong camera"
|
||||
assert camera.data.sensor_fit == "HORIZONTAL"
|
||||
assert abs(camera.data.lens - manifest["camera"]["lensMm"]) < 1e-5
|
||||
for point in item["points"]:
|
||||
projected = world_to_camera_view(scene, camera, Vector(point["position"]))
|
||||
assert projected.z > 0, (case['name'], item['frame'], 'landmark behind camera')
|
||||
error = max(abs(projected.x - point["uv"][0]), abs(projected.y - point["uv"][1]))
|
||||
max_error = max(error, max_error)
|
||||
assert error < 2e-5, (case["name"], item["frame"], error)
|
||||
projection_count += 1
|
||||
for name in original_names:
|
||||
scene = bpy.data.scenes[name]
|
||||
assert (scene.render.resolution_x, scene.render.resolution_y, scene.frame_end) == original_settings[name]
|
||||
return max_error, projection_count
|
||||
|
||||
|
||||
before_error, count = check_all()
|
||||
blend = directory / "synthetic-cameras.blend"
|
||||
if blend.exists():
|
||||
raise SystemExit("Synthetic output already exists; choose a fresh fixture directory")
|
||||
bpy.context.window.scene = bpy.data.scenes[cases[0][2]]
|
||||
bpy.context.scene.frame_set(1)
|
||||
for area in bpy.context.screen.areas:
|
||||
if area.type == 'VIEW_3D':
|
||||
area.spaces.active.region_3d.view_perspective = 'CAMERA'
|
||||
bpy.ops.wm.save_as_mainfile(filepath=str(blend.resolve()), check_existing=False)
|
||||
assert blend.stat().st_size > 10000
|
||||
bpy.ops.wm.open_mainfile(filepath=str(blend.resolve()), load_ui=False, use_scripts=False)
|
||||
assert bpy.context.scene.name == cases[0][2], 'Demo must reopen on the blockout scene'
|
||||
after_error, after_count = check_all()
|
||||
assert after_count == count
|
||||
receipt = {"state": "BLENDER_CAMERA_PROJECTION_OK", "blenderVersion": bpy.app.version_string, "cases": len(cases), "projectionsBeforeSave": count, "projectionsAfterReload": after_count, "maxUvError": max(before_error, after_error), "rendered": False, "gpuRequested": False, "blend": blend.name}
|
||||
(directory / "blender-receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
||||
print(json.dumps(receipt))
|
||||
@@ -0,0 +1,173 @@
|
||||
#!/usr/bin/env node
|
||||
/** Generate tiny, provider-free fixtures plus an independent Cesium projection oracle. */
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { parseArgs } from 'node:util';
|
||||
import * as C from 'cesium';
|
||||
import { exportCameraManifest } from '../../src/tooling/blenderCamera.js';
|
||||
import { sceneSeekState } from '../../src/director/timeline.js';
|
||||
|
||||
const { values } = parseArgs({ options: { output: { type: 'string' } } });
|
||||
if (!values.output)
|
||||
throw new Error(
|
||||
'Usage: node tools/blender/make_fixture.mjs --output directory',
|
||||
);
|
||||
const output = resolve(values.output);
|
||||
await mkdir(output, { recursive: true });
|
||||
const pose = (values) => ({
|
||||
lat: 39.7003,
|
||||
lon: -105.0004,
|
||||
alt: 1750,
|
||||
heading: 20,
|
||||
pitch: -25,
|
||||
roll: 17,
|
||||
altitudeReference: 'ellipsoid',
|
||||
...values,
|
||||
});
|
||||
const finish = pose({
|
||||
lat: 39.7005,
|
||||
lon: -104.9995,
|
||||
alt: 1800,
|
||||
heading: 95,
|
||||
pitch: -40,
|
||||
roll: -25,
|
||||
});
|
||||
const cut = pose({
|
||||
lat: 39.6998,
|
||||
lon: -105.0003,
|
||||
alt: 1725,
|
||||
heading: 230,
|
||||
pitch: -15,
|
||||
roll: 35,
|
||||
});
|
||||
const document = {
|
||||
version: 6,
|
||||
scenes: [
|
||||
{
|
||||
id: 'synthetic-scene',
|
||||
title: 'Synthetic camera bridge',
|
||||
shots: [
|
||||
{
|
||||
id: 'rolled-move',
|
||||
title: 'Move and hold',
|
||||
durationSec: 0.2,
|
||||
holdSec: 0.1,
|
||||
camera: finish,
|
||||
move: { from: pose({}), easing: 'cubic-in-out' },
|
||||
},
|
||||
{
|
||||
id: 'cut',
|
||||
title: 'Explicit cut and hold',
|
||||
durationSec: 0.2,
|
||||
holdSec: 0.1,
|
||||
camera: cut,
|
||||
move: { from: cut, easing: 'linear' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const origin = { lat: 39.7, lon: -105, height: 1600 };
|
||||
const anchor = C.Cartesian3.fromDegrees(origin.lon, origin.lat, origin.height);
|
||||
const worldToLocal = C.Matrix4.inverseTransformation(
|
||||
C.Transforms.eastNorthUpToFixedFrame(anchor),
|
||||
new C.Matrix4(),
|
||||
);
|
||||
const cases = [];
|
||||
for (const [name, width, height] of [
|
||||
['landscape', 1920, 1080],
|
||||
['portrait', 1080, 1920],
|
||||
]) {
|
||||
const manifest = exportCameraManifest(document, {
|
||||
origin,
|
||||
fps: { numerator: 30000, denominator: 1001 },
|
||||
width,
|
||||
height,
|
||||
horizontalFovDegrees: 70,
|
||||
});
|
||||
await writeFile(
|
||||
resolve(output, `${name}.camera.json`),
|
||||
JSON.stringify(manifest, null, 2) + '\n',
|
||||
);
|
||||
const camera = new C.Camera({
|
||||
drawingBufferWidth: width,
|
||||
drawingBufferHeight: height,
|
||||
mapProjection: new C.GeographicProjection(),
|
||||
mode: C.SceneMode.SCENE3D,
|
||||
});
|
||||
camera.frustum.aspectRatio = width / height;
|
||||
camera.frustum.fov =
|
||||
width >= height
|
||||
? manifest.camera.horizontalFovRadians
|
||||
: manifest.camera.verticalFovRadians;
|
||||
camera.frustum.near = 0.01;
|
||||
camera.frustum.far = 200000;
|
||||
const checks = [];
|
||||
for (const sample of manifest.frames) {
|
||||
const state = sceneSeekState(
|
||||
document.scenes[0],
|
||||
sample.timeSec / manifest.timeline.durationSec,
|
||||
(_scene, shot) => shot.durationSec + shot.holdSec,
|
||||
(_scene, shot) => shot.holdSec,
|
||||
);
|
||||
const p = state.camera;
|
||||
camera.setView({
|
||||
destination: C.Cartesian3.fromDegrees(p.lon, p.lat, p.alt),
|
||||
orientation: {
|
||||
heading: C.Math.toRadians(p.heading),
|
||||
pitch: C.Math.toRadians(p.pitch),
|
||||
roll: C.Math.toRadians(p.roll),
|
||||
},
|
||||
});
|
||||
const projectionView = C.Matrix4.multiply(
|
||||
camera.frustum.projectionMatrix,
|
||||
camera.viewMatrix,
|
||||
new C.Matrix4(),
|
||||
);
|
||||
const points = [];
|
||||
for (const [right, up] of [
|
||||
[0, 0],
|
||||
[25, 0],
|
||||
[-25, 15],
|
||||
[0, -20],
|
||||
]) {
|
||||
const world = C.Cartesian3.clone(camera.positionWC);
|
||||
for (const [axis, distance] of [
|
||||
[camera.directionWC, 100],
|
||||
[camera.rightWC, right],
|
||||
[camera.upWC, up],
|
||||
]) {
|
||||
C.Cartesian3.add(
|
||||
world,
|
||||
C.Cartesian3.multiplyByScalar(axis, distance, new C.Cartesian3()),
|
||||
world,
|
||||
);
|
||||
}
|
||||
const clip = C.Matrix4.multiplyByVector(
|
||||
projectionView,
|
||||
new C.Cartesian4(world.x, world.y, world.z, 1),
|
||||
new C.Cartesian4(),
|
||||
);
|
||||
const local = C.Matrix4.multiplyByPoint(
|
||||
worldToLocal,
|
||||
world,
|
||||
new C.Cartesian3(),
|
||||
);
|
||||
points.push({
|
||||
position: [local.x, local.y, local.z],
|
||||
uv: [(clip.x / clip.w + 1) / 2, (clip.y / clip.w + 1) / 2],
|
||||
});
|
||||
}
|
||||
checks.push({ frame: sample.frame, shotId: sample.shotId, points });
|
||||
}
|
||||
cases.push({ name, manifest: `${name}.camera.json`, checks });
|
||||
}
|
||||
await writeFile(
|
||||
resolve(output, 'scene.json'),
|
||||
JSON.stringify(document, null, 2) + '\n',
|
||||
);
|
||||
await writeFile(
|
||||
resolve(output, 'projection-reference.json'),
|
||||
JSON.stringify({ origin, cases }, null, 2) + '\n',
|
||||
);
|
||||
console.log('CAMERA_FIXTURE_OK');
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Data validation checks. Standard Python only; no Blender or rendering required."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
module_path = Path(__file__).with_name("camera_import.py")
|
||||
if module_path.exists():
|
||||
spec = importlib.util.spec_from_file_location("camera_import", module_path)
|
||||
importer = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(importer)
|
||||
else:
|
||||
importer = None
|
||||
|
||||
|
||||
def fixture():
|
||||
return {
|
||||
"schema": "gev.camera-manifest.v1",
|
||||
"source": {"sceneId": "scene", "sceneTitle": "Fixture", "sampling": "director-seek-authored-timing", "attributions": []},
|
||||
"coordinates": {"units": "meters", "axes": "east-north-up", "heightDatum": "WGS84-ellipsoid", "origin": {"lat": 0, "lon": 0, "height": 0}, "cameraAxes": "X-right,Y-up,-Z-forward"},
|
||||
"camera": {"projection": "perspective", "sensorFit": "HORIZONTAL", "sensorWidthMm": 36, "lensMm": 18, "horizontalFovRadians": math.pi / 2, "verticalFovRadians": math.pi / 2},
|
||||
"timeline": {"fps": {"numerator": 30, "denominator": 1}, "width": 100, "height": 100, "pixelAspect": [1, 1], "frameStart": 1, "frameEnd": 1, "durationSec": 1 / 30},
|
||||
"shots": [{"id": "north", "title": "North", "startTimeSec": 0, "endTimeSec": 1 / 30, "durationSec": 1 / 30, "holdSec": 0, "frameStart": 1, "frameEndExclusive": 2}],
|
||||
"frames": [{"frame": 1, "timeSec": 0, "shotId": "north", "position": [0, 0, 0], "basisColumns": [[1, 0, 0], [0, 0, 1], [0, -1, 0]]}],
|
||||
}
|
||||
|
||||
|
||||
class ValidationTests(unittest.TestCase):
|
||||
def test_validator_exists(self):
|
||||
self.assertIsNotNone(importer, "camera importer is missing")
|
||||
|
||||
def test_valid_manifest_is_not_mutated_and_does_not_import_bpy(self):
|
||||
data = fixture()
|
||||
before = copy.deepcopy(data)
|
||||
importer.validate_manifest(data)
|
||||
self.assertEqual(data, before)
|
||||
self.assertNotIn("bpy", sys.modules)
|
||||
|
||||
def test_rejects_datum_axes_lens_fps_and_timing_mismatches(self):
|
||||
mutations = [
|
||||
lambda m: m.update(schema="other"),
|
||||
lambda m: m["coordinates"].update(heightDatum="MSL"),
|
||||
lambda m: m["coordinates"].update(axes="north-east-down"),
|
||||
lambda m: m["camera"].update(lensMm=35),
|
||||
lambda m: m["camera"].update(lensMm=0.5),
|
||||
lambda m: m["camera"].update(verticalFovRadians=1),
|
||||
lambda m: m["timeline"]["fps"].update(denominator=0),
|
||||
lambda m: m["timeline"].update(frameEnd=2),
|
||||
lambda m: m["timeline"].update(width=1),
|
||||
lambda m: m["timeline"].update(pixelAspect=[2, 1]),
|
||||
lambda m: m["frames"][0].update(frame=2),
|
||||
lambda m: m["frames"][0].update(timeSec=1),
|
||||
lambda m: m["frames"][0].update(shotId="missing"),
|
||||
lambda m: m["shots"][0].update(frameStart=2),
|
||||
lambda m: m["shots"][0].update(endTimeSec=2),
|
||||
lambda m: m["frames"][0].update(position=[100001, 0, 0]),
|
||||
lambda m: m["frames"][0].update(position=[False, 0, 0]),
|
||||
lambda m: m["frames"][0].update(position=[math.nan, 0, 0]),
|
||||
lambda m: m["frames"][0].update(basisColumns=[[1, 0, 0], [1, 0, 0], [0, 0, 1]]),
|
||||
lambda m: m["frames"][0].update(basisColumns=[[-1, 0, 0], [0, 0, 1], [0, -1, 0]]),
|
||||
]
|
||||
for mutate in mutations:
|
||||
data = fixture()
|
||||
mutate(data)
|
||||
with self.subTest(mutation=mutations.index(mutate)):
|
||||
with self.assertRaises((ValueError, TypeError, KeyError)):
|
||||
importer.validate_manifest(data)
|
||||
|
||||
def test_output_extension_is_checked_before_existing_file_guard(self):
|
||||
with tempfile.TemporaryDirectory(prefix='gev-blender-output-') as directory:
|
||||
output = Path(directory) / 'camera.blend'
|
||||
output.write_bytes(b'existing file must survive')
|
||||
with self.assertRaises(ValueError):
|
||||
importer.new_blend_output(Path(directory) / 'camera')
|
||||
with self.assertRaises(FileExistsError):
|
||||
importer.new_blend_output(output)
|
||||
with self.assertRaises(ValueError):
|
||||
importer.new_blend_output(Path(directory) / 'new.BLEND')
|
||||
self.assertEqual(output.read_bytes(), b'existing file must survive')
|
||||
self.assertEqual(importer.new_blend_output(Path(directory) / 'new.blend').name, 'new.blend')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
result = unittest.main(exit=False)
|
||||
if result.result.wasSuccessful():
|
||||
print("IMPORT_VALIDATION_OK")
|
||||
else:
|
||||
sys.exit(1)
|
||||
Reference in new issue
Block a user