Merge main into M9.13 (GPU kernels defer CPU-only controls via catalog::gpu_supported)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -277,6 +277,30 @@ fn iris_spans(r: f64, sides: u32, rotation_deg: f64, roundness: f64) -> Vec<(i64
|
||||
spans
|
||||
}
|
||||
|
||||
/// Camera Lens Blur's iris spans at blur radius `r` pixels (shape, rotation, roundness and
|
||||
/// aspect ratio applied) and the iris' horizontal reach (shared with the GPU kernel).
|
||||
pub fn camera_lens_spans(ctx: &EffectCtx, r: f64) -> (Vec<(i64, i64, i64)>, f64) {
|
||||
let shape = ctx.params.e("irisProperties/irisShape");
|
||||
let sides = if shape >= 8 { 0 } else { shape + 3 };
|
||||
let roundness = ctx.params.f("irisProperties/irisRoundness").clamp(0.0, 100.0) / 100.0;
|
||||
// Aspect Ratio stretches the iris horizontally (> 1) or squeezes it (< 1).
|
||||
let aspect = ctx.params.f("irisProperties/irisAspectRatio");
|
||||
let mut spans = iris_spans(r, sides, ctx.params.f("irisProperties/irisRotation"), roundness);
|
||||
if aspect > 0.0 && (aspect - 1.0).abs() > 1e-6 {
|
||||
for s in spans.iter_mut() {
|
||||
s.1 = (s.1 as f64 * aspect).round() as i64;
|
||||
s.2 = (s.2 as f64 * aspect).round() as i64;
|
||||
}
|
||||
}
|
||||
(spans, r * aspect.max(1.0))
|
||||
}
|
||||
|
||||
/// Whether Camera Lens Blur needs more than plain iris spans (Diffraction Fringe or a Blur
|
||||
/// Map): the GPU kernel handles the plain blur only.
|
||||
pub fn camera_lens_plain(ctx: &EffectCtx) -> bool {
|
||||
ctx.params.f("irisProperties/diffractionFringe") <= 0.0 && ctx.params.get("blurMap/blurMapLayer").and_then(|v| v.as_layer()).is_none()
|
||||
}
|
||||
|
||||
fn camera_lens_blur(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let r = ctx.params.f("blurRadius").max(0.0) * b.scale;
|
||||
if r < 0.5 {
|
||||
|
||||
@@ -8,8 +8,12 @@
|
||||
//! Shot Type, Angle of View, Solve Method and deleted points it was solved with, so changing
|
||||
//! those re-solves without re-tracking). **Method Used** and **Average Error** report the solve.
|
||||
//!
|
||||
//! The effect passes its input through; with **Render Track Points** on it draws the solved
|
||||
//! points (as the viewer shows them) into the frame. The viewer overlay, target and the Create
|
||||
//! **Solve Lens Distortion** (Advanced; also on with Detailed Analysis) solves radial lens
|
||||
//! distortion `k1, k2` jointly with the camera; **Undistort Footage** then renders the input
|
||||
//! undistorted (the pinhole image the solved camera sees) so 3D layers line up with it.
|
||||
//!
|
||||
//! The effect passes its input through (undistorted when asked); with **Render Track Points**
|
||||
//! on it draws the solved points (as the viewer shows them) into the frame. The viewer overlay, target and the Create
|
||||
//! commands live in the engine and the UI.
|
||||
|
||||
use std::collections::HashMap;
|
||||
@@ -19,6 +23,7 @@ use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use effectcraft_track::camtrack::{CameraSolve, CameraTracks, ShotType, SolveMethod, SolveSettings, linalg, point_color};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::warp_stab::param;
|
||||
use crate::{Buf, EffectCtx, EffectSpec, Params, num, p, popup, slider};
|
||||
@@ -58,6 +63,8 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
p(METHOD_USED, "Method Used", Value::Str(String::new()), ParamUi::Hidden),
|
||||
p(AVERAGE_ERROR, "Average Error", num(0.0), ParamUi::Hidden),
|
||||
p("advanced/detailedAnalysis", "Detailed Analysis", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("advanced/lensDistortion", "Solve Lens Distortion", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("advanced/undistort", "Undistort Footage", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("advanced/autoDeletePoints", "Auto-delete Points Across Time", Value::Bool(true), ParamUi::Checkbox),
|
||||
p("advanced/hideWarningBanner", "Hide Warning Banner", Value::Bool(false), ParamUi::Checkbox),
|
||||
p(TRACKS, "Tracks", Value::Str(String::new()), ParamUi::Hidden),
|
||||
@@ -104,13 +111,15 @@ pub fn settings(params: &Params) -> SolveSettings {
|
||||
hfov: f(params, "horizontalAngleOfView"),
|
||||
method: SolveMethod::ALL.get(e(params, "advanced/solveMethod") as usize).copied().unwrap_or_default(),
|
||||
deleted: del,
|
||||
lens_distortion: b(params, "advanced/lensDistortion") || b(params, "advanced/detailedAnalysis"),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a solve depends on besides the tracks.
|
||||
pub fn solve_key(st: &SolveSettings) -> String {
|
||||
let hfov = if st.shot == ShotType::SpecifyAngle { format!("{:.4}", st.hfov) } else { String::new() };
|
||||
format!("{:?}|{hfov}|{:?}|{:?}", st.shot, st.method, st.deleted)
|
||||
let lens = if st.lens_distortion { "|lens" } else { "" };
|
||||
format!("{:?}|{hfov}|{:?}|{:?}{lens}", st.shot, st.method, st.deleted)
|
||||
}
|
||||
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
@@ -165,18 +174,49 @@ pub fn target_radius(size_pct: f64, z: f64, median_z: f64) -> f64 {
|
||||
(6.0 * size_pct / 100.0 * (median_z / z.max(1e-9))).clamp(1.5, 40.0)
|
||||
}
|
||||
|
||||
/// The solved points visible on frame `k`: (id, layer pixel position, camera depth).
|
||||
/// The solved points visible on frame `k`: (id, layer pixel position in the footage, camera
|
||||
/// depth).
|
||||
pub fn projected(solve: &CameraSolve, k: usize) -> Vec<(u32, [f64; 2], f64)> {
|
||||
projected_with(solve, k, false)
|
||||
}
|
||||
|
||||
/// [`projected`] into the footage, or (`undistorted`) into the undistorted image.
|
||||
pub fn projected_with(solve: &CameraSolve, k: usize, undistorted: bool) -> Vec<(u32, [f64; 2], f64)> {
|
||||
let Some(cam) = solve.frames.get(k) else { return vec![] };
|
||||
solve
|
||||
.visible(k)
|
||||
.filter_map(|p| {
|
||||
let c = cam.to_cam(p.pos);
|
||||
cam.project(solve.size, p.pos).map(|q| (p.id, q, c[2]))
|
||||
solve.project(k, p.pos, undistorted).map(|q| (p.id, q, c[2]))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether the instance renders its input undistorted (Undistort Footage with a solved
|
||||
/// distortion).
|
||||
pub fn undistorts(params: &Params, solve: &CameraSolve) -> bool {
|
||||
b(params, "advanced/undistort") && solve.distortion.is_some_and(|d| !d.is_none())
|
||||
}
|
||||
|
||||
/// The input resampled through the solved distortion: every output pixel shows the footage
|
||||
/// at its distorted position (transparent where that falls outside the layer).
|
||||
fn undistort(buf: &Buf, sol: &CameraSolve) -> Buf {
|
||||
let sc = if buf.scale > 0.0 { buf.scale } else { 1.0 };
|
||||
let mut out = Image::new(buf.img.width, buf.img.height);
|
||||
let size = sol.size;
|
||||
out.rows_mut().for_each(|(y, row)| {
|
||||
for (x, px) in row.iter_mut().enumerate() {
|
||||
let p = [(x as f64 + 0.5 - buf.offset[0]) / sc, (y as f64 + 0.5 - buf.offset[1]) / sc];
|
||||
let q = sol.to_image(p);
|
||||
if q[0] < 0.0 || q[1] < 0.0 || q[0] > size[0] || q[1] > size[1] {
|
||||
continue;
|
||||
}
|
||||
*px = buf.img.sample_bilinear_clamped(q[0] * sc + buf.offset[0], q[1] * sc + buf.offset[1]);
|
||||
}
|
||||
});
|
||||
Buf { img: out, offset: buf.offset, scale: buf.scale }
|
||||
}
|
||||
|
||||
/// Median of the depths.
|
||||
pub fn median_depth(v: &[(u32, [f64; 2], f64)]) -> f64 {
|
||||
let mut z: Vec<f64> = v.iter().map(|x| x.2).collect();
|
||||
@@ -188,15 +228,23 @@ pub fn median_depth(v: &[(u32, [f64; 2], f64)]) -> f64 {
|
||||
}
|
||||
|
||||
fn render(ctx: &EffectCtx, mut buf: Buf) -> Buf {
|
||||
if !b(ctx.params, "renderTrackPoints") {
|
||||
let points = b(ctx.params, "renderTrackPoints");
|
||||
if !points && !b(ctx.params, "advanced/undistort") {
|
||||
return buf;
|
||||
}
|
||||
let Some(sol) = solve(ctx.params) else { return buf };
|
||||
if (sol.size[0] - ctx.layer_size[0]).abs() > 0.5 || (sol.size[1] - ctx.layer_size[1]).abs() > 0.5 {
|
||||
return buf;
|
||||
}
|
||||
let und = undistorts(ctx.params, &sol);
|
||||
if und {
|
||||
buf = undistort(&buf, &sol);
|
||||
}
|
||||
if !points {
|
||||
return buf;
|
||||
}
|
||||
let Some(k) = sol.frame_at(ctx.time) else { return buf };
|
||||
let pts = projected(&sol, k);
|
||||
let pts = projected_with(&sol, k, und);
|
||||
let med = median_depth(&pts);
|
||||
let size = f(ctx.params, "trackPointSize");
|
||||
let sc = if buf.scale > 0.0 { buf.scale } else { 1.0 };
|
||||
@@ -287,5 +335,37 @@ mod tests {
|
||||
let st = settings(&Params::default());
|
||||
assert_eq!(st.shot, ShotType::FixedAngle);
|
||||
assert!(solve_key(&st).contains("FixedAngle"));
|
||||
assert!(!st.lens_distortion && !solve_key(&st).contains("lens"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undistort_footage_remaps_through_the_solved_lens() {
|
||||
use effectcraft_track::camtrack::Distortion;
|
||||
let sol = CameraSolve {
|
||||
version: 1,
|
||||
size: [64.0, 48.0],
|
||||
start: 0.0,
|
||||
frame_duration: 1.0 / 30.0,
|
||||
frames: vec![SolvedFrame { rot: [0.0; 3], center: [0.0; 3], focal: 50.0, solved: true }],
|
||||
distortion: Some(Distortion { k1: -0.2, k2: 0.0, radius: 40.0 }),
|
||||
..Default::default()
|
||||
};
|
||||
let mut params = params_with(&sol, false);
|
||||
params.values.insert("advanced/undistort".into(), Value::Bool(true));
|
||||
assert!(undistorts(¶ms, &sol));
|
||||
// A horizontal ramp: undistortion keeps the centre and pulls edge content outwards.
|
||||
let mut img = Image::new(64, 48);
|
||||
for (i, px) in img.data.iter_mut().enumerate() {
|
||||
let x = (i % 64) as f32 / 64.0;
|
||||
*px = [x, x, x, 1.0];
|
||||
}
|
||||
let ctx = EffectCtx { params: ¶ms, time: 0.0, layer_size: [64.0, 48.0], seed: 0, adjustment: false, env: EffectEnv::default() };
|
||||
let out = render(&ctx, Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 });
|
||||
let at = |im: &Image, x: u32, y: u32| im.data[im.idx(x, y)][0];
|
||||
assert!((at(&out.img, 32, 24) - at(&img, 32, 24)).abs() < 0.02);
|
||||
// Barrel distortion compresses the edges: the ideal pixel at x = 56 shows footage nearer the centre.
|
||||
assert!(at(&out.img, 56, 24) < at(&img, 56, 24) - 0.01, "{} vs {}", at(&out.img, 56, 24), at(&img, 56, 24));
|
||||
let sp = sol.to_image([56.0, 24.0]);
|
||||
assert!(sp[0] < 56.0 && (sol.to_ideal(sp)[0] - 56.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,52 @@ pub fn param_shown(effect: &str, param: &str, value: &dyn Fn(&str) -> Option<eff
|
||||
}
|
||||
}
|
||||
|
||||
/// Controls of GPU-accelerated effects that only the CPU implements: while any of them is away
|
||||
/// from its default the effect renders on the CPU. (Prefixes ending in `/` cover a whole group.)
|
||||
const CPU_ONLY_CONTROLS: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"ec.color.lumetri",
|
||||
&["highDynamicRange", "basicCorrection/inputLut", "creative/look", "curves/rgbCurves/", "curves/hueSaturationCurves/", "hslSecondary/"],
|
||||
),
|
||||
(
|
||||
"ec.color.colorama",
|
||||
&["inputPhase/addPhase", "outputCycle/usePresetPalette", "modify/", "pixelSelection/matchingMode", "masking/maskingMode", "masking/compositeOverLayer"],
|
||||
),
|
||||
(
|
||||
"ec.keying.keylight",
|
||||
&[
|
||||
"foregroundColourCorrection/colourSuppression",
|
||||
"foregroundColourCorrection/suppressionAmount",
|
||||
"foregroundColourCorrection/colourBalanceSaturation",
|
||||
"edgeColourCorrection/edgeColourSuppression",
|
||||
"edgeColourCorrection/edgeSuppressionAmount",
|
||||
"edgeColourCorrection/edgeColourBalanceSaturation",
|
||||
"sourceCrops/xMethod",
|
||||
"sourceCrops/yMethod",
|
||||
"sourceCrops/edgeColourAlpha",
|
||||
],
|
||||
),
|
||||
("ec.noise.addgrain", &["viewingMode", "preset", "color/redBalance", "color/greenBalance", "color/blueBalance", "previewRegion/"]),
|
||||
("ec.blur.cameralens", &["irisProperties/diffractionFringe", "blurMap/blurMapLayer"]),
|
||||
];
|
||||
|
||||
/// Whether the GPU kernel of effect `id` covers the instance's current settings (see
|
||||
/// [`CPU_ONLY_CONTROLS`]; plus Cell Pattern's HQ variants and Turbulent Displace's locked
|
||||
/// pinning).
|
||||
pub fn gpu_supported(id: &str, ctx: &crate::EffectCtx) -> bool {
|
||||
match id {
|
||||
"ec.generate.cellpattern" if (6..=10).contains(&ctx.params.e("cellPattern")) => return false,
|
||||
"ec.distort.turbulentdisplace" if ctx.params.e("pinning") >= 8 => return false,
|
||||
_ => {}
|
||||
}
|
||||
let Some((_, controls)) = CPU_ONLY_CONTROLS.iter().find(|(e, _)| *e == id) else { return true };
|
||||
let Some(spec) = crate::find(id) else { return true };
|
||||
spec.params
|
||||
.iter()
|
||||
.filter(|ps| controls.iter().any(|c| if c.ends_with('/') { ps.id.starts_with(c) } else { ps.id == *c }))
|
||||
.all(|ps| ctx.params.get(ps.id).is_none_or(|v| *v == crate::default_value(ps, ctx.layer_size)))
|
||||
}
|
||||
|
||||
/// Implementation status of effect `id` (`Implemented` or `Partial: …`).
|
||||
pub fn status(id: &str) -> String {
|
||||
match PARTIAL.iter().find(|(e, _)| *e == id) {
|
||||
@@ -130,6 +176,32 @@ mod tests {
|
||||
assert!(have == want, "docs/effects.md is stale: UPDATE_DOCS=1 cargo test -p effectcraft-effects --lib effects_doc_is_current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_only_controls_keep_effects_off_the_gpu() {
|
||||
use effectcraft_keyframe::Value;
|
||||
let ctx_with = |id: &str, set: &[(&str, Value)]| {
|
||||
let s = crate::find(id).unwrap();
|
||||
let mut values: std::collections::HashMap<String, Value> =
|
||||
s.params.iter().map(|p| (p.id.to_string(), crate::default_value(p, [64.0, 64.0]))).collect();
|
||||
for (k, v) in set {
|
||||
values.insert(k.to_string(), v.clone());
|
||||
}
|
||||
crate::Params { values }
|
||||
};
|
||||
let ok = |id: &str, set: &[(&str, Value)]| {
|
||||
let params = ctx_with(id, set);
|
||||
let ctx = crate::EffectCtx { params: ¶ms, time: 0.0, layer_size: [64.0, 64.0], seed: 0, adjustment: false, env: Default::default() };
|
||||
super::gpu_supported(id, &ctx)
|
||||
};
|
||||
assert!(ok("ec.color.lumetri", &[]));
|
||||
assert!(!ok("ec.color.lumetri", &[("hslSecondary/correction/saturation", Value::Scalar(50.0))]));
|
||||
assert!(!ok("ec.noise.addgrain", &[("preset", Value::Enum(2))]));
|
||||
assert!(ok("ec.generate.cellpattern", &[("cellPattern", Value::Enum(3))]));
|
||||
assert!(!ok("ec.generate.cellpattern", &[("cellPattern", Value::Enum(9))]));
|
||||
assert!(!ok("ec.distort.turbulentdisplace", &[("pinning", Value::Enum(9))]));
|
||||
assert!(ok("ec.blur.gaussian", &[]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn popups_choose_the_shown_controls() {
|
||||
use effectcraft_keyframe::Value;
|
||||
|
||||
@@ -6,6 +6,13 @@ use effectcraft_project::ParamUi;
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, col, num, p, popup, slider};
|
||||
|
||||
/// Id of the Stereo 3D Controls effect (Layer ▸ Camera ▸ Create Stereo 3D Rig).
|
||||
pub const STEREO_CONTROLS: &str = "ec.control.stereo3d";
|
||||
/// Stereo 3D Controls ▸ Configuration: which eyes are offset from the master camera.
|
||||
pub const STEREO_CONFIGURATIONS: [&str; 3] = ["Stereo Pair (Left & Right)", "Center & Right", "Center & Left"];
|
||||
/// Stereo 3D Controls ▸ Convergence Of: the zero-parallax distance.
|
||||
pub const STEREO_CONVERGENCE: [&str; 2] = ["Camera Point of Interest", "Camera Zoom Plane"];
|
||||
|
||||
fn passthrough(_: &EffectCtx, b: Buf) -> Buf {
|
||||
b
|
||||
}
|
||||
@@ -24,5 +31,17 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
spec("ec.control.point3d", "3D Point Control", vec![p("point", "3D Point", Value::Vec3([0.0, 0.0, 0.0]), ParamUi::Point3)]),
|
||||
spec("ec.control.layer", "Layer Control", vec![p("layer", "Layer", Value::Layer(None), ParamUi::Layer)]),
|
||||
spec("ec.control.dropdown", "Dropdown Menu Control", vec![p("menu", "Menu", Value::Enum(0), popup(&["Item 1", "Item 2", "Item 3"]))]),
|
||||
// Layer ▸ Camera ▸ Create Stereo 3D Rig: the rig's eye cameras read these (expressions).
|
||||
spec(
|
||||
STEREO_CONTROLS,
|
||||
"Stereo 3D Controls",
|
||||
vec![
|
||||
p("configuration", "Configuration", Value::Enum(0), popup(&STEREO_CONFIGURATIONS)),
|
||||
p("sceneDepth", "Stereo Scene Depth", num(3.0), slider(0.0, 100.0, 0.0, 10.0, 2)),
|
||||
p("convergence", "Enable Convergence", Value::Bool(false), ParamUi::Checkbox),
|
||||
p("convergenceOf", "Convergence Of", Value::Enum(0), popup(&STEREO_CONVERGENCE)),
|
||||
p("zOffset", "Convergence Z Offset", num(0.0), slider(-100_000.0, 100_000.0, -2000.0, 2000.0, 1)),
|
||||
],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -454,7 +454,8 @@ fn grid_warp(src: &Image, w: u32, h: u32, nx: usize, ny: usize, dest: &[Pt], src
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_mesh(s: &str) -> Vec<Pt> {
|
||||
/// Mesh Warp's `mesh` parameter: the vertex offsets (layer pixels), row-major.
|
||||
pub fn parse_mesh(s: &str) -> Vec<(f64, f64)> {
|
||||
s.split(|c: char| c.is_whitespace() || c == ';')
|
||||
.filter(|t| !t.is_empty())
|
||||
.filter_map(|t| {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Face tracking results (Tracker panel ▸ Method ▸ Face Tracking (Detailed Features)):
|
||||
//!
|
||||
//! - **Face Track Points** holds one point control per facial landmark (eyebrows, eyes and
|
||||
//! pupils, nose, nostrils, mouth, chin and jaw), keyed on every tracked frame by the engine's
|
||||
//! mask tracker ([`effectcraft_track::face`]); expressions and other layers can follow them.
|
||||
//! - **Face Measurements** holds the measurements derived from those points (head position,
|
||||
//! scale and orientation, eye openness, eyebrow raise, mouth openness, width and offset), keyed
|
||||
//! by Extract & Copy Face Measurements (`track.extractFaceMeasurements`).
|
||||
//!
|
||||
//! Both pass their input through unchanged: they are data, like expression controls.
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_track::face::{LANDMARKS, MEASUREMENTS};
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, ParamSpec, num, p, slider};
|
||||
|
||||
/// Effect ids.
|
||||
pub const POINTS_ID: &str = "ec.utility.facetrackpoints";
|
||||
pub const MEASUREMENTS_ID: &str = "ec.utility.facemeasurements";
|
||||
|
||||
fn passthrough(_: &EffectCtx, b: Buf) -> Buf {
|
||||
b
|
||||
}
|
||||
|
||||
fn measurement_ui(id: &str) -> ParamUi {
|
||||
match id {
|
||||
"headPositionX" | "headPositionY" => slider(-100_000.0, 100_000.0, 0.0, 1920.0, 1),
|
||||
"headOrientationX" | "headOrientationY" | "headOrientationZ" => slider(-180.0, 180.0, -90.0, 90.0, 1),
|
||||
_ => slider(-100_000.0, 100_000.0, 0.0, 200.0, 1),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<EffectSpec> {
|
||||
let points: Vec<ParamSpec> = LANDMARKS
|
||||
.iter()
|
||||
// Point defaults are fractions of the layer size: the canonical face in the middle.
|
||||
.map(|(id, name, q)| p(id, name, Value::Vec2([0.5 + 0.25 * q[0], 0.5 + 0.25 * q[1]]), ParamUi::Point))
|
||||
.collect();
|
||||
let measurements: Vec<ParamSpec> = MEASUREMENTS.iter().map(|(id, name)| p(id, name, num(0.0), measurement_ui(id))).collect();
|
||||
vec![
|
||||
EffectSpec { id: POINTS_ID, name: "Face Track Points", category: "Utility", params: points, render: passthrough, gpu: false, float: true },
|
||||
EffectSpec { id: MEASUREMENTS_ID, name: "Face Measurements", category: "Utility", params: measurements, render: passthrough, gpu: false, float: true },
|
||||
]
|
||||
}
|
||||
@@ -75,7 +75,7 @@ pub(crate) const GEN_BLEND_MODES: [&str; 20] = [
|
||||
"Silhouette Alpha",
|
||||
];
|
||||
|
||||
fn gen_mode(i: u32) -> Option<BlendMode> {
|
||||
pub fn gen_mode(i: u32) -> Option<BlendMode> {
|
||||
Some(match i {
|
||||
0 => return None,
|
||||
2 => BlendMode::Add,
|
||||
|
||||
@@ -62,7 +62,7 @@ const CELL_PATTERNS: [&str; 12] = [
|
||||
];
|
||||
|
||||
/// Shaping used for Cell Pattern option `i` (see [`cell_value`]).
|
||||
fn pattern_kind(i: u32) -> u32 {
|
||||
pub fn pattern_kind(i: u32) -> u32 {
|
||||
match i {
|
||||
0..=5 => i,
|
||||
6 => 1,
|
||||
|
||||
@@ -198,6 +198,11 @@ fn crop_source(ctx: &EffectCtx, b: &Buf) -> Image {
|
||||
let methods = [pr.e("sourceCrops/xMethod"), pr.e("sourceCrops/yMethod")];
|
||||
let ec = pr.color("sourceCrops/edgeColour");
|
||||
let ea = (pr.f("sourceCrops/edgeColourAlpha") / 100.0) as f32;
|
||||
if methods == [0, 0] && ea <= 0.0 {
|
||||
// Transparent edge colour: the borders are cut from the result instead (keying sees
|
||||
// the whole picture).
|
||||
return b.img.clone();
|
||||
}
|
||||
let edge = premul([ec[0], ec[1], ec[2]], ea);
|
||||
// Fold a coordinate into [lo, hi) by a method; None = outside with Colour.
|
||||
let fold = |v: f64, lo: f64, hi: f64, m: u32| -> Option<f64> {
|
||||
|
||||
@@ -18,11 +18,12 @@ mod channel3d;
|
||||
mod color2;
|
||||
mod color3;
|
||||
mod color_fx;
|
||||
mod controls;
|
||||
pub mod controls;
|
||||
mod distort;
|
||||
mod distort2;
|
||||
mod distort3;
|
||||
pub mod distort4;
|
||||
pub mod face_track;
|
||||
mod generate;
|
||||
mod generate2;
|
||||
mod generate3;
|
||||
@@ -38,9 +39,12 @@ mod noise2;
|
||||
mod noise3;
|
||||
mod obsolete;
|
||||
mod ocio;
|
||||
pub mod ocio_config;
|
||||
pub mod paint;
|
||||
mod perspective;
|
||||
mod perspective2;
|
||||
pub mod plugin;
|
||||
pub mod psim;
|
||||
pub mod puppet;
|
||||
pub mod roto;
|
||||
mod sim;
|
||||
@@ -67,11 +71,20 @@ pub use color_fx::{
|
||||
};
|
||||
pub use color2::Curve;
|
||||
pub use distort::transform_shutter;
|
||||
pub use distort2::parse_mesh;
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::build::Ids;
|
||||
use effectcraft_project::{GroupKind, ParamUi, PropGroup, Property};
|
||||
pub use effectcraft_raster::{AuxChannels, Image};
|
||||
pub use misc::{INVERT_ALPHA, INVERT_CHANNELS, glow_operation};
|
||||
pub use sim::particle_state;
|
||||
pub use sim3::playground_state;
|
||||
// CPU helpers the GPU kernels share (effectcraft-gpu).
|
||||
pub use blur2::{camera_lens_plain, camera_lens_spans};
|
||||
pub use generate::gen_mode;
|
||||
pub use generate2::pattern_kind as cell_pattern_kind;
|
||||
pub use noise::GrainLook;
|
||||
pub use transition::place_layer;
|
||||
|
||||
/// Effect categories in Effects & Presets order.
|
||||
pub const CATEGORIES: &[&str] = &[
|
||||
@@ -275,6 +288,11 @@ pub trait EffectHost: Sync {
|
||||
fn params_at(&self, _layer_time: f64) -> Option<Params> {
|
||||
None
|
||||
}
|
||||
/// A particle simulation backend (GPU particles; see [`psim`]). `None` = simulate on the
|
||||
/// CPU.
|
||||
fn particles(&self) -> Option<&dyn psim::ParticleSim> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Extra context the renderer may supply (all optional; `Default` is "nothing known").
|
||||
@@ -415,6 +433,7 @@ pub fn registry() -> &'static [EffectSpec] {
|
||||
v.extend(puppet::specs());
|
||||
v.extend(warp_stab::specs());
|
||||
v.extend(camera_tracker::specs());
|
||||
v.extend(face_track::specs());
|
||||
v.extend(roto::specs());
|
||||
v.sort_by(|a, b| a.category.cmp(b.category).then(a.name.cmp(b.name)));
|
||||
for s in v.iter_mut() {
|
||||
@@ -426,14 +445,37 @@ pub fn registry() -> &'static [EffectSpec] {
|
||||
})
|
||||
}
|
||||
|
||||
/// A built-in effect or a registered plug-in by id.
|
||||
pub fn find(id: &str) -> Option<&'static EffectSpec> {
|
||||
registry().iter().find(|s| s.id == id)
|
||||
registry().iter().find(|s| s.id == id).or_else(|| plugin::plugins().into_iter().find(|s| s.id == id))
|
||||
}
|
||||
|
||||
/// Every effect: the built-ins ([`registry`]) and the registered plug-ins
|
||||
/// ([`plugin::register_plugin`]), sorted by category then name.
|
||||
pub fn all() -> Vec<&'static EffectSpec> {
|
||||
let plugins = plugin::plugins();
|
||||
let mut v: Vec<&'static EffectSpec> = registry().iter().collect();
|
||||
if !plugins.is_empty() {
|
||||
v.extend(plugins);
|
||||
v.sort_by(|a, b| a.category.cmp(b.category).then(a.name.cmp(b.name)));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// Effects & Presets categories: [`CATEGORIES`] then the plug-ins' own, alphabetically.
|
||||
pub fn categories() -> Vec<&'static str> {
|
||||
let mut v: Vec<&'static str> = CATEGORIES.to_vec();
|
||||
let mut extra: Vec<&'static str> = plugin::plugins().iter().map(|s| s.category).filter(|c| !CATEGORIES.contains(c)).collect();
|
||||
extra.sort_unstable();
|
||||
extra.dedup();
|
||||
v.extend(extra);
|
||||
v
|
||||
}
|
||||
|
||||
/// Find by id or (case-insensitive) display name.
|
||||
pub fn lookup(name_or_id: &str) -> Option<&'static EffectSpec> {
|
||||
find(name_or_id)
|
||||
.or_else(|| registry().iter().find(|s| s.name.eq_ignore_ascii_case(name_or_id)))
|
||||
.or_else(|| all().into_iter().find(|s| s.name.eq_ignore_ascii_case(name_or_id)))
|
||||
.or_else(|| {
|
||||
// After Effects' third-party display names we register under a generic name.
|
||||
keylight::KEYLIGHT_ALIASES.iter().any(|a| a.eq_ignore_ascii_case(name_or_id)).then(|| find("ec.keying.keylight")).flatten()
|
||||
@@ -728,6 +770,42 @@ pub const GPU_EFFECTS: &[&str] = &[
|
||||
"ec.color.exposure",
|
||||
"ec.channel.invert",
|
||||
"ec.distort.transform",
|
||||
"ec.distort.turbulentdisplace",
|
||||
"ec.distort.displacementmap",
|
||||
"ec.distort.wavewarp",
|
||||
"ec.distort.ripple",
|
||||
"ec.distort.twirl",
|
||||
"ec.distort.bulge",
|
||||
"ec.distort.cclens",
|
||||
"ec.distort.meshwarp",
|
||||
"ec.stylize.mosaic",
|
||||
"ec.stylize.findedges",
|
||||
"ec.stylize.emboss",
|
||||
// Blur, transition and generate family (effectcraft-gpu `fx_generate`).
|
||||
"ec.blur.radial",
|
||||
"ec.blur.cameralens",
|
||||
"ec.blur.ccradialfast",
|
||||
"ec.transition.venetian",
|
||||
"ec.transition.linearwipe",
|
||||
"ec.transition.radialwipe",
|
||||
"ec.transition.gradientwipe",
|
||||
"ec.generate.cellpattern",
|
||||
"ec.generate.checkerboard",
|
||||
"ec.generate.grid",
|
||||
"ec.generate.fourcolor",
|
||||
"ec.noise.noise",
|
||||
"ec.noise.addgrain",
|
||||
// effectcraft-gpu fx_color
|
||||
"ec.color.colorbalance",
|
||||
"ec.color.vibrance",
|
||||
"ec.color.lumetri",
|
||||
"ec.color.blackwhite",
|
||||
"ec.color.tritone",
|
||||
"ec.color.colorama",
|
||||
"ec.color.channelmixer",
|
||||
"ec.color.selectivecolor",
|
||||
"ec.key.linearcolor",
|
||||
"ec.keying.keylight",
|
||||
];
|
||||
|
||||
/// Effects whose output depends on [`EffectCtx::time`] directly (not only through animated
|
||||
|
||||
@@ -41,7 +41,7 @@ pub(crate) const GRAIN_BLEND_MODES: [&str; 5] = ["Film", "Multiply", "Add", "Scr
|
||||
|
||||
/// The Tweaking / Color / Application / Animation controls Add Grain and Match Grain share
|
||||
/// (twirl-down groups with the same ids in both effects).
|
||||
pub(crate) struct GrainLook {
|
||||
pub struct GrainLook {
|
||||
pub intensity: f32,
|
||||
pub channel_intensity: [f32; 3],
|
||||
pub size: f32,
|
||||
@@ -64,7 +64,7 @@ pub(crate) struct GrainLook {
|
||||
}
|
||||
|
||||
impl GrainLook {
|
||||
pub(crate) fn from_params(ctx: &EffectCtx) -> GrainLook {
|
||||
pub fn from_params(ctx: &EffectCtx) -> GrainLook {
|
||||
let pr = ctx.params;
|
||||
let ch = |pre: &str, a: &str, b: &str, c: &str| [a, b, c].map(|k| pr.get(&format!("{pre}{k}")).map(Value::as_f64).unwrap_or(1.0) as f32);
|
||||
let ft = ctx.time * 24.0 * pr.f("animation/animationSpeed");
|
||||
|
||||
@@ -559,6 +559,10 @@ pub const DISPLAYS: &[(&str, [[f64; 2]; 3], Tf)] =
|
||||
|
||||
pub const VIEWS: &[&str] = &["Standard", "Tone Mapped", "Raw"];
|
||||
|
||||
/// Configuration popup: the built-in config, or a custom `.ocio` file (Config File: a path or
|
||||
/// the config's text; spaces chosen by name, see [`crate::ocio_config`]).
|
||||
pub const CONFIGS: &[&str] = &["Built-in (EffectCraft minimal)", "Custom (.ocio file)"];
|
||||
|
||||
/// Built-in looks: CDLs applied in ACEScct.
|
||||
pub fn looks() -> Vec<(&'static str, Cdl)> {
|
||||
let grey = 0.413_588_402_492_442_1; // ACEScct of 0.18
|
||||
@@ -647,7 +651,35 @@ fn space_at(i: u32) -> &'static Space {
|
||||
&SPACES[(i as usize).min(SPACES.len() - 1)]
|
||||
}
|
||||
|
||||
/// The custom config chosen by an effect (Configuration ▸ Custom with a readable file).
|
||||
fn custom_config(ctx: &EffectCtx) -> Option<std::sync::Arc<crate::ocio_config::Config>> {
|
||||
if ctx.params.e("config") != 1 {
|
||||
return None;
|
||||
}
|
||||
crate::ocio_config::load_config(ctx.params.s("configFile"))
|
||||
}
|
||||
|
||||
/// A space of a custom config by its typed name, else by the built-in popup's name.
|
||||
fn custom_space<'c>(cfg: &'c crate::ocio_config::Config, name: &str, popup: u32) -> Option<&'c crate::ocio_config::ConfigSpace> {
|
||||
cfg.space(name).or_else(|| cfg.space(space_at(popup).name))
|
||||
}
|
||||
|
||||
fn ocio_cst(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
// Custom configuration that can't be read: pixels pass through.
|
||||
if ctx.params.e("config") == 1 && custom_config(ctx).is_none() {
|
||||
return b;
|
||||
}
|
||||
if let Some(cfg) = custom_config(ctx) {
|
||||
let (Some(a), Some(z)) = (
|
||||
custom_space(&cfg, ctx.params.s("sourceName"), ctx.params.e("source")),
|
||||
custom_space(&cfg, ctx.params.s("destinationName"), ctx.params.e("destination")),
|
||||
) else {
|
||||
return b;
|
||||
};
|
||||
let (a, z) = if ctx.params.e("direction") == 1 { (z, a) } else { (a, z) };
|
||||
map_px(&mut b, |c| cfg.convert(a, z, c.map(|v| v as f64)).map(|v| v as f32));
|
||||
return b;
|
||||
}
|
||||
let (a, z) = (space_at(ctx.params.e("source")), space_at(ctx.params.e("destination")));
|
||||
let (a, z) = if ctx.params.e("direction") == 1 { (z, a) } else { (a, z) };
|
||||
if a.name == z.name {
|
||||
@@ -683,6 +715,21 @@ fn ocio_cdl(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
}
|
||||
|
||||
fn ocio_display(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
// Custom configuration that can't be read: pixels pass through.
|
||||
if ctx.params.e("config") == 1 && custom_config(ctx).is_none() {
|
||||
return b;
|
||||
}
|
||||
if let Some(cfg) = custom_config(ctx) {
|
||||
// The display's view names a colour space of the config.
|
||||
let display = DISPLAYS.get(ctx.params.e("display") as usize).map_or("", |d| d.0);
|
||||
let view = VIEWS.get(ctx.params.e("view") as usize).copied().unwrap_or("");
|
||||
let dn = if ctx.params.s("displayName").is_empty() { display } else { ctx.params.s("displayName") };
|
||||
let vn = if ctx.params.s("viewName").is_empty() { view } else { ctx.params.s("viewName") };
|
||||
let (Some(a), Some(z)) = (custom_space(&cfg, ctx.params.s("sourceName"), ctx.params.e("source")), cfg.view_space(dn, vn)) else { return b };
|
||||
let (a, z) = if ctx.params.e("direction") == 1 { (z, a) } else { (a, z) };
|
||||
map_px(&mut b, |c| cfg.convert(a, z, c.map(|v| v as f64)).map(|v| v as f32));
|
||||
return b;
|
||||
}
|
||||
let input = space_at(ctx.params.e("source"));
|
||||
let f = display_xform(input, ctx.params.e("display") as usize, ctx.params.e("view") as usize, ctx.params.e("direction") == 1);
|
||||
map_px(&mut b, f);
|
||||
@@ -758,6 +805,10 @@ fn profile(ctx: &EffectCtx, i: u32) -> (Space, bool) {
|
||||
ColorSpace::Rec709 => sp("Rec.709", REC709, D65, Tf::Gamma(2.4)),
|
||||
ColorSpace::Rec2020 => sp("Rec.2020", REC2020, D65, Tf::Gamma(2.4)),
|
||||
ColorSpace::DisplayP3 => sp("Display P3", P3, D65, Tf::Srgb),
|
||||
ColorSpace::AcesCg => *space_by_name("ACEScg").expect("built-in"),
|
||||
ColorSpace::Aces2065 => *space_by_name("ACES2065-1").expect("built-in"),
|
||||
// HDR encodings are output spaces, never a working space.
|
||||
ColorSpace::Rec2100Pq | ColorSpace::Rec2100Hlg => sp("Rec.2020", REC2020, D65, Tf::Gamma(2.4)),
|
||||
};
|
||||
match i {
|
||||
0 => (ws(ctx.env.working_space.unwrap_or(ColorSpace::Srgb)), ctx.env.working_linear),
|
||||
@@ -919,9 +970,12 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"OCIO Color Space Transform",
|
||||
cc,
|
||||
vec![
|
||||
p("config", "Configuration", Value::Enum(0), popup(&["Built-in (EffectCraft minimal)"])),
|
||||
p("config", "Configuration", Value::Enum(0), popup(CONFIGS)),
|
||||
p("configFile", "Config File (.ocio)", Value::Str(String::new()), ParamUi::Text),
|
||||
space_param("source", "Source", lin709),
|
||||
p("sourceName", "Source (config name)", Value::Str(String::new()), ParamUi::Text),
|
||||
space_param("destination", "Destination", srgb),
|
||||
p("destinationName", "Destination (config name)", Value::Str(String::new()), ParamUi::Text),
|
||||
direction(),
|
||||
],
|
||||
ocio_cst,
|
||||
@@ -931,10 +985,14 @@ pub fn specs() -> Vec<EffectSpec> {
|
||||
"OCIO Display Transform",
|
||||
cc,
|
||||
vec![
|
||||
p("config", "Configuration", Value::Enum(0), popup(&["Built-in (EffectCraft minimal)"])),
|
||||
p("config", "Configuration", Value::Enum(0), popup(CONFIGS)),
|
||||
p("configFile", "Config File (.ocio)", Value::Str(String::new()), ParamUi::Text),
|
||||
space_param("source", "Input Color Space", lin709),
|
||||
p("sourceName", "Source (config name)", Value::Str(String::new()), ParamUi::Text),
|
||||
p("display", "Display Device", Value::Enum(0), popup(&DISPLAYS.iter().map(|d| d.0).collect::<Vec<_>>())),
|
||||
p("displayName", "Display (config name)", Value::Str(String::new()), ParamUi::Text),
|
||||
p("view", "View Transform", Value::Enum(0), popup(VIEWS)),
|
||||
p("viewName", "View (config name)", Value::Str(String::new()), ParamUi::Text),
|
||||
direction(),
|
||||
],
|
||||
ocio_display,
|
||||
|
||||
@@ -0,0 +1,928 @@
|
||||
//! Custom OpenColorIO configuration files (`.ocio`) for the OCIO effects, read from the
|
||||
//! published configuration format (a YAML document), not from OpenColorIO's source.
|
||||
//!
|
||||
//! Supported subset:
|
||||
//!
|
||||
//! * `search_path` (a string with `:`-separated entries or a list), resolved against the
|
||||
//! config's folder, for `FileTransform` sources;
|
||||
//! * `roles` (any role name can stand for its colour space);
|
||||
//! * `colorspaces`: `name`, `aliases`, `isdata`, and the transforms to / from the reference
|
||||
//! space — `to_reference` / `from_reference` (OCIO v1) or `to_scene_reference` /
|
||||
//! `from_scene_reference` (v2); a space with only one direction is inverted for the other;
|
||||
//! * `displays`: display → views (`!<View> {name, colorspace}`);
|
||||
//! * transforms: `MatrixTransform` (`matrix` 4×4 row-major, `offset`), `FileTransform` (the LUT
|
||||
//! and CDL files [`super::ocio::parse_file`] reads; `interpolation`, `ccc_id`),
|
||||
//! `ExponentTransform` (`value`), `LogTransform` (`base`), `LogAffineTransform` (`base`,
|
||||
//! `logSideSlope`, `logSideOffset`, `linSideSlope`, `linSideOffset`), `CDLTransform` (`slope`,
|
||||
//! `offset`, `power`, `sat`), `RangeTransform` (`min_in_value`, `max_in_value`,
|
||||
//! `min_out_value`, `max_out_value`) and `GroupTransform` (`children`), each with
|
||||
//! `direction: inverse`. Other transforms are reported by [`Config::unsupported`] and pass
|
||||
//! colours through.
|
||||
//!
|
||||
//! The YAML reader covers what configs use: block mappings and sequences, flow `{}` / `[]`
|
||||
//! collections (also spanning lines), `!<Tag>` tags, quoted scalars, `|` / `>` block scalars
|
||||
//! and comments.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use super::ocio::{Cdl, FileXform, load_file};
|
||||
|
||||
// ---------------------------------------------------------------- YAML subset
|
||||
|
||||
/// A parsed YAML node.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Yaml {
|
||||
Str(String),
|
||||
Seq(Vec<Yaml>),
|
||||
Map(Vec<(String, Yaml)>),
|
||||
/// A `!<Tag>` node.
|
||||
Tagged(String, Box<Yaml>),
|
||||
Null,
|
||||
}
|
||||
|
||||
impl Yaml {
|
||||
pub fn get(&self, k: &str) -> Option<&Yaml> {
|
||||
match self {
|
||||
Yaml::Map(m) => m.iter().find(|(key, _)| key == k).map(|(_, v)| v),
|
||||
Yaml::Tagged(_, v) => v.get(k),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn str(&self) -> Option<&str> {
|
||||
match self {
|
||||
Yaml::Str(s) => Some(s),
|
||||
Yaml::Tagged(_, v) => v.str(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn seq(&self) -> &[Yaml] {
|
||||
match self {
|
||||
Yaml::Seq(v) => v,
|
||||
Yaml::Tagged(_, v) => v.seq(),
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
pub fn tag(&self) -> Option<&str> {
|
||||
match self {
|
||||
Yaml::Tagged(t, _) => Some(t),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn f(&self) -> Option<f64> {
|
||||
self.str()?.trim().parse().ok()
|
||||
}
|
||||
fn nums(&self) -> Vec<f64> {
|
||||
match self {
|
||||
Yaml::Seq(v) => v.iter().filter_map(Yaml::f).collect(),
|
||||
Yaml::Str(_) => self.f().into_iter().collect(),
|
||||
Yaml::Tagged(_, v) => v.nums(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Strip a trailing comment (a `#` outside quotes, at the start or after whitespace).
|
||||
fn strip_comment(line: &str) -> &str {
|
||||
let (mut sq, mut dq) = (false, false);
|
||||
let b = line.as_bytes();
|
||||
for (i, &c) in b.iter().enumerate() {
|
||||
match c {
|
||||
b'\'' if !dq => sq = !sq,
|
||||
b'"' if !sq => dq = !dq,
|
||||
b'#' if !sq && !dq && (i == 0 || b[i - 1].is_ascii_whitespace()) => return &line[..i],
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
fn unquote(s: &str) -> String {
|
||||
let t = s.trim();
|
||||
if t.len() >= 2 && ((t.starts_with('"') && t.ends_with('"')) || (t.starts_with('\'') && t.ends_with('\''))) {
|
||||
return t[1..t.len() - 1].replace("\\\"", "\"").replace("''", "'");
|
||||
}
|
||||
t.to_string()
|
||||
}
|
||||
|
||||
/// Split `key: value` at the first `:` followed by a space or the end (outside quotes/brackets).
|
||||
fn split_key(s: &str) -> Option<(String, &str)> {
|
||||
let b = s.as_bytes();
|
||||
let (mut sq, mut dq, mut depth) = (false, false, 0i32);
|
||||
for (i, &c) in b.iter().enumerate() {
|
||||
match c {
|
||||
b'\'' if !dq => sq = !sq,
|
||||
b'"' if !sq => dq = !dq,
|
||||
b'{' | b'[' if !sq && !dq => depth += 1,
|
||||
b'}' | b']' if !sq && !dq => depth -= 1,
|
||||
b':' if !sq && !dq && depth == 0 && (i + 1 == b.len() || b[i + 1] == b' ' || b[i + 1] == b'\t') => {
|
||||
let k = s[..i].trim();
|
||||
if k.is_empty() || k.starts_with('!') || k.starts_with('{') || k.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
return Some((unquote(k), s[i + 1..].trim()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Bracket balance of a flow fragment (outside quotes).
|
||||
fn balance(s: &str) -> i32 {
|
||||
let (mut sq, mut dq, mut d) = (false, false, 0);
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'\'' if !dq => sq = !sq,
|
||||
'"' if !sq => dq = !dq,
|
||||
'{' | '[' if !sq && !dq => d += 1,
|
||||
'}' | ']' if !sq && !dq => d -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
struct Flow<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl Flow<'_> {
|
||||
fn ws(&mut self) {
|
||||
while self.i < self.s.len() && (self.s[self.i] as char).is_whitespace() {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.s.get(self.i).copied()
|
||||
}
|
||||
fn value(&mut self) -> Yaml {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
Some(b'{') => {
|
||||
self.i += 1;
|
||||
let mut m = vec![];
|
||||
loop {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
None => break,
|
||||
Some(b'}') => {
|
||||
self.i += 1;
|
||||
break;
|
||||
}
|
||||
Some(b',') => {
|
||||
self.i += 1;
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let k = self.scalar(true);
|
||||
self.ws();
|
||||
if self.peek() == Some(b':') {
|
||||
self.i += 1;
|
||||
}
|
||||
let v = self.value();
|
||||
m.push((unquote(&k), v));
|
||||
}
|
||||
Yaml::Map(m)
|
||||
}
|
||||
Some(b'[') => {
|
||||
self.i += 1;
|
||||
let mut v = vec![];
|
||||
loop {
|
||||
self.ws();
|
||||
match self.peek() {
|
||||
None => break,
|
||||
Some(b']') => {
|
||||
self.i += 1;
|
||||
break;
|
||||
}
|
||||
Some(b',') => {
|
||||
self.i += 1;
|
||||
continue;
|
||||
}
|
||||
_ => v.push(self.value()),
|
||||
}
|
||||
}
|
||||
Yaml::Seq(v)
|
||||
}
|
||||
Some(b'!') => {
|
||||
let start = self.i;
|
||||
while self.i < self.s.len() && !(self.s[self.i] as char).is_whitespace() && self.s[self.i] != b'{' && self.s[self.i] != b'[' {
|
||||
self.i += 1;
|
||||
}
|
||||
let tag = tag_name(std::str::from_utf8(&self.s[start..self.i]).unwrap_or(""));
|
||||
self.ws();
|
||||
let inner = match self.peek() {
|
||||
Some(b'{') | Some(b'[') => self.value(),
|
||||
_ => Yaml::Null,
|
||||
};
|
||||
Yaml::Tagged(tag, Box::new(inner))
|
||||
}
|
||||
_ => {
|
||||
let s = self.scalar(false);
|
||||
if s.is_empty() { Yaml::Null } else { Yaml::Str(unquote(&s)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
/// A plain or quoted scalar, ending at `,` `}` `]` (and `:` + space for keys).
|
||||
fn scalar(&mut self, key: bool) -> String {
|
||||
self.ws();
|
||||
let start = self.i;
|
||||
if let Some(q @ (b'"' | b'\'')) = self.peek() {
|
||||
self.i += 1;
|
||||
while self.i < self.s.len() && self.s[self.i] != q {
|
||||
self.i += 1;
|
||||
}
|
||||
self.i = (self.i + 1).min(self.s.len());
|
||||
return String::from_utf8_lossy(&self.s[start..self.i]).into_owned();
|
||||
}
|
||||
while self.i < self.s.len() {
|
||||
let c = self.s[self.i];
|
||||
if c == b',' || c == b'}' || c == b']' {
|
||||
break;
|
||||
}
|
||||
if key && c == b':' {
|
||||
break;
|
||||
}
|
||||
self.i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&self.s[start..self.i]).trim().to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn tag_name(t: &str) -> String {
|
||||
t.trim().trim_start_matches('!').trim_start_matches('<').trim_end_matches('>').to_string()
|
||||
}
|
||||
|
||||
fn flow(s: &str) -> Yaml {
|
||||
Flow { s: s.as_bytes(), i: 0 }.value()
|
||||
}
|
||||
|
||||
struct Lines {
|
||||
/// (indent, content without comment), blank lines removed.
|
||||
v: Vec<(usize, String)>,
|
||||
}
|
||||
|
||||
impl Lines {
|
||||
fn new(text: &str) -> Lines {
|
||||
let v = text
|
||||
.lines()
|
||||
.filter(|l| !l.trim_start().starts_with('%') && l.trim() != "---" && l.trim() != "...")
|
||||
.map(|l| {
|
||||
let c = strip_comment(l).trim_end();
|
||||
(c.len() - c.trim_start().len(), c.trim_start().to_string())
|
||||
})
|
||||
.filter(|(_, c)| !c.is_empty())
|
||||
.collect();
|
||||
Lines { v }
|
||||
}
|
||||
|
||||
/// The value of a `key:` / `- ` remainder `rest` whose children are indented more than
|
||||
/// `indent` (from line `*i`).
|
||||
fn value(&self, rest: &str, indent: usize, i: &mut usize) -> Yaml {
|
||||
let rest = rest.trim();
|
||||
if rest.is_empty() {
|
||||
return match self.v.get(*i) {
|
||||
// A sequence may sit at the key's own indent.
|
||||
Some((ind, c)) if *ind > indent || (*ind == indent && (c == "-" || c.starts_with("- "))) => self.block(*ind, i),
|
||||
_ => Yaml::Null,
|
||||
};
|
||||
}
|
||||
if rest == "|" || rest == ">" || rest.starts_with("|-") || rest.starts_with(">-") || rest.starts_with("|+") || rest.starts_with(">+") {
|
||||
let mut out = vec![];
|
||||
while let Some((ind, c)) = self.v.get(*i) {
|
||||
if *ind <= indent {
|
||||
break;
|
||||
}
|
||||
out.push(c.clone());
|
||||
*i += 1;
|
||||
}
|
||||
return Yaml::Str(out.join(if rest.starts_with('>') { " " } else { "\n" }));
|
||||
}
|
||||
if rest.starts_with('!') && !rest.contains('{') && !rest.contains('[') {
|
||||
let tag = tag_name(rest);
|
||||
let inner = match self.v.get(*i) {
|
||||
Some((ind, _)) if *ind > indent => self.block(*ind, i),
|
||||
_ => Yaml::Null,
|
||||
};
|
||||
return Yaml::Tagged(tag, Box::new(inner));
|
||||
}
|
||||
if rest.starts_with('{') || rest.starts_with('[') || (rest.starts_with('!') && (rest.contains('{') || rest.contains('['))) {
|
||||
// Flow collections may continue on the next lines.
|
||||
let mut text = rest.to_string();
|
||||
while balance(&text) > 0 && *i < self.v.len() {
|
||||
text.push(' ');
|
||||
text.push_str(&self.v[*i].1);
|
||||
*i += 1;
|
||||
}
|
||||
return flow(&text);
|
||||
}
|
||||
Yaml::Str(unquote(rest))
|
||||
}
|
||||
|
||||
/// A block node whose lines start at `indent`.
|
||||
fn block(&self, indent: usize, i: &mut usize) -> Yaml {
|
||||
let Some((_, first)) = self.v.get(*i) else { return Yaml::Null };
|
||||
if first == "-" || first.starts_with("- ") {
|
||||
let mut items = vec![];
|
||||
while let Some((ind, c)) = self.v.get(*i) {
|
||||
if *ind != indent || !(c == "-" || c.starts_with("- ")) {
|
||||
break;
|
||||
}
|
||||
*i += 1;
|
||||
let rest = c[1..].trim_start().to_string();
|
||||
// `- key: value` opens a mapping whose keys are indented to the key.
|
||||
if split_key(&rest).is_some() && !rest.starts_with('{') && !rest.starts_with('!') {
|
||||
let inner = indent + 1 + (c.len() - 1 - c[1..].trim_start().len());
|
||||
items.push(self.map_from(Some(rest), inner.max(indent + 2), i));
|
||||
} else {
|
||||
items.push(self.value(&rest, indent, i));
|
||||
}
|
||||
}
|
||||
return Yaml::Seq(items);
|
||||
}
|
||||
if split_key(first).is_some() {
|
||||
return self.map_from(None, indent, i);
|
||||
}
|
||||
*i += 1;
|
||||
Yaml::Str(unquote(first))
|
||||
}
|
||||
|
||||
/// A block mapping at `indent`; `first` is an entry already taken from a `- ` line.
|
||||
fn map_from(&self, first: Option<String>, indent: usize, i: &mut usize) -> Yaml {
|
||||
let mut m = vec![];
|
||||
if let Some(f) = first
|
||||
&& let Some((k, rest)) = split_key(&f)
|
||||
{
|
||||
let v = self.value(rest, indent, i);
|
||||
m.push((k, v));
|
||||
}
|
||||
while let Some((ind, c)) = self.v.get(*i) {
|
||||
if *ind != indent {
|
||||
if *ind < indent {
|
||||
break;
|
||||
}
|
||||
// Over-indented stray line: skip.
|
||||
*i += 1;
|
||||
continue;
|
||||
}
|
||||
let Some((k, rest)) = split_key(c) else { break };
|
||||
*i += 1;
|
||||
let v = self.value(rest, indent, i);
|
||||
m.push((k, v));
|
||||
}
|
||||
Yaml::Map(m)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a YAML document (the subset described in the module docs).
|
||||
pub fn parse_yaml(text: &str) -> Yaml {
|
||||
let l = Lines::new(text);
|
||||
let mut i = 0;
|
||||
let indent = l.v.first().map_or(0, |(ind, _)| *ind);
|
||||
l.block(indent, &mut i)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- transforms
|
||||
|
||||
/// A colour transform of a config.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Xf {
|
||||
/// 4×4 row-major matrix (RGB of the first three rows/columns) plus offset.
|
||||
Matrix {
|
||||
m: [f64; 16],
|
||||
offset: [f64; 4],
|
||||
},
|
||||
File {
|
||||
src: String,
|
||||
xf: Option<Arc<FileXform>>,
|
||||
interp: u32,
|
||||
ccc: String,
|
||||
},
|
||||
Exponent([f64; 3]),
|
||||
Log {
|
||||
base: f64,
|
||||
},
|
||||
LogAffine {
|
||||
base: f64,
|
||||
log_slope: [f64; 3],
|
||||
log_offset: [f64; 3],
|
||||
lin_slope: [f64; 3],
|
||||
lin_offset: [f64; 3],
|
||||
},
|
||||
Cdl(Cdl),
|
||||
Range {
|
||||
min_in: f64,
|
||||
max_in: f64,
|
||||
min_out: f64,
|
||||
max_out: f64,
|
||||
},
|
||||
Group(Vec<Xf>),
|
||||
Inverse(Box<Xf>),
|
||||
/// An unsupported transform (by tag): identity.
|
||||
Unsupported(String),
|
||||
}
|
||||
|
||||
fn vec3_of(y: Option<&Yaml>, d: f64) -> [f64; 3] {
|
||||
let v = y.map(Yaml::nums).unwrap_or_default();
|
||||
match v.len() {
|
||||
0 => [d; 3],
|
||||
1 | 2 => [v[0]; 3],
|
||||
_ => [v[0], v[1], v[2]],
|
||||
}
|
||||
}
|
||||
|
||||
fn mat_apply(m: &[f64; 16], off: &[f64; 4], c: [f64; 3]) -> [f64; 3] {
|
||||
[0, 1, 2].map(|r| m[r * 4] * c[0] + m[r * 4 + 1] * c[1] + m[r * 4 + 2] * c[2] + off[r])
|
||||
}
|
||||
|
||||
fn mat3_inverse(m: &[f64; 16]) -> Option<[[f64; 3]; 3]> {
|
||||
let a = [[m[0], m[1], m[2]], [m[4], m[5], m[6]], [m[8], m[9], m[10]]];
|
||||
let det = a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
|
||||
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]);
|
||||
(det.abs() > 1e-12).then(|| effectcraft_color::space::invert(&a))
|
||||
}
|
||||
|
||||
fn log_base(v: f64, base: f64) -> f64 {
|
||||
v.max(f64::MIN_POSITIVE).ln() / base.ln()
|
||||
}
|
||||
|
||||
impl Xf {
|
||||
fn from_yaml(y: &Yaml, dir: &Path, search: &[String]) -> Xf {
|
||||
let tag = y.tag().unwrap_or("");
|
||||
let body = match y {
|
||||
Yaml::Tagged(_, b) => b.as_ref(),
|
||||
other => other,
|
||||
};
|
||||
let inverse = body.get("direction").and_then(Yaml::str).is_some_and(|d| d.eq_ignore_ascii_case("inverse"));
|
||||
let xf = match tag {
|
||||
"MatrixTransform" => {
|
||||
let v = body.get("matrix").map(Yaml::nums).unwrap_or_default();
|
||||
let mut m = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
if v.len() == 16 {
|
||||
m.copy_from_slice(&v);
|
||||
} else if v.len() == 9 {
|
||||
for r in 0..3 {
|
||||
for c in 0..3 {
|
||||
m[r * 4 + c] = v[r * 3 + c];
|
||||
}
|
||||
}
|
||||
}
|
||||
let o = body.get("offset").map(Yaml::nums).unwrap_or_default();
|
||||
let mut offset = [0.0; 4];
|
||||
for (k, v) in o.iter().take(4).enumerate() {
|
||||
offset[k] = *v;
|
||||
}
|
||||
Xf::Matrix { m, offset }
|
||||
}
|
||||
"FileTransform" => {
|
||||
let src = body.get("src").and_then(Yaml::str).unwrap_or("").to_string();
|
||||
let interp = match body.get("interpolation").and_then(Yaml::str).unwrap_or("linear").to_ascii_lowercase().as_str() {
|
||||
"nearest" => 0,
|
||||
"tetrahedral" | "best" => 2,
|
||||
_ => 1,
|
||||
};
|
||||
let ccc = body.get("cccid").or_else(|| body.get("ccc_id")).and_then(Yaml::str).unwrap_or("").to_string();
|
||||
let xf = resolve(&src, dir, search).and_then(|p| load_file(&p.to_string_lossy()));
|
||||
Xf::File { src, xf, interp, ccc }
|
||||
}
|
||||
"ExponentTransform" => Xf::Exponent(vec3_of(body.get("value"), 1.0)),
|
||||
"LogTransform" => Xf::Log { base: body.get("base").and_then(Yaml::f).unwrap_or(2.0) },
|
||||
"LogAffineTransform" => Xf::LogAffine {
|
||||
base: body.get("base").and_then(Yaml::f).unwrap_or(2.0),
|
||||
log_slope: vec3_of(body.get("logSideSlope"), 1.0),
|
||||
log_offset: vec3_of(body.get("logSideOffset"), 0.0),
|
||||
lin_slope: vec3_of(body.get("linSideSlope"), 1.0),
|
||||
lin_offset: vec3_of(body.get("linSideOffset"), 0.0),
|
||||
},
|
||||
"CDLTransform" => Xf::Cdl(Cdl {
|
||||
slope: vec3_of(body.get("slope"), 1.0),
|
||||
offset: vec3_of(body.get("offset"), 0.0),
|
||||
power: vec3_of(body.get("power"), 1.0),
|
||||
sat: body.get("sat").and_then(Yaml::f).unwrap_or(1.0),
|
||||
}),
|
||||
"RangeTransform" => Xf::Range {
|
||||
min_in: body.get("min_in_value").and_then(Yaml::f).unwrap_or(0.0),
|
||||
max_in: body.get("max_in_value").and_then(Yaml::f).unwrap_or(1.0),
|
||||
min_out: body.get("min_out_value").and_then(Yaml::f).unwrap_or(0.0),
|
||||
max_out: body.get("max_out_value").and_then(Yaml::f).unwrap_or(1.0),
|
||||
},
|
||||
"GroupTransform" => Xf::Group(body.get("children").map(|c| c.seq().iter().map(|t| Xf::from_yaml(t, dir, search)).collect()).unwrap_or_default()),
|
||||
other => Xf::Unsupported(other.to_string()),
|
||||
};
|
||||
if inverse { Xf::Inverse(Box::new(xf)) } else { xf }
|
||||
}
|
||||
|
||||
/// Apply forward (or inverse) to linear-or-encoded RGB.
|
||||
pub fn apply(&self, c: [f64; 3], inverse: bool) -> [f64; 3] {
|
||||
match self {
|
||||
Xf::Inverse(x) => x.apply(c, !inverse),
|
||||
Xf::Matrix { m, offset } => {
|
||||
if !inverse {
|
||||
return mat_apply(m, offset, c);
|
||||
}
|
||||
match mat3_inverse(m) {
|
||||
Some(inv) => {
|
||||
let d = [c[0] - offset[0], c[1] - offset[1], c[2] - offset[2]];
|
||||
effectcraft_color::space::mul_vec(&inv, d)
|
||||
}
|
||||
None => c,
|
||||
}
|
||||
}
|
||||
Xf::File { xf, interp, ccc, .. } => match xf {
|
||||
Some(x) => x.apply(c.map(|v| v as f32), *interp, inverse, ccc).map(|v| v as f64),
|
||||
None => c,
|
||||
},
|
||||
Xf::Exponent(e) => [0, 1, 2].map(|k| {
|
||||
let p = if inverse { 1.0 / e[k].max(1e-9) } else { e[k] };
|
||||
c[k].max(0.0).powf(p)
|
||||
}),
|
||||
Xf::Log { base } => {
|
||||
if inverse {
|
||||
c.map(|v| base.powf(v))
|
||||
} else {
|
||||
c.map(|v| log_base(v, *base))
|
||||
}
|
||||
}
|
||||
Xf::LogAffine { base, log_slope, log_offset, lin_slope, lin_offset } => [0, 1, 2].map(|k| {
|
||||
if inverse {
|
||||
(base.powf((c[k] - log_offset[k]) / log_slope[k]) - lin_offset[k]) / lin_slope[k]
|
||||
} else {
|
||||
log_slope[k] * log_base(lin_slope[k] * c[k] + lin_offset[k], *base) + log_offset[k]
|
||||
}
|
||||
}),
|
||||
Xf::Cdl(cdl) => {
|
||||
if inverse {
|
||||
cdl.invert(c, true)
|
||||
} else {
|
||||
cdl.apply(c, true)
|
||||
}
|
||||
}
|
||||
Xf::Range { min_in, max_in, min_out, max_out } => {
|
||||
let (a0, a1, b0, b1) = if inverse { (*min_out, *max_out, *min_in, *max_in) } else { (*min_in, *max_in, *min_out, *max_out) };
|
||||
let k = if (a1 - a0).abs() > 1e-12 { (b1 - b0) / (a1 - a0) } else { 0.0 };
|
||||
c.map(|v| b0 + (v - a0) * k)
|
||||
}
|
||||
Xf::Group(list) => {
|
||||
let mut v = c;
|
||||
if inverse {
|
||||
for x in list.iter().rev() {
|
||||
v = x.apply(v, true);
|
||||
}
|
||||
} else {
|
||||
for x in list {
|
||||
v = x.apply(v, false);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
Xf::Unsupported(_) => c,
|
||||
}
|
||||
}
|
||||
|
||||
fn unsupported(&self, out: &mut Vec<String>) {
|
||||
match self {
|
||||
Xf::Unsupported(t) => out.push(t.clone()),
|
||||
Xf::Inverse(x) => x.unsupported(out),
|
||||
Xf::Group(v) => v.iter().for_each(|x| x.unsupported(out)),
|
||||
Xf::File { src, xf: None, .. } => out.push(format!("FileTransform (missing `{src}`)")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Find a FileTransform source on the search path (relative to the config's folder).
|
||||
fn resolve(src: &str, dir: &Path, search: &[String]) -> Option<PathBuf> {
|
||||
let p = Path::new(src);
|
||||
if p.is_absolute() {
|
||||
return p.exists().then(|| p.to_path_buf());
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = search.iter().map(|s| dir.join(s)).collect();
|
||||
dirs.push(dir.to_path_buf());
|
||||
dirs.into_iter().map(|d| d.join(src)).find(|c| c.exists())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the config
|
||||
|
||||
/// A colour space of a config.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConfigSpace {
|
||||
pub name: String,
|
||||
pub aliases: Vec<String>,
|
||||
pub family: String,
|
||||
pub is_data: bool,
|
||||
pub to_ref: Option<Xf>,
|
||||
pub from_ref: Option<Xf>,
|
||||
}
|
||||
|
||||
impl ConfigSpace {
|
||||
fn to_reference(&self, c: [f64; 3]) -> [f64; 3] {
|
||||
match (&self.to_ref, &self.from_ref) {
|
||||
(Some(x), _) => x.apply(c, false),
|
||||
(None, Some(x)) => x.apply(c, true),
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
fn reference_to(&self, c: [f64; 3]) -> [f64; 3] {
|
||||
match (&self.from_ref, &self.to_ref) {
|
||||
(Some(x), _) => x.apply(c, false),
|
||||
(None, Some(x)) => x.apply(c, true),
|
||||
_ => c,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed `.ocio` configuration.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Config {
|
||||
pub name: String,
|
||||
pub search_path: Vec<String>,
|
||||
pub roles: Vec<(String, String)>,
|
||||
pub spaces: Vec<ConfigSpace>,
|
||||
/// Display → [(view, colour space)].
|
||||
pub displays: Vec<(String, Vec<(String, String)>)>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
/// Parse config text; FileTransform sources resolve against `dir`.
|
||||
pub fn parse(text: &str, dir: &Path) -> Result<Config, String> {
|
||||
let y = parse_yaml(text);
|
||||
if !matches!(y, Yaml::Map(_)) {
|
||||
return Err("not an OCIO config (expected a YAML mapping)".into());
|
||||
}
|
||||
let search_path: Vec<String> = match y.get("search_path") {
|
||||
Some(Yaml::Seq(v)) => v.iter().filter_map(|s| s.str().map(str::to_string)).collect(),
|
||||
Some(s) => s.str().map(|s| s.split(':').map(|p| p.trim().to_string()).filter(|p| !p.is_empty()).collect()).unwrap_or_default(),
|
||||
None => vec![],
|
||||
};
|
||||
let roles = match y.get("roles") {
|
||||
Some(Yaml::Map(m)) => m.iter().filter_map(|(k, v)| v.str().map(|s| (k.clone(), s.to_string()))).collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
let mut spaces = vec![];
|
||||
for list in ["colorspaces", "display_colorspaces"] {
|
||||
for cs in y.get(list).map(Yaml::seq).unwrap_or(&[]) {
|
||||
let Some(name) = cs.get("name").and_then(Yaml::str) else { continue };
|
||||
let xf = |keys: &[&str]| keys.iter().find_map(|k| cs.get(k)).filter(|v| !matches!(v, Yaml::Null)).map(|v| Xf::from_yaml(v, dir, &search_path));
|
||||
spaces.push(ConfigSpace {
|
||||
name: name.to_string(),
|
||||
aliases: cs.get("aliases").map(|a| a.seq().iter().filter_map(|s| s.str().map(str::to_string)).collect()).unwrap_or_default(),
|
||||
family: cs.get("family").and_then(Yaml::str).unwrap_or("").to_string(),
|
||||
is_data: cs.get("isdata").and_then(Yaml::str).is_some_and(|v| v == "true"),
|
||||
to_ref: xf(&["to_reference", "to_scene_reference", "to_display_reference"]),
|
||||
from_ref: xf(&["from_reference", "from_scene_reference", "from_display_reference"]),
|
||||
});
|
||||
}
|
||||
}
|
||||
if spaces.is_empty() {
|
||||
return Err("the config has no colorspaces".into());
|
||||
}
|
||||
let displays = match y.get("displays") {
|
||||
Some(Yaml::Map(m)) => m
|
||||
.iter()
|
||||
.map(|(d, views)| {
|
||||
let v = views.seq().iter().filter_map(|v| Some((v.get("name")?.str()?.to_string(), v.get("colorspace")?.str()?.to_string()))).collect();
|
||||
(d.clone(), v)
|
||||
})
|
||||
.collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Ok(Config { name: y.get("name").and_then(Yaml::str).unwrap_or("").to_string(), search_path, roles, spaces, displays })
|
||||
}
|
||||
|
||||
pub fn space_names(&self) -> Vec<&str> {
|
||||
self.spaces.iter().map(|s| s.name.as_str()).collect()
|
||||
}
|
||||
|
||||
/// A colour space by name, alias or role (case-insensitive).
|
||||
pub fn space(&self, name: &str) -> Option<&ConfigSpace> {
|
||||
let n = name.trim();
|
||||
let by = |n: &str| self.spaces.iter().find(|s| s.name.eq_ignore_ascii_case(n) || s.aliases.iter().any(|a| a.eq_ignore_ascii_case(n)));
|
||||
by(n).or_else(|| self.roles.iter().find(|(r, _)| r.eq_ignore_ascii_case(n)).and_then(|(_, s)| by(s)))
|
||||
}
|
||||
|
||||
/// The colour space of a display's view.
|
||||
pub fn view_space(&self, display: &str, view: &str) -> Option<&ConfigSpace> {
|
||||
let (_, views) = self.displays.iter().find(|(d, _)| d.eq_ignore_ascii_case(display.trim())).or(self.displays.first())?;
|
||||
let (_, cs) = views.iter().find(|(v, _)| v.eq_ignore_ascii_case(view.trim())).or(views.first())?;
|
||||
self.space(cs)
|
||||
}
|
||||
|
||||
/// Convert one colour from space `a` to space `b` (through the reference space; data
|
||||
/// spaces pass through).
|
||||
pub fn convert(&self, a: &ConfigSpace, b: &ConfigSpace, c: [f64; 3]) -> [f64; 3] {
|
||||
if a.is_data || b.is_data || a.name == b.name {
|
||||
return c;
|
||||
}
|
||||
b.reference_to(a.to_reference(c))
|
||||
}
|
||||
|
||||
/// Transforms this module can't apply (by tag), for warnings.
|
||||
pub fn unsupported(&self) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
for s in &self.spaces {
|
||||
for x in [&s.to_ref, &s.from_ref].into_iter().flatten() {
|
||||
x.unsupported(&mut out);
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out.dedup();
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigCache = Mutex<HashMap<String, Option<Arc<Config>>>>;
|
||||
|
||||
/// Load (and cache) a config from a `.ocio` path or the config text itself.
|
||||
pub fn load_config(src: &str) -> Option<Arc<Config>> {
|
||||
let t = src.trim();
|
||||
if t.is_empty() {
|
||||
return None;
|
||||
}
|
||||
static CACHE: OnceLock<ConfigCache> = OnceLock::new();
|
||||
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
if let Ok(m) = cache.lock()
|
||||
&& let Some(v) = m.get(src)
|
||||
{
|
||||
return v.clone();
|
||||
}
|
||||
let parsed = if src.contains('\n') {
|
||||
Config::parse(src, Path::new("."))
|
||||
} else {
|
||||
let p = Path::new(t);
|
||||
std::fs::read_to_string(p).map_err(|e| e.to_string()).and_then(|text| Config::parse(&text, p.parent().unwrap_or(Path::new("."))))
|
||||
}
|
||||
.ok()
|
||||
.map(Arc::new);
|
||||
if let Ok(mut m) = cache.lock() {
|
||||
m.insert(src.to_string(), parsed.clone());
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CONFIG: &str = r#"
|
||||
ocio_profile_version: 2
|
||||
|
||||
name: Test Config # a comment
|
||||
search_path: "luts:other"
|
||||
roles:
|
||||
scene_linear: lin
|
||||
color_timing: "log2"
|
||||
|
||||
displays:
|
||||
sRGB:
|
||||
- !<View> {name: Standard, colorspace: gamma22}
|
||||
- !<View> {name: Raw, colorspace: raw}
|
||||
|
||||
colorspaces:
|
||||
- !<ColorSpace>
|
||||
name: lin
|
||||
family: ""
|
||||
description: |
|
||||
The reference.
|
||||
Linear.
|
||||
isdata: false
|
||||
|
||||
- !<ColorSpace>
|
||||
name: gamma22
|
||||
aliases: [g22, "gamma 2.2"]
|
||||
to_scene_reference: !<ExponentTransform> {value: [2.2, 2.2, 2.2, 1]}
|
||||
|
||||
- !<ColorSpace>
|
||||
name: half
|
||||
from_reference: !<MatrixTransform> {matrix: [0.5, 0, 0, 0,
|
||||
0, 0.5, 0, 0,
|
||||
0, 0, 0.5, 0,
|
||||
0, 0, 0, 1], offset: [0.1, 0.1, 0.1, 0]}
|
||||
|
||||
- !<ColorSpace>
|
||||
name: log2
|
||||
from_reference: !<GroupTransform>
|
||||
children:
|
||||
- !<MatrixTransform> {matrix: [2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 2, 0, 0, 0, 0, 1]}
|
||||
- !<LogTransform> {base: 2}
|
||||
|
||||
- !<ColorSpace>
|
||||
name: affine
|
||||
to_reference: !<LogAffineTransform> {base: 10, logSideSlope: 0.5, logSideOffset: 0.2, linSideSlope: 2, linSideOffset: 0.01, direction: inverse}
|
||||
|
||||
- !<ColorSpace>
|
||||
name: lut
|
||||
to_reference: !<FileTransform> {src: double.cube, interpolation: linear}
|
||||
|
||||
- !<ColorSpace>
|
||||
name: raw
|
||||
isdata: true
|
||||
|
||||
- !<ColorSpace>
|
||||
name: weird
|
||||
to_reference: !<ExposureContrastTransform> {exposure: 1}
|
||||
"#;
|
||||
|
||||
fn close(a: [f64; 3], b: [f64; 3], tol: f64) -> bool {
|
||||
(0..3).all(|i| (a[i] - b[i]).abs() < tol)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn yaml_subset() {
|
||||
let y = parse_yaml("a: 1\nb:\n - x\n - {k: [1, 2], s: 'q: r'}\nc: !<T> {v: 3}\nd:\n- 4\n- 5\n");
|
||||
assert_eq!(y.get("a").and_then(Yaml::str), Some("1"));
|
||||
assert_eq!(y.get("b").unwrap().seq().len(), 2);
|
||||
assert_eq!(y.get("b").unwrap().seq()[1].get("k").unwrap().nums(), vec![1.0, 2.0]);
|
||||
assert_eq!(y.get("b").unwrap().seq()[1].get("s").and_then(Yaml::str), Some("q: r"));
|
||||
assert_eq!(y.get("c").unwrap().tag(), Some("T"));
|
||||
assert_eq!(y.get("c").unwrap().get("v").and_then(Yaml::str), Some("3"));
|
||||
assert_eq!(y.get("d").unwrap().seq().len(), 2, "a sequence at the key's indent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_spaces_roles_displays_and_converts() {
|
||||
let dir = std::env::temp_dir().join(format!("ec-ocio-{}", std::process::id()));
|
||||
std::fs::create_dir_all(dir.join("luts")).unwrap();
|
||||
// A 1D LUT that doubles (0..1 → 0..2).
|
||||
std::fs::write(dir.join("luts/double.cube"), "LUT_1D_SIZE 2\nDOMAIN_MIN 0 0 0\nDOMAIN_MAX 1 1 1\n0 0 0\n2 2 2\n").unwrap();
|
||||
let c = Config::parse(CONFIG, &dir).unwrap();
|
||||
assert_eq!(c.name, "Test Config");
|
||||
assert_eq!(c.search_path, vec!["luts", "other"]);
|
||||
assert_eq!(c.space_names(), vec!["lin", "gamma22", "half", "log2", "affine", "lut", "raw", "weird"]);
|
||||
// Roles and aliases resolve.
|
||||
assert_eq!(c.space("scene_linear").unwrap().name, "lin");
|
||||
assert_eq!(c.space("G22").unwrap().name, "gamma22");
|
||||
assert_eq!(c.space("gamma 2.2").unwrap().name, "gamma22");
|
||||
assert_eq!(c.view_space("sRGB", "Standard").unwrap().name, "gamma22");
|
||||
let sp = |n: &str| c.space(n).unwrap();
|
||||
// gamma22 → lin: decode with the exponent.
|
||||
let g = c.convert(sp("gamma22"), sp("lin"), [0.5, 0.25, 1.0]);
|
||||
assert!(close(g, [0.5f64.powf(2.2), 0.25f64.powf(2.2), 1.0], 1e-9), "{g:?}");
|
||||
// lin → gamma22: the inverse (only to_reference given).
|
||||
let back = c.convert(sp("lin"), sp("gamma22"), g);
|
||||
assert!(close(back, [0.5, 0.25, 1.0], 1e-9), "{back:?}");
|
||||
// lin → half: matrix and offset; and back through the inverse matrix.
|
||||
let h = c.convert(sp("lin"), sp("half"), [0.4, 0.6, 1.0]);
|
||||
assert!(close(h, [0.3, 0.4, 0.6], 1e-9), "{h:?}");
|
||||
assert!(close(c.convert(sp("half"), sp("lin"), h), [0.4, 0.6, 1.0], 1e-9));
|
||||
// lin → log2: a group (×2 then log2): 0.5 → 0; 2 → 2.
|
||||
let l = c.convert(sp("lin"), sp("log2"), [0.5, 2.0, 4.0]);
|
||||
assert!(close(l, [0.0, 2.0, 3.0], 1e-9), "{l:?}");
|
||||
assert!(close(c.convert(sp("log2"), sp("lin"), l), [0.5, 2.0, 4.0], 1e-9));
|
||||
// LogAffine (inverse direction as to_reference) round-trips.
|
||||
let a = c.convert(sp("lin"), sp("affine"), [0.18, 0.5, 1.0]);
|
||||
let expect = [0.18f64, 0.5, 1.0].map(|v| 0.5 * (2.0 * v + 0.01).log10() + 0.2);
|
||||
assert!(close(a, expect, 1e-9), "{a:?} vs {expect:?}");
|
||||
assert!(close(c.convert(sp("affine"), sp("lin"), a), [0.18, 0.5, 1.0], 1e-9));
|
||||
// FileTransform found on the search path.
|
||||
let f = c.convert(sp("lut"), sp("lin"), [0.25, 0.5, 0.0]);
|
||||
assert!(close(f, [0.5, 1.0, 0.0], 1e-6), "{f:?}");
|
||||
// Data spaces pass through; unsupported transforms are reported.
|
||||
assert_eq!(c.convert(sp("raw"), sp("gamma22"), [0.3, 0.3, 0.3]), [0.3, 0.3, 0.3]);
|
||||
assert_eq!(c.unsupported(), vec!["ExposureContrastTransform".to_string()]);
|
||||
// Loading from a file path (cached), and errors.
|
||||
std::fs::write(dir.join("config.ocio"), CONFIG).unwrap();
|
||||
let loaded = load_config(&dir.join("config.ocio").to_string_lossy()).unwrap();
|
||||
assert_eq!(loaded.spaces.len(), 8);
|
||||
assert!(load_config("/no/such/config.ocio").is_none());
|
||||
assert!(Config::parse("just: text\n", &dir).is_err());
|
||||
}
|
||||
/// The OCIO Color Space and Display Transform effects with Configuration ▸ Custom.
|
||||
#[test]
|
||||
fn effects_use_a_custom_config() {
|
||||
use effectcraft_keyframe::Value;
|
||||
let cfg = "ocio_profile_version: 1\nroles:\n default: lin\ndisplays:\n Monitor:\n - !<View> {name: Video, colorspace: g2}\ncolorspaces:\n - !<ColorSpace>\n name: lin\n - !<ColorSpace>\n name: g2\n to_reference: !<ExponentTransform> {value: [2, 2, 2, 1]}\n";
|
||||
let img = crate::Image::filled(2, 2, [0.5, 0.25, 1.0, 1.0]);
|
||||
let fx = |id: &str, extra: &[(&str, Value)]| {
|
||||
let mut v = vec![("config", Value::Enum(1)), ("configFile", Value::Str(cfg.into()))];
|
||||
v.extend(extra.iter().cloned());
|
||||
crate::run_fx(id, &v, img.clone(), 0.0, crate::EffectEnv::default()).img.data[0]
|
||||
};
|
||||
let o = fx("ec.color.ociocolorspace", &[("sourceName", Value::Str("g2".into())), ("destinationName", Value::Str("default".into()))]);
|
||||
assert!((o[0] - 0.25).abs() < 1e-6 && (o[1] - 0.0625).abs() < 1e-6 && (o[2] - 1.0).abs() < 1e-6, "{o:?}");
|
||||
// Inverse direction.
|
||||
let o = fx(
|
||||
"ec.color.ociocolorspace",
|
||||
&[("sourceName", Value::Str("g2".into())), ("destinationName", Value::Str("lin".into())), ("direction", Value::Enum(1))],
|
||||
);
|
||||
assert!((o[0] - 0.5f32.sqrt()).abs() < 1e-6, "{o:?}");
|
||||
// Display ▸ view → its colour space.
|
||||
let o = fx(
|
||||
"ec.color.ociodisplay",
|
||||
&[("sourceName", Value::Str("lin".into())), ("displayName", Value::Str("Monitor".into())), ("viewName", Value::Str("Video".into()))],
|
||||
);
|
||||
assert!((o[0] - 0.5f32.sqrt()).abs() < 1e-6, "{o:?}");
|
||||
// An unreadable config leaves pixels alone.
|
||||
let o = crate::run_fx(
|
||||
"ec.color.ociocolorspace",
|
||||
&[("config", Value::Enum(1)), ("configFile", Value::Str("/missing.ocio".into()))],
|
||||
img.clone(),
|
||||
0.0,
|
||||
crate::EffectEnv::default(),
|
||||
);
|
||||
assert_eq!(o.img.data, img.data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
//! The effect plug-in API, version [`PLUGIN_API_VERSION`].
|
||||
//!
|
||||
//! A plug-in is anything implementing [`EffectPlugin`]: a [`PluginManifest`] (stable id,
|
||||
//! display name, Effects & Presets category, typed parameters) and a `render` that processes a
|
||||
//! [`PluginFrame`] in place. [`register_plugin`] turns it into an ordinary [`EffectSpec`]:
|
||||
//! instances are property groups like every built-in effect, so plug-in parameters animate,
|
||||
//! take expressions, show in Effect Controls and are addressable by agents, and the effect is
|
||||
//! applied by id (`effect.apply {"effect": "org.example.posterize"}`) like a built-in.
|
||||
//!
|
||||
//! Plug-ins come from Rust code (implement the trait and register it at start-up) or from
|
||||
//! sandboxed WebAssembly modules (`effectcraft-plugin`, see `docs/plugins.md`), which implement
|
||||
//! the same contract through a small C-like ABI.
|
||||
//!
|
||||
//! The contract (stable within an API version):
|
||||
//! * pixels are premultiplied RGBA `f32` (0–1, may exceed 1 in 32 bpc projects), row-major,
|
||||
//! in the layer's buffer, which may be scaled (preview resolution) and padded;
|
||||
//! * parameters are flattened to `f64`s in declaration order: slider / angle / checkbox (0 or 1)
|
||||
//! / popup (0-based index) take one value, point two (**frame pixels**, already mapped to the
|
||||
//! buffer), colour four (RGBA 0–1);
|
||||
//! * `time` is layer time in seconds; `scale` is the buffer's pixels per layer pixel (scale
|
||||
//! pixel distances like blur radii by it);
|
||||
//! * rendering must be deterministic (same inputs, same output) and may run on several threads
|
||||
//! at once.
|
||||
|
||||
use std::sync::{Arc, OnceLock, RwLock};
|
||||
|
||||
use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, ParamSpec, RenderFn};
|
||||
|
||||
/// The plug-in API version this build implements.
|
||||
pub const PLUGIN_API_VERSION: u32 = 1;
|
||||
|
||||
/// The most plug-in effects one process can register.
|
||||
pub const MAX_PLUGINS: usize = 64;
|
||||
|
||||
/// A plug-in parameter's kind, default and range.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "lowercase")]
|
||||
pub enum PluginParamKind {
|
||||
Slider {
|
||||
default: f64,
|
||||
#[serde(default)]
|
||||
min: f64,
|
||||
#[serde(default = "hundred")]
|
||||
max: f64,
|
||||
/// Slider range (defaults to min..max).
|
||||
#[serde(default, rename = "sliderMin")]
|
||||
slider_min: Option<f64>,
|
||||
#[serde(default, rename = "sliderMax")]
|
||||
slider_max: Option<f64>,
|
||||
#[serde(default = "two")]
|
||||
decimals: u8,
|
||||
},
|
||||
Angle {
|
||||
#[serde(default)]
|
||||
default: f64,
|
||||
},
|
||||
Checkbox {
|
||||
#[serde(default)]
|
||||
default: bool,
|
||||
},
|
||||
Popup {
|
||||
options: Vec<String>,
|
||||
/// 0-based index.
|
||||
#[serde(default)]
|
||||
default: u32,
|
||||
},
|
||||
/// Default as fractions of the layer size (`[0.5, 0.5]` = centre).
|
||||
Point {
|
||||
#[serde(default = "centre")]
|
||||
default: [f64; 2],
|
||||
},
|
||||
/// RGBA, 0–1.
|
||||
Color {
|
||||
#[serde(default = "white")]
|
||||
default: [f64; 4],
|
||||
},
|
||||
}
|
||||
|
||||
fn hundred() -> f64 {
|
||||
100.0
|
||||
}
|
||||
fn two() -> u8 {
|
||||
2
|
||||
}
|
||||
fn centre() -> [f64; 2] {
|
||||
[0.5, 0.5]
|
||||
}
|
||||
fn white() -> [f64; 4] {
|
||||
[1.0; 4]
|
||||
}
|
||||
|
||||
impl PluginParamKind {
|
||||
/// How many `f64`s the parameter flattens to.
|
||||
pub fn width(&self) -> usize {
|
||||
match self {
|
||||
PluginParamKind::Point { .. } => 2,
|
||||
PluginParamKind::Color { .. } => 4,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One parameter of a plug-in effect.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PluginParam {
|
||||
/// Stable id (the property's match name; letters, digits, `_`).
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(flatten)]
|
||||
pub kind: PluginParamKind,
|
||||
}
|
||||
|
||||
/// What a plug-in declares about itself.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PluginManifest {
|
||||
/// The plug-in API version it was written for (must be [`PLUGIN_API_VERSION`]).
|
||||
pub api: u32,
|
||||
/// Stable, reverse-domain effect id (`org.example.posterize`); `ec.` is reserved.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// Effects & Presets category: one of [`crate::CATEGORIES`] or a new one.
|
||||
pub category: String,
|
||||
#[serde(default)]
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub params: Vec<PluginParam>,
|
||||
}
|
||||
|
||||
impl PluginManifest {
|
||||
/// Check the manifest against this API version.
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.api != PLUGIN_API_VERSION {
|
||||
return Err(format!("plug-in `{}` targets plug-in API {} but this build implements API {PLUGIN_API_VERSION}", self.id, self.api));
|
||||
}
|
||||
let ok_id = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
|
||||
if !ok_id(&self.id) || self.id.starts_with("ec.") {
|
||||
return Err(format!("bad plug-in id `{}` (reverse-domain, letters, digits, `.`, `_`, `-`; `ec.` is reserved)", self.id));
|
||||
}
|
||||
if self.name.trim().is_empty() || self.category.trim().is_empty() {
|
||||
return Err(format!("plug-in `{}` needs a name and a category", self.id));
|
||||
}
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for p in &self.params {
|
||||
if p.id.is_empty() || !p.id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') || !seen.insert(p.id.as_str()) {
|
||||
return Err(format!("plug-in `{}`: bad or duplicate parameter id `{}`", self.id, p.id));
|
||||
}
|
||||
if let PluginParamKind::Popup { options, default } = &p.kind
|
||||
&& (options.is_empty() || *default as usize >= options.len())
|
||||
{
|
||||
return Err(format!("plug-in `{}`: popup `{}` needs options and a default index in range", self.id, p.id));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Total flattened parameter count.
|
||||
pub fn flat_len(&self) -> usize {
|
||||
self.params.iter().map(|p| p.kind.width()).sum()
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixels a plug-in renders, in place.
|
||||
pub struct PluginFrame<'a> {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Premultiplied RGBA, row-major, `width * height` pixels.
|
||||
pub pixels: &'a mut [[f32; 4]],
|
||||
/// Buffer pixels per layer pixel (preview resolution).
|
||||
pub scale: f64,
|
||||
}
|
||||
|
||||
/// Parameter values for one render, flattened (see the module docs) with typed accessors.
|
||||
pub struct PluginParams<'a> {
|
||||
pub manifest: &'a PluginManifest,
|
||||
pub flat: &'a [f64],
|
||||
}
|
||||
|
||||
impl PluginParams<'_> {
|
||||
fn slot(&self, id: &str) -> Option<&[f64]> {
|
||||
let mut at = 0;
|
||||
for p in &self.manifest.params {
|
||||
let w = p.kind.width();
|
||||
if p.id == id {
|
||||
return self.flat.get(at..at + w);
|
||||
}
|
||||
at += w;
|
||||
}
|
||||
None
|
||||
}
|
||||
/// Slider / angle / popup index / checkbox (0 or 1).
|
||||
pub fn f(&self, id: &str) -> f64 {
|
||||
self.slot(id).and_then(|s| s.first().copied()).unwrap_or(0.0)
|
||||
}
|
||||
pub fn b(&self, id: &str) -> bool {
|
||||
self.f(id) != 0.0
|
||||
}
|
||||
/// Point in frame pixels.
|
||||
pub fn point(&self, id: &str) -> [f64; 2] {
|
||||
self.slot(id).map(|s| [s[0], s[1]]).unwrap_or([0.0; 2])
|
||||
}
|
||||
pub fn color(&self, id: &str) -> [f64; 4] {
|
||||
self.slot(id).map(|s| [s[0], s[1], s[2], s[3]]).unwrap_or([1.0; 4])
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect plug-in.
|
||||
pub trait EffectPlugin: Send + Sync {
|
||||
fn manifest(&self) -> &PluginManifest;
|
||||
/// Process `frame` in place. `time` is layer time in seconds. An error leaves the frame as
|
||||
/// it was (the error is logged once).
|
||||
fn render(&self, frame: &mut PluginFrame, params: &PluginParams, time: f64) -> Result<(), String>;
|
||||
/// Where the plug-in came from (a file path, `built-in`…), for listings.
|
||||
fn source(&self) -> String {
|
||||
"built-in".into()
|
||||
}
|
||||
}
|
||||
|
||||
static SLOTS: [OnceLock<Arc<dyn EffectPlugin>>; MAX_PLUGINS] = [const { OnceLock::new() }; MAX_PLUGINS];
|
||||
|
||||
/// Registered plug-in effects, in registration order.
|
||||
fn plugin_specs() -> &'static RwLock<Vec<&'static EffectSpec>> {
|
||||
static P: OnceLock<RwLock<Vec<&'static EffectSpec>>> = OnceLock::new();
|
||||
P.get_or_init(|| RwLock::new(vec![]))
|
||||
}
|
||||
|
||||
/// The registered plug-in effects.
|
||||
pub fn plugins() -> Vec<&'static EffectSpec> {
|
||||
plugin_specs().read().map(|v| v.clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The plug-in behind a registered effect id.
|
||||
pub fn plugin(id: &str) -> Option<Arc<dyn EffectPlugin>> {
|
||||
SLOTS.iter().filter_map(|s| s.get()).find(|p| p.manifest().id == id).cloned()
|
||||
}
|
||||
|
||||
fn leak(s: &str) -> &'static str {
|
||||
Box::leak(s.to_string().into_boxed_str())
|
||||
}
|
||||
|
||||
fn param_spec(p: &PluginParam) -> ParamSpec {
|
||||
let (default, ui) = match &p.kind {
|
||||
PluginParamKind::Slider { default, min, max, slider_min, slider_max, decimals } => (
|
||||
Value::Scalar(*default),
|
||||
ParamUi::Slider { min: *min, max: *max, slider_min: slider_min.unwrap_or(*min), slider_max: slider_max.unwrap_or(*max), decimals: *decimals },
|
||||
),
|
||||
PluginParamKind::Angle { default } => (Value::Scalar(*default), ParamUi::Angle),
|
||||
PluginParamKind::Checkbox { default } => (Value::Bool(*default), ParamUi::Checkbox),
|
||||
PluginParamKind::Popup { options, default } => (Value::Enum(*default), ParamUi::Popup { options: options.clone() }),
|
||||
PluginParamKind::Point { default } => (Value::Vec2(*default), ParamUi::Point),
|
||||
PluginParamKind::Color { default } => (Value::Color(*default), ParamUi::Color),
|
||||
};
|
||||
ParamSpec { id: leak(&p.id), name: leak(&p.name), default, ui }
|
||||
}
|
||||
|
||||
/// Register a plug-in effect: it appears in Effects & Presets under its category and is
|
||||
/// applied by id like a built-in. Fails for a bad manifest, a taken id or when
|
||||
/// [`MAX_PLUGINS`] are registered.
|
||||
pub fn register_plugin(plugin: Arc<dyn EffectPlugin>) -> Result<&'static EffectSpec, String> {
|
||||
let m = plugin.manifest().clone();
|
||||
m.validate()?;
|
||||
let mut specs = plugin_specs().write().map_err(|_| "plug-in registry poisoned".to_string())?;
|
||||
if crate::registry().iter().any(|s| s.id == m.id) || specs.iter().any(|s| s.id == m.id) {
|
||||
return Err(format!("an effect with id `{}` is already registered", m.id));
|
||||
}
|
||||
let slot = SLOTS.iter().position(|s| s.get().is_none()).ok_or_else(|| format!("too many plug-ins (at most {MAX_PLUGINS})"))?;
|
||||
SLOTS[slot].set(plugin).map_err(|_| "plug-in slot taken".to_string())?;
|
||||
let spec: &'static EffectSpec = Box::leak(Box::new(EffectSpec {
|
||||
id: leak(&m.id),
|
||||
name: leak(&m.name),
|
||||
category: leak(&m.category),
|
||||
params: m.params.iter().map(param_spec).collect(),
|
||||
render: TRAMPOLINES[slot],
|
||||
gpu: false,
|
||||
float: true,
|
||||
}));
|
||||
specs.push(spec);
|
||||
Ok(spec)
|
||||
}
|
||||
|
||||
/// Each slot needs its own `fn` (effect render functions are plain function pointers).
|
||||
fn trampoline<const I: usize>(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
run_slot(I, ctx, buf)
|
||||
}
|
||||
|
||||
macro_rules! trampolines {
|
||||
($($i:literal)*) => { [$(trampoline::<$i> as RenderFn),*] };
|
||||
}
|
||||
|
||||
const TRAMPOLINES: [RenderFn; MAX_PLUGINS] = trampolines!(
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
||||
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
||||
);
|
||||
|
||||
/// Flatten an instance's evaluated parameters for the plug-in (points mapped to frame pixels).
|
||||
pub fn flatten(m: &PluginManifest, ctx: &EffectCtx, buf: &Buf) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(m.flat_len());
|
||||
for p in &m.params {
|
||||
let v = ctx.params.get(&p.id);
|
||||
match &p.kind {
|
||||
PluginParamKind::Point { .. } => {
|
||||
let q = v.map(Value::as_vec2).unwrap_or([0.0; 2]);
|
||||
let (x, y) = buf.to_px(q);
|
||||
out.extend([x, y]);
|
||||
}
|
||||
PluginParamKind::Color { .. } => {
|
||||
let c = v.map(Value::as_color).unwrap_or([1.0; 4]);
|
||||
out.extend(c.iter().map(|x| *x as f64));
|
||||
}
|
||||
PluginParamKind::Checkbox { .. } => out.push(if v.map(Value::as_bool).unwrap_or(false) { 1.0 } else { 0.0 }),
|
||||
PluginParamKind::Popup { .. } => out.push(v.map(Value::as_enum).unwrap_or(0) as f64),
|
||||
_ => out.push(v.map(Value::as_f64).unwrap_or(0.0)),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn run_slot(slot: usize, ctx: &EffectCtx, mut buf: Buf) -> Buf {
|
||||
let Some(plugin) = SLOTS[slot].get() else { return buf };
|
||||
let m = plugin.manifest();
|
||||
let flat = flatten(m, ctx, &buf);
|
||||
let params = PluginParams { manifest: m, flat: &flat };
|
||||
let (width, height) = (buf.img.width, buf.img.height);
|
||||
let before = buf.img.data.clone();
|
||||
let mut frame = PluginFrame { width, height, pixels: &mut buf.img.data, scale: buf.scale };
|
||||
if let Err(e) = plugin.render(&mut frame, ¶ms, ctx.time) {
|
||||
log::warn!("plug-in `{}`: {e}", m.id);
|
||||
buf.img.data = before;
|
||||
}
|
||||
buf
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
//! Pluggable particle simulation (GPU particles, M12.7).
|
||||
//!
|
||||
//! The stepped particle systems (CC Particle World, CC Particle Systems II and Particle
|
||||
//! Playground's Cannon without interacting forces) evolve every particle independently: births
|
||||
//! come from a rate (the same `carry` arithmetic as the CPU step), and each particle integrates
|
||||
//! its own motion with the same fixed step. An accelerator ([`ParticleSim`], reached through
|
||||
//! [`crate::EffectHost::particles`]) can therefore simulate all of them in parallel and return
|
||||
//! the state the CPU's `SimCache` would reach. The CPU stays the oracle: anything the backend
|
||||
//! declines (interacting forces, caps that would drop births) simulates on the CPU.
|
||||
|
||||
/// CC Particle World / CC Particle Systems II physics (see `sim::Phys`), with the per-step and
|
||||
/// per-spawn constants already evaluated on the CPU (bit-identical to the CPU's).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EngineDesc {
|
||||
pub life: f32,
|
||||
pub producer: [f32; 3],
|
||||
pub radius: [f32; 3],
|
||||
/// Animation (0 Explosive … 9 Fractal Uni).
|
||||
pub anim: u32,
|
||||
pub speed: f32,
|
||||
pub gravity: [f32; 3],
|
||||
/// Normalised direction axis.
|
||||
pub axis: [f32; 3],
|
||||
pub extra: f32,
|
||||
/// Cone Axis spread factor `|tan(extra angle / 2)|` (≤ 20).
|
||||
pub cone: f32,
|
||||
/// Velocity damping per step `exp(−drag · dt)`.
|
||||
pub damp: f32,
|
||||
pub seed: u32,
|
||||
/// 2D systems keep z = 0.
|
||||
pub flat: bool,
|
||||
}
|
||||
|
||||
/// Particle Playground's Cannon with gravity only (see `sim3::Pg`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct CannonDesc {
|
||||
pub pos: [f32; 2],
|
||||
pub barrel_angle: f32,
|
||||
pub barrel_radius: f32,
|
||||
pub dir_spread: f32,
|
||||
pub vel: f32,
|
||||
pub vel_spread: f32,
|
||||
pub gravity: [f32; 2],
|
||||
pub grav_spread: f32,
|
||||
pub seed: u32,
|
||||
/// Particles leaving `[x0, y0, x1, y1]` are removed.
|
||||
pub bounds: [f32; 4],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ParticleSystem {
|
||||
Engine(EngineDesc),
|
||||
Cannon(CannonDesc),
|
||||
}
|
||||
|
||||
/// One simulation request: the state after `steps` steps of system `key`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SimRequest<'a> {
|
||||
/// Identifies the system (parameters, seed); checkpoints are reused per key.
|
||||
pub key: u64,
|
||||
pub steps: u64,
|
||||
/// Birth step of every particle id born before `steps` (ascending).
|
||||
pub births: &'a [u32],
|
||||
pub system: ParticleSystem,
|
||||
}
|
||||
|
||||
/// A live particle (ascending ids, as the CPU state keeps them).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SimParticle {
|
||||
pub p: [f32; 3],
|
||||
pub v: [f32; 3],
|
||||
pub age: f32,
|
||||
pub life: f32,
|
||||
pub rnd: f32,
|
||||
pub id: u32,
|
||||
}
|
||||
|
||||
/// A particle simulation backend (the GPU).
|
||||
pub trait ParticleSim: Send + Sync {
|
||||
/// The live particles after `req.steps` steps, or `None` (simulate on the CPU).
|
||||
fn simulate(&self, req: &SimRequest) -> Option<Vec<SimParticle>>;
|
||||
}
|
||||
|
||||
/// Birth step of every particle born in the first `steps` steps at `rate` particles per second
|
||||
/// (the CPU step's `carry` arithmetic, exactly). `None` when more than `cap` would be born (the
|
||||
/// CPU drops births at its live-particle cap, which an independent simulation can't know).
|
||||
pub fn births(rate: f64, steps: u64, cap: usize) -> Option<Vec<u32>> {
|
||||
let per = rate / SPS;
|
||||
if per * steps as f64 > cap as f64 + 2.0 {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut carry = 0.0f64;
|
||||
for i in 0..steps {
|
||||
carry += per;
|
||||
let n = carry.floor() as u32;
|
||||
carry -= n as f64;
|
||||
for _ in 0..n {
|
||||
out.push(i as u32);
|
||||
}
|
||||
}
|
||||
(out.len() <= cap).then_some(out)
|
||||
}
|
||||
|
||||
/// Steps per second of the stepped simulations.
|
||||
pub const SPS: f64 = crate::sim::SPS;
|
||||
@@ -818,6 +818,60 @@ impl Phys {
|
||||
}
|
||||
}
|
||||
|
||||
impl Phys {
|
||||
/// The backend description (per-step and per-spawn constants evaluated here, in f32).
|
||||
pub(crate) fn desc(&self) -> crate::psim::EngineDesc {
|
||||
let mut drag = self.resistance;
|
||||
if self.anim == 3 {
|
||||
drag += 3.0 * self.extra.max(0.1);
|
||||
}
|
||||
let dt = (1.0 / SPS) as f32;
|
||||
crate::psim::EngineDesc {
|
||||
life: self.life,
|
||||
producer: self.producer,
|
||||
radius: self.radius,
|
||||
anim: self.anim,
|
||||
speed: self.speed,
|
||||
gravity: self.gravity,
|
||||
axis: norm3(self.axis),
|
||||
extra: self.extra,
|
||||
cone: (self.extra_angle.to_radians() * 0.5).tan().abs().min(20.0),
|
||||
damp: (-drag * dt).exp(),
|
||||
seed: self.seed,
|
||||
flat: self.flat,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The state at layer time `ctx.time` from the host's particle backend (GPU particles), or
|
||||
/// `None` (simulate on the CPU).
|
||||
fn accelerated(ctx: &EffectCtx, key: u64, phys: &Phys) -> Option<std::sync::Arc<PState>> {
|
||||
let backend = ctx.env.host?.particles()?;
|
||||
let steps = steps_at(ctx.time);
|
||||
let births = crate::psim::births(phys.rate, steps, phys.max)?;
|
||||
let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Engine(phys.desc()) };
|
||||
let parts = backend.simulate(&req)?;
|
||||
Some(std::sync::Arc::new(PState {
|
||||
parts: parts.into_iter().map(|q| Particle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect(),
|
||||
carry: 0.0,
|
||||
next_id: births.len() as u32,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The live particles of a stepped particle effect (`ec.sim.ccparticleworld`,
|
||||
/// `ec.sim.ccparticlesystems2`) at `ctx.time`: from the host's particle backend when it has
|
||||
/// one (GPU particles), else from the CPU simulation. For comparing the two.
|
||||
pub fn particle_state(id: &str, ctx: &EffectCtx) -> Option<Vec<crate::psim::SimParticle>> {
|
||||
let (phys, cache, salt) = match id {
|
||||
"ec.sim.ccparticleworld" => (pw_phys(ctx), &PW_CACHE, 1),
|
||||
"ec.sim.ccparticlesystems2" => (ps2_phys(ctx), &PS2_CACHE, 2),
|
||||
_ => return None,
|
||||
};
|
||||
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, salt);
|
||||
let st = accelerated(ctx, key, &phys).unwrap_or_else(|| simulate(cache, key, ctx.time, &phys));
|
||||
Some(st.parts.iter().map(|q| crate::psim::SimParticle { p: q.p, v: q.v, age: q.age, life: q.life, rnd: q.rnd, id: q.id }).collect())
|
||||
}
|
||||
|
||||
/// Run a particle system to layer time `t` through `cache`.
|
||||
pub(crate) fn simulate(cache: &SimCache<PState>, key: u64, t: f64, phys: &Phys) -> std::sync::Arc<PState> {
|
||||
cache.run(key, steps_at(t), PState::default, |st, i| phys.step(st, i))
|
||||
@@ -859,10 +913,10 @@ fn type_sprite(kind: u32, x: f32, y: f32, r: f32, c: [f32; 4], vx: f32, vy: f32,
|
||||
|
||||
static PW_CACHE: SimCache<PState> = SimCache::new(6);
|
||||
|
||||
fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
/// CC Particle World's physics.
|
||||
fn pw_phys(ctx: &EffectCtx) -> Phys {
|
||||
let pr = ctx.params;
|
||||
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
|
||||
let phys = Phys {
|
||||
Phys {
|
||||
rate: pr.f("birthRate").max(0.0) * 120.0,
|
||||
life: pr.f("longevity").max(0.0) as f32,
|
||||
producer: [pr.f("producer/producerX") as f32, pr.f("producer/producerY") as f32, pr.f("producer/producerZ") as f32],
|
||||
@@ -882,11 +936,18 @@ fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
seed: (pr.f("extras/randomSeed") as u32).wrapping_mul(0x9e3779b9) ^ ctx.seed,
|
||||
max: 40_000,
|
||||
flat: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
|
||||
let phys = pw_phys(ctx);
|
||||
if phys.rate <= 0.0 && ctx.time <= 0.0 {
|
||||
return b;
|
||||
}
|
||||
let st = simulate(&PW_CACHE, params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1), ctx.time, &phys);
|
||||
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 1);
|
||||
let st = accelerated(ctx, key, &phys).unwrap_or_else(|| simulate(&PW_CACHE, key, ctx.time, &phys));
|
||||
let kind = pr.e("particle/particleType");
|
||||
let birth = pr.color("particle/birthColor");
|
||||
let death = pr.color("particle/deathColor");
|
||||
@@ -936,13 +997,14 @@ fn particle_world(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
|
||||
static PS2_CACHE: SimCache<PState> = SimCache::new(6);
|
||||
|
||||
fn particle_systems2(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
/// CC Particle Systems II's physics.
|
||||
fn ps2_phys(ctx: &EffectCtx) -> Phys {
|
||||
let pr = ctx.params;
|
||||
let lh = ctx.layer_size[1] as f32;
|
||||
let unit = lh.max(1.0);
|
||||
let pos = pr.v2("producer/position");
|
||||
let dir = (pr.f("physics/direction") as f32).to_radians();
|
||||
let phys = Phys {
|
||||
Phys {
|
||||
rate: pr.f("birthRate").max(0.0) * 60.0,
|
||||
life: pr.f("longevity").max(0.0) as f32,
|
||||
producer: [pos[0] as f32 / unit, pos[1] as f32 / unit, 0.0],
|
||||
@@ -958,8 +1020,16 @@ fn particle_systems2(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
seed: (pr.f("randomSeed") as u32).wrapping_mul(0x85ebca6b) ^ ctx.seed,
|
||||
max: 40_000,
|
||||
flat: true,
|
||||
};
|
||||
let st = simulate(&PS2_CACHE, params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 2), ctx.time, &phys);
|
||||
}
|
||||
}
|
||||
|
||||
fn particle_systems2(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let lh = ctx.layer_size[1] as f32;
|
||||
let unit = lh.max(1.0);
|
||||
let phys = ps2_phys(ctx);
|
||||
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 2);
|
||||
let st = accelerated(ctx, key, &phys).unwrap_or_else(|| simulate(&PS2_CACHE, key, ctx.time, &phys));
|
||||
let kind = pr.e("particle/particleType");
|
||||
let birth = pr.color("particle/birthColor");
|
||||
let death = pr.color("particle/deathColor");
|
||||
|
||||
@@ -603,7 +603,8 @@ fn blit_layer(out: &mut Image, lp: &crate::LayerPixels, x: f64, y: f64, angle: f
|
||||
}
|
||||
}
|
||||
|
||||
fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
/// Particle Playground's producers and forces.
|
||||
fn pg_of(ctx: &EffectCtx) -> Pg {
|
||||
let pr = ctx.params;
|
||||
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
|
||||
let grav_dir = (pr.f("gravity/gravityDirection") as f32).to_radians();
|
||||
@@ -611,7 +612,7 @@ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let wall = (pr.f("wall/wallBoundary").round() as usize).checked_sub(1).and_then(|i| ctx.env.masks.get(i)).map(|m| m.points.clone());
|
||||
let persistent = if pr.b("mapperEnabled") { mapper_from(ctx, "persistentPropertyMapper", false) } else { None };
|
||||
let ephemeral = mapper_from(ctx, "ephemeralPropertyMapper", true);
|
||||
let pg = Pg {
|
||||
Pg {
|
||||
cannon: pr.b("cannonEnabled"),
|
||||
pos: { pr.v2("cannon/cannonPosition").map(|v| v as f32) },
|
||||
barrel_angle: pr.f("cannon/barrelAngle") as f32,
|
||||
@@ -638,7 +639,87 @@ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
ephemeral,
|
||||
seed: (pr.f("randomSeed") as u32).wrapping_mul(0x9e37_79b9) ^ ctx.seed,
|
||||
bounds: [-lw * 2.0, -lh * 2.0, lw * 3.0, lh * 3.0],
|
||||
}
|
||||
}
|
||||
|
||||
impl Pg {
|
||||
/// Only a cannon with gravity: every particle moves on its own (what the host's particle
|
||||
/// backend can simulate).
|
||||
fn cannon_only(&self) -> bool {
|
||||
self.cannon
|
||||
&& !(self.repel != 0.0 && self.repel_radius > 0.0)
|
||||
&& self.wall.is_none()
|
||||
&& self.persistent.is_none()
|
||||
&& self.ephemeral.is_none()
|
||||
&& self.pex_radius <= 0.0
|
||||
&& self.grav_affects.is_all()
|
||||
}
|
||||
}
|
||||
|
||||
impl Affects {
|
||||
/// Affects everything (the defaults).
|
||||
fn is_all(&self) -> bool {
|
||||
self.from == 0 && self.selection.is_none() && self.chars.is_empty() && self.age == 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Particle Playground cannons with gravity only, simulated by the host's particle backend.
|
||||
fn pg_accelerated(ctx: &EffectCtx, key: u64, pg: &Pg) -> Option<std::sync::Arc<PgState>> {
|
||||
let backend = ctx.env.host?.particles()?;
|
||||
let steps = steps_at(ctx.time);
|
||||
let births = crate::psim::births(pg.rate, steps, 60_000)?;
|
||||
let desc = crate::psim::CannonDesc {
|
||||
pos: pg.pos,
|
||||
barrel_angle: pg.barrel_angle,
|
||||
barrel_radius: pg.barrel_radius,
|
||||
dir_spread: pg.dir_spread,
|
||||
vel: pg.vel,
|
||||
vel_spread: pg.vel_spread,
|
||||
gravity: pg.gravity,
|
||||
grav_spread: pg.grav_spread,
|
||||
seed: pg.seed,
|
||||
bounds: pg.bounds,
|
||||
};
|
||||
let req = crate::psim::SimRequest { key, steps, births: &births, system: crate::psim::ParticleSystem::Cannon(desc) };
|
||||
let parts = backend.simulate(&req)?;
|
||||
Some(std::sync::Arc::new(PgState {
|
||||
parts: parts
|
||||
.into_iter()
|
||||
.map(|q| {
|
||||
let born = pg.spawn(q.id);
|
||||
PgParticle { p: [q.p[0], q.p[1]], v: [q.v[0], q.v[1]], ..born }
|
||||
})
|
||||
.collect(),
|
||||
carry: 0.0,
|
||||
next_id: births.len() as u32,
|
||||
}))
|
||||
}
|
||||
|
||||
/// The live particles of a Particle Playground whose cannon is the only producer and force
|
||||
/// besides gravity, at `ctx.time`: from the host's particle backend when it has one (GPU
|
||||
/// particles), else from the CPU simulation (`None` for other set-ups). For comparing the two.
|
||||
pub fn playground_state(ctx: &EffectCtx) -> Option<Vec<crate::psim::SimParticle>> {
|
||||
let pg = pg_of(ctx);
|
||||
let pr = ctx.params;
|
||||
let grid = pr.b("gridEnabled") && pr.f("grid/particlesAcross").round() > 0.0 && pr.f("grid/particlesDown").round() > 0.0;
|
||||
let exploder = pr.b("exploderEnabled") && pr.get("layerExploder/explodeLayer").and_then(Value::as_layer).is_some();
|
||||
if !pg.cannon_only() || grid || exploder {
|
||||
return None;
|
||||
}
|
||||
let key = params_key(ctx, &Buf { img: Image::new(0, 0), offset: [0.0; 2], scale: 1.0 }, 0x7067);
|
||||
let st = pg_accelerated(ctx, key, &pg).unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), PgState::default, |st, _| pg.step(st)));
|
||||
Some(
|
||||
st.parts
|
||||
.iter()
|
||||
.map(|q| crate::psim::SimParticle { p: [q.p[0], q.p[1], 0.0], v: [q.v[0], q.v[1], 0.0], age: 0.0, life: 0.0, rnd: 0.0, id: q.id })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
let pr = ctx.params;
|
||||
let (lw, lh) = (ctx.layer_size[0] as f32, ctx.layer_size[1] as f32);
|
||||
let pg = pg_of(ctx);
|
||||
// Initial particles: Grid and Layer Exploder.
|
||||
let grid_on = pr.b("gridEnabled");
|
||||
let across = pr.f("grid/particlesAcross").max(0.0).round() as u32;
|
||||
@@ -730,7 +811,10 @@ fn particle_playground(ctx: &EffectCtx, mut b: Buf) -> Buf {
|
||||
}
|
||||
st
|
||||
};
|
||||
let st = PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st));
|
||||
// A cannon with gravity only: every particle moves on its own (GPU particles).
|
||||
let independent = pg.cannon_only() && !(grid_on && across > 0 && down > 0) && exploder.is_none();
|
||||
let gpu = if independent { pg_accelerated(ctx, key, &pg) } else { None };
|
||||
let st = gpu.unwrap_or_else(|| PG_CACHE.run(key, steps_at(ctx.time), init, |st, _| pg.step(st)));
|
||||
// Render: what the ephemeral mapper changes shows for this frame only.
|
||||
let parts: Vec<PgParticle> = st.parts.iter().map(|q| pg.ephemeral(q)).collect();
|
||||
let auto_orient = pr.b("options/autoOrientRotation");
|
||||
|
||||
@@ -31,7 +31,7 @@ fn scale_px(px: &mut Px, k: f32) {
|
||||
/// Resample `other` into `b`'s pixel grid with placement `mode` (Gradient Wipe's Gradient
|
||||
/// Placement, Texturize's Texture Placement): 0 tile from the top-left, 1 centre once,
|
||||
/// 2 stretch to fit.
|
||||
pub(crate) fn place_layer(ctx: &EffectCtx, b: &Buf, other: &crate::LayerPixels, mode: u32) -> effectcraft_raster::Image {
|
||||
pub fn place_layer(ctx: &EffectCtx, b: &Buf, other: &crate::LayerPixels, mode: u32) -> effectcraft_raster::Image {
|
||||
let (ls, os) = (ctx.layer_size, other.size);
|
||||
let inv = 1.0 / b.scale.max(1e-9);
|
||||
crate::util::gen_image(b.img.width, b.img.height, |x, y| {
|
||||
|
||||
@@ -17,8 +17,11 @@
|
||||
//! Edge Cropping ignores bad edge pixels of the input frames;
|
||||
//! - **Show Track Points** draws the analysed background features.
|
||||
//!
|
||||
//! *Subspace Warp* is approximated by a per-frame perspective warp (no content-preserving
|
||||
//! mesh warp yet), and *Rolling Shutter Ripple* is stored but has no effect.
|
||||
//! *Subspace Warp* warps each frame with a content-preserving mesh fitted to the analysis'
|
||||
//! subspace-smoothed feature trajectories ([`effectcraft_track::subspace`]); analyses made
|
||||
//! before trajectories were stored fall back to a perspective warp. *Rolling Shutter Ripple*
|
||||
//! picks the mesh: Automatic Reduction (12 × 8, stiffer) or Enhanced Reduction (twice the rows,
|
||||
//! softer), which follows the row-wise wobble of rolling-shutter shake more closely.
|
||||
//!
|
||||
//! Without an analysis (or with one made for another layer size) the input passes through.
|
||||
|
||||
@@ -30,7 +33,7 @@ use effectcraft_keyframe::Value;
|
||||
use effectcraft_project::ParamUi;
|
||||
use effectcraft_raster::{Image, Px};
|
||||
use effectcraft_track::Homography;
|
||||
use effectcraft_track::stabilize::{Framing, Method, Plan, StabResult, StabSettings, WarpAnalysis, plan};
|
||||
use effectcraft_track::stabilize::{Framing, Method, Plan, Ripple, StabResult, StabSettings, WarpAnalysis, plan};
|
||||
use rayon::prelude::*;
|
||||
|
||||
use crate::{Buf, EffectCtx, EffectSpec, Params, num, p, popup, slider};
|
||||
@@ -145,6 +148,7 @@ pub fn settings(params: &Params, fps: f64) -> StabSettings {
|
||||
// AE's 0…100 slider (50 = balanced) onto the planner's −100…100.
|
||||
crop_less_smooth_more: (f(params, "advanced/cropLessSmoothMore") - 50.0) * 2.0,
|
||||
fps,
|
||||
ripple: if e(params, "advanced/rollingShutterRipple") == 1 { Ripple::Enhanced } else { Ripple::Automatic },
|
||||
}
|
||||
}
|
||||
|
||||
@@ -175,7 +179,7 @@ fn settings_key(s: &StabSettings) -> u64 {
|
||||
for v in [s.smoothness, s.max_scale, s.action_safe, s.additional_scale, s.crop_less_smooth_more, s.fps] {
|
||||
h.write_u64(v.to_bits());
|
||||
}
|
||||
h.write(format!("{:?}{:?}{:?}{:?}", s.result, s.method, s.preserve_scale, s.framing).as_bytes());
|
||||
h.write(format!("{:?}{:?}{:?}{:?}{:?}", s.result, s.method, s.preserve_scale, s.framing, s.ripple).as_bytes());
|
||||
h.finish()
|
||||
}
|
||||
|
||||
@@ -275,6 +279,13 @@ fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
}
|
||||
let sc = if buf.scale > 0.0 { buf.scale } else { 1.0 };
|
||||
let Some(inv) = pl.warps[k].inverse() else { return buf };
|
||||
// Output point → source point of this frame (a mesh lookup for Subspace Warp).
|
||||
let mesh = pl.meshes.get(k);
|
||||
let finv = pl.framing.inverse().unwrap_or(Homography::IDENTITY);
|
||||
let src_of = |p: [f64; 2]| match mesh {
|
||||
Some(m) => m.sample(finv.apply(p)),
|
||||
None => inv.apply(p),
|
||||
};
|
||||
let (ow, oh) = (((size[0] * sc).ceil() as u32).max(1), ((size[1] * sc).ceil() as u32).max(1));
|
||||
let synth = matches!(settings(ctx.params, 30.0).framing, Framing::SynthesizeEdges);
|
||||
let crop = [
|
||||
@@ -306,7 +317,7 @@ fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let q = inv.apply(p);
|
||||
let q = src_of(p);
|
||||
if !synth {
|
||||
*px = sample(src, q);
|
||||
continue;
|
||||
@@ -337,12 +348,12 @@ fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
});
|
||||
let need = need_m.into_inner().unwrap_or_else(|e| e.into_inner());
|
||||
if synth && need.iter().any(|w| *w > 0.0) {
|
||||
synthesize(ctx, &a, k, &inv, &crop, sc, &mut out, &need);
|
||||
synthesize(ctx, &a, k, &src_of, &crop, sc, &mut out, &need);
|
||||
}
|
||||
if b(ctx.params, "advanced/showTrackPoints") {
|
||||
let r = (2.5 * f(ctx.params, "advanced/trackPointSize") / 100.0 * sc).max(0.5);
|
||||
for q in &a.frames[k].points {
|
||||
let o = pl.warps[k].apply([q[0] as f64, q[1] as f64]);
|
||||
let Some(o) = pl.output_of(k, [q[0] as f64, q[1] as f64]) else { continue };
|
||||
dot(&mut out, [o[0] * sc, o[1] * sc], r, [0.25, 0.75, 1.0, 1.0]);
|
||||
}
|
||||
}
|
||||
@@ -352,7 +363,16 @@ fn render(ctx: &EffectCtx, buf: Buf) -> Buf {
|
||||
/// Fill the pixels flagged in `need` (weight = how much synthesized content they take) from
|
||||
/// neighbouring frames, nearest first.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn synthesize(ctx: &EffectCtx, a: &WarpAnalysis, k: usize, inv: &Homography, crop: &[f64; 4], sc: f64, out: &mut Image, need: &[f32]) {
|
||||
fn synthesize(
|
||||
ctx: &EffectCtx,
|
||||
a: &WarpAnalysis,
|
||||
k: usize,
|
||||
src_of: &(dyn Fn([f64; 2]) -> [f64; 2] + Sync),
|
||||
crop: &[f64; 4],
|
||||
sc: f64,
|
||||
out: &mut Image,
|
||||
need: &[f32],
|
||||
) {
|
||||
let Some(host) = ctx.env.host else { return };
|
||||
let n = a.frames.len();
|
||||
let range = ((f(ctx.params, "advanced/synthesizeInputRange").max(0.0) / a.frame_duration.max(1e-6)).round() as usize).min(60);
|
||||
@@ -376,7 +396,7 @@ fn synthesize(ctx: &EffectCtx, a: &WarpAnalysis, k: usize, inv: &Homography, cro
|
||||
.filter(|i| !filled[**i])
|
||||
.filter_map(|i| {
|
||||
let (x, y) = (i % ow, i / ow);
|
||||
let q = inv.apply([(x as f64 + 0.5) / sc, (y as f64 + 0.5) / sc]);
|
||||
let q = src_of([(x as f64 + 0.5) / sc, (y as f64 + 0.5) / sc]);
|
||||
let qj = m.apply(q);
|
||||
inside(crop, qj).then(|| (*i, nb.img.sample_bilinear_clamped(qj[0] * nb.scale + nb.offset[0], qj[1] * nb.scale + nb.offset[1])))
|
||||
})
|
||||
@@ -412,7 +432,7 @@ mod tests {
|
||||
use effectcraft_track::stabilize::FrameMotion;
|
||||
|
||||
fn analysis_json(n: usize, w: f64, h: f64, shift: impl Fn(usize) -> [f64; 2]) -> String {
|
||||
let mut a = WarpAnalysis { version: 1, start: 0.0, frame_duration: 1.0 / 25.0, size: [w, h], detailed: false, frames: vec![] };
|
||||
let mut a = WarpAnalysis { version: 1, start: 0.0, frame_duration: 1.0 / 25.0, size: [w, h], detailed: false, frames: vec![], tracks: vec![] };
|
||||
for k in 0..n {
|
||||
let mut fm = FrameMotion::default();
|
||||
if k > 0 {
|
||||
|
||||
Reference in New Issue
Block a user