M7.7: camera/light rigs and Advanced 3D motion blur, blend modes, track mattes
Layer > Camera > Create Stereo 3D Rig (left/right eye comps with expression-linked eye cameras, Stereo 3D Controls effect, stereo comp through 3D Glasses), Create Orbit Null, Create Cameras from 3D Model; Layer > Light > Create Lights from 3D Model (KHR_lights_punctual), Control Light with Camera, Create Environment Light Background Layer (equirectangular sky drawn through the camera). glTF cameras and punctual lights are parsed by effectcraft-model. Advanced 3D: per-sample motion blur over the comp shutter, and blend modes / track mattes / Preserve Transparency composited through the 2D path in depth order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
f9f8d454e0
commit
8696d1e9ba
@@ -7,8 +7,9 @@
|
||||
//! (base colour, metallic-roughness, normal, occlusion and emissive textures; alpha modes;
|
||||
//! double-sided; `KHR_materials_emissive_strength`, `KHR_materials_unlit`), embedded or
|
||||
//! external PNG/JPEG images with sampler wrap modes, skins and animations (step, linear and
|
||||
//! cubic-spline translation/rotation/scale). Sparse accessors, morph targets, cameras and
|
||||
//! lights are ignored.
|
||||
//! cubic-spline translation/rotation/scale), perspective and orthographic cameras, and
|
||||
//! `KHR_lights_punctual` lights (directional, point, spot). Sparse accessors and morph targets
|
||||
//! are ignored.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -363,6 +364,8 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<
|
||||
matrix,
|
||||
mesh: idx(n, "mesh").filter(|&m| m < meshes.len()),
|
||||
skin: idx(n, "skin"),
|
||||
camera: idx(n, "camera"),
|
||||
light: n.get("extensions").and_then(|e| e.get("KHR_lights_punctual")).and_then(|e| idx(e, "light")),
|
||||
children: arr(n, "children").iter().filter_map(Value::as_u64).map(|c| c as usize).collect(),
|
||||
});
|
||||
}
|
||||
@@ -434,7 +437,54 @@ pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option<Vec<u8>>) -> Result<
|
||||
animations.push(anim);
|
||||
}
|
||||
|
||||
Ok(Model { meshes, nodes, roots, materials, textures, skins, animations })
|
||||
let cameras = arr(&j, "cameras").iter().enumerate().map(|(i, c)| camera(c, i)).collect();
|
||||
let lights = j
|
||||
.get("extensions")
|
||||
.and_then(|e| e.get("KHR_lights_punctual"))
|
||||
.map(|e| arr(e, "lights").iter().enumerate().map(|(i, l)| light(l, i)).collect())
|
||||
.unwrap_or_default();
|
||||
Ok(Model { meshes, nodes, roots, materials, textures, skins, animations, cameras, lights })
|
||||
}
|
||||
|
||||
fn name_or(v: &Value, d: String) -> String {
|
||||
v.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or(d)
|
||||
}
|
||||
|
||||
/// A glTF camera (glTF 2.0 §5.12): `perspective` {yfov, aspectRatio?, znear} or
|
||||
/// `orthographic` {xmag, ymag}.
|
||||
fn camera(c: &Value, i: usize) -> crate::ModelCamera {
|
||||
let projection = match (c.get("type").and_then(Value::as_str), c.get("orthographic")) {
|
||||
(Some("orthographic"), Some(o)) => crate::CameraProjection::Orthographic { xmag: num(o, "xmag", 1.0), ymag: num(o, "ymag", 1.0) },
|
||||
_ => {
|
||||
let p = c.get("perspective").cloned().unwrap_or(Value::Null);
|
||||
crate::CameraProjection::Perspective {
|
||||
yfov: num(&p, "yfov", 0.8).clamp(1e-3, 3.1),
|
||||
aspect: p.get("aspectRatio").and_then(Value::as_f64),
|
||||
znear: num(&p, "znear", 0.01),
|
||||
}
|
||||
}
|
||||
};
|
||||
crate::ModelCamera { name: name_or(c, format!("Camera {}", i + 1)), projection }
|
||||
}
|
||||
|
||||
/// A `KHR_lights_punctual` light: type, color, intensity, range, spot cone angles.
|
||||
fn light(l: &Value, i: usize) -> crate::ModelLight {
|
||||
let kind = match l.get("type").and_then(Value::as_str) {
|
||||
Some("directional") => crate::ModelLightKind::Directional,
|
||||
Some("spot") => {
|
||||
let s = l.get("spot").cloned().unwrap_or(Value::Null);
|
||||
let outer = num(&s, "outerConeAngle", std::f64::consts::FRAC_PI_4).clamp(1e-3, std::f64::consts::FRAC_PI_2);
|
||||
crate::ModelLightKind::Spot { inner: num(&s, "innerConeAngle", 0.0).clamp(0.0, outer), outer }
|
||||
}
|
||||
_ => crate::ModelLightKind::Point,
|
||||
};
|
||||
crate::ModelLight {
|
||||
name: name_or(l, format!("Light {}", i + 1)),
|
||||
kind,
|
||||
color: nums(l, "color", [1.0; 3]),
|
||||
intensity: num(l, "intensity", 1.0).max(0.0),
|
||||
range: l.get("range").and_then(Value::as_f64),
|
||||
}
|
||||
}
|
||||
|
||||
fn primitive(d: &Doc, p: &Value, materials: &[Material]) -> Result<Option<Primitive>> {
|
||||
|
||||
@@ -295,6 +295,10 @@ pub struct Node {
|
||||
pub matrix: Option<Mat4>,
|
||||
pub mesh: Option<usize>,
|
||||
pub skin: Option<usize>,
|
||||
/// A camera of [`Model::cameras`] at this node (looking down the node's −Z, +Y up).
|
||||
pub camera: Option<usize>,
|
||||
/// A light of [`Model::lights`] at this node (`KHR_lights_punctual`, shining down −Z).
|
||||
pub light: Option<usize>,
|
||||
pub children: Vec<usize>,
|
||||
}
|
||||
|
||||
@@ -308,6 +312,8 @@ impl Default for Node {
|
||||
matrix: None,
|
||||
mesh: None,
|
||||
skin: None,
|
||||
camera: None,
|
||||
light: None,
|
||||
children: vec![],
|
||||
}
|
||||
}
|
||||
@@ -495,6 +501,60 @@ pub struct Model {
|
||||
pub textures: Vec<Arc<Texture>>,
|
||||
pub skins: Vec<Skin>,
|
||||
pub animations: Vec<Animation>,
|
||||
/// Cameras embedded in the file (glTF `cameras`).
|
||||
pub cameras: Vec<ModelCamera>,
|
||||
/// Punctual lights embedded in the file (glTF `KHR_lights_punctual`).
|
||||
pub lights: Vec<ModelLight>,
|
||||
}
|
||||
|
||||
/// A camera embedded in a model file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ModelCamera {
|
||||
pub name: String,
|
||||
pub projection: CameraProjection,
|
||||
}
|
||||
|
||||
/// glTF camera projections.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum CameraProjection {
|
||||
/// Vertical field of view (radians), optional aspect ratio, near plane.
|
||||
Perspective { yfov: f64, aspect: Option<f64>, znear: f64 },
|
||||
/// Half the orthographic view's width and height (model units).
|
||||
Orthographic { xmag: f64, ymag: f64 },
|
||||
}
|
||||
|
||||
/// Kinds of `KHR_lights_punctual` lights.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ModelLightKind {
|
||||
Directional,
|
||||
Point,
|
||||
/// Inner and outer cone angles (radians, from the axis).
|
||||
Spot {
|
||||
inner: f64,
|
||||
outer: f64,
|
||||
},
|
||||
}
|
||||
|
||||
/// A punctual light embedded in a model file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ModelLight {
|
||||
pub name: String,
|
||||
pub kind: ModelLightKind,
|
||||
/// Linear RGB.
|
||||
pub color: [f64; 3],
|
||||
/// Candela (point, spot) or lux (directional).
|
||||
pub intensity: f64,
|
||||
pub range: Option<f64>,
|
||||
}
|
||||
|
||||
/// A camera or light placed in model space by [`Model::placed`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Placed {
|
||||
/// Index into [`Model::cameras`] or [`Model::lights`].
|
||||
pub index: usize,
|
||||
pub node: usize,
|
||||
/// Node → model space.
|
||||
pub world: Mat4,
|
||||
}
|
||||
|
||||
/// One mesh placed in model space by [`Model::instances`].
|
||||
@@ -579,6 +639,31 @@ impl Model {
|
||||
out
|
||||
}
|
||||
|
||||
/// The scene's cameras (`lights = false`) or lights (`true`) placed at animation `clip`
|
||||
/// time `t`, in node order.
|
||||
pub fn placed(&self, lights: bool, clip: Option<usize>, t: f64) -> Vec<Placed> {
|
||||
let world = self.world_pose(&self.local_pose(clip, t));
|
||||
let mut reach = vec![false; self.nodes.len()];
|
||||
let mut stack: Vec<usize> = self.roots.clone();
|
||||
while let Some(i) = stack.pop() {
|
||||
if i >= self.nodes.len() || reach[i] {
|
||||
continue;
|
||||
}
|
||||
reach[i] = true;
|
||||
stack.extend(self.nodes[i].children.iter().copied());
|
||||
}
|
||||
let count = if lights { self.lights.len() } else { self.cameras.len() };
|
||||
self.nodes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| reach[*i])
|
||||
.filter_map(|(i, n)| {
|
||||
let index = if lights { n.light } else { n.camera }?;
|
||||
(index < count).then_some(Placed { index, node: i, world: world[i] })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Model-space bounds of the rest pose (None for an empty model).
|
||||
pub fn bounds(&self) -> Option<([f64; 3], [f64; 3])> {
|
||||
let mut lo = [f64::INFINITY; 3];
|
||||
|
||||
@@ -316,3 +316,47 @@ fn contours_group_into_outlines_by_nesting() {
|
||||
assert_eq!(g.len(), 3);
|
||||
assert_eq!(g.iter().map(|o| o.holes.len()).sum::<usize>(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gltf_cameras_and_punctual_lights() {
|
||||
let doc = r#"{
|
||||
"asset": {"version": "2.0"},
|
||||
"scene": 0,
|
||||
"scenes": [{"nodes": [0, 2]}],
|
||||
"nodes": [
|
||||
{"name": "Rig", "translation": [0, 0, 10], "children": [1]},
|
||||
{"name": "Cam", "camera": 0, "translation": [1, 0, 0]},
|
||||
{"name": "Sun", "rotation": [-0.7071068, 0, 0, 0.7071068], "extensions": {"KHR_lights_punctual": {"light": 1}}},
|
||||
{"name": "Orphan", "camera": 1}
|
||||
],
|
||||
"cameras": [
|
||||
{"type": "perspective", "name": "Shot", "perspective": {"yfov": 0.5, "znear": 0.1, "aspectRatio": 1.5}},
|
||||
{"type": "orthographic", "orthographic": {"xmag": 2, "ymag": 1, "znear": 0, "zfar": 10}}
|
||||
],
|
||||
"extensions": {"KHR_lights_punctual": {"lights": [
|
||||
{"type": "spot", "name": "Key", "color": [1, 0.5, 0.25], "intensity": 3, "spot": {"innerConeAngle": 0.2, "outerConeAngle": 0.4}},
|
||||
{"type": "directional", "intensity": 2}
|
||||
]}}
|
||||
}"#;
|
||||
let m = crate::gltf::parse(doc.as_bytes(), &|_| None).unwrap();
|
||||
assert_eq!(m.cameras.len(), 2);
|
||||
assert_eq!(m.cameras[0].name, "Shot");
|
||||
assert_eq!(m.cameras[0].projection, CameraProjection::Perspective { yfov: 0.5, aspect: Some(1.5), znear: 0.1 });
|
||||
assert_eq!(m.cameras[1].projection, CameraProjection::Orthographic { xmag: 2.0, ymag: 1.0 });
|
||||
assert_eq!(m.lights.len(), 2);
|
||||
assert_eq!(m.lights[0].kind, ModelLightKind::Spot { inner: 0.2, outer: 0.4 });
|
||||
assert_eq!(m.lights[0].color, [1.0, 0.5, 0.25]);
|
||||
assert_eq!(m.lights[1].kind, ModelLightKind::Directional);
|
||||
assert_eq!(m.lights[1].name, "Light 2");
|
||||
// Only nodes of the scene are placed; the camera node inherits its parent's translation.
|
||||
let cams = m.placed(false, None, 0.0);
|
||||
assert_eq!(cams.len(), 1);
|
||||
assert_eq!((cams[0].index, cams[0].node), (0, 1));
|
||||
let eye = cams[0].world.apply(vec3(0.0, 0.0, 0.0));
|
||||
assert!((eye.x - 1.0).abs() < 1e-9 && (eye.z - 10.0).abs() < 1e-9, "{eye:?}");
|
||||
let lights = m.placed(true, None, 0.0);
|
||||
assert_eq!(lights.len(), 1);
|
||||
// −90° about X: the light's −Z axis points down (−Y in glTF).
|
||||
let d = lights[0].world.apply_vec(vec3(0.0, 0.0, -1.0));
|
||||
assert!((d.y + 1.0).abs() < 1e-6, "{d:?}");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user