M0.1–M0.7: workspace, time/geom/color/keyframe/project/raster/path/text/effects/render crates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-01 14:05:20 -04:00
co-authored by Claude Opus 5.5
parent 9f19158a59
commit 808cd490cd
76 changed files with 12319 additions and 3 deletions
+464
View File
@@ -0,0 +1,464 @@
//! Builders for the standard property groups and layers.
use effectcraft_color::{BlendMode, Label};
use effectcraft_keyframe::{Gradient, ShapePath, TextDoc, Value};
use effectcraft_time::Tick;
use crate::props::{GroupKind, MaskMode, ParamUi, PropGroup, Property};
use crate::{Comp, Layer, LayerId, LayerSource, LightKind, Project, Switches};
/// Id allocator borrowing the project's counter.
pub struct Ids<'a>(pub &'a mut u64);
impl Ids<'_> {
pub fn alloc(&mut self) -> u64 {
let v = *self.0;
*self.0 += 1;
v
}
pub fn prop(&mut self, m: &str, name: &str, v: Value) -> Property {
Property::new(self.alloc(), m, name, v)
}
pub fn group(&mut self, m: &str, name: &str) -> PropGroup {
PropGroup::new(self.alloc(), m, name)
}
}
fn slider(min: f64, max: f64, smin: f64, smax: f64, decimals: u8) -> ParamUi {
ParamUi::Slider { min, max, slider_min: smin, slider_max: smax, decimals }
}
fn popup(opts: &[&str]) -> ParamUi {
ParamUi::Popup { options: opts.iter().map(|s| s.to_string()).collect() }
}
/// Layer Transform group. Values are always 3D; 2D layers show two dimensions.
pub fn transform(ids: &mut Ids, anchor: [f64; 2], position: [f64; 2]) -> PropGroup {
let mut a = ids.prop("anchor", "Anchor Point", Value::Vec3([anchor[0], anchor[1], 0.0])).with_ui(ParamUi::Point).spatial();
a.shown_dims = 2;
let mut p = ids.prop("position", "Position", Value::Vec3([position[0], position[1], 0.0])).with_ui(ParamUi::Point).spatial();
p.shown_dims = 2;
let mut s = ids.prop("scale", "Scale", Value::Vec3([100.0, 100.0, 100.0])).with_ui(ParamUi::Percent);
s.shown_dims = 2;
let mut o = ids.prop("orientation", "Orientation", Value::Vec3([0.0; 3])).with_ui(ParamUi::Angle);
o.three_d_only = true;
let mut rx = ids.prop("rotationX", "X Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle);
rx.three_d_only = true;
let mut ry = ids.prop("rotationY", "Y Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle);
ry.three_d_only = true;
let rz = ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle);
let op = ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0));
ids.group("transform", "Transform").with(a).with(p).with(s).with(o).with(rx).with(ry).with(rz).with(op)
}
pub fn masks(ids: &mut Ids) -> PropGroup {
ids.group("masks", "Masks")
}
pub fn effects(ids: &mut Ids) -> PropGroup {
ids.group("effects", "Effects")
}
/// Mask colours cycle like AE's default mask colours.
pub const MASK_COLORS: [[u8; 3]; 8] =
[[0xb1, 0xb4, 0x4f], [0x4f, 0x8c, 0xc9], [0xc9, 0x4f, 0x8c], [0x4f, 0xc9, 0x7a], [0xc9, 0x8c, 0x4f], [0x8c, 0x4f, 0xc9], [0x4f, 0xc9, 0xc9], [0xc9, 0x4f, 0x4f]];
pub fn mask(ids: &mut Ids, name: &str, path: ShapePath, mode: MaskMode, color: [u8; 3]) -> PropGroup {
let mut g = ids.group("mask", name);
g.kind = GroupKind::Mask { mode, inverted: false, color, locked: false };
g.with(ids.prop("path", "Mask Path", Value::Path(path)).with_ui(ParamUi::Path))
.with(ids.prop("feather", "Mask Feather", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Pixels))
.with(ids.prop("opacity", "Mask Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)))
.with(ids.prop("expansion", "Mask Expansion", Value::Scalar(0.0)).with_ui(ParamUi::Pixels))
}
pub fn text(ids: &mut Ids, doc: TextDoc) -> PropGroup {
let mut st = ids.prop("sourceText", "Source Text", Value::Text(Box::new(doc))).with_ui(ParamUi::Text);
st.hold_only = true;
let path_opts = ids.group("pathOptions", "Path Options").with(ids.prop("path", "Path", Value::Enum(0)).with_ui(popup(&["None"])));
let more = ids
.group("moreOptions", "More Options")
.with(ids.prop("anchorGrouping", "Anchor Point Grouping", Value::Enum(0)).with_ui(popup(&["Character", "Word", "Line", "All"])))
.with(ids.prop("groupingAlignment", "Grouping Alignment", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Percent))
.with(ids.prop("fillStroke", "Fill & Stroke", Value::Enum(0)).with_ui(popup(&["Per Character Palette", "All Fills Over All Strokes", "All Strokes Over All Fills"])))
.with(ids.prop("interCharBlend", "Inter-Character Blending", Value::Enum(0)).with_ui(popup(&["Normal", "Multiply", "Screen", "Overlay"])));
ids.group("text", "Text").with(st).with(path_opts).with(more).with(ids.group("animators", "Animators"))
}
/// A text animator with one range selector and the given properties.
pub fn text_animator(ids: &mut Ids, name: &str, props: Vec<Property>) -> PropGroup {
let mut g = ids.group("animator", name);
g.kind = GroupKind::Indexed;
let mut sels = ids.group("selectors", "Selectors");
sels.children.push(range_selector(ids, "Range Selector 1").into());
let mut pg = ids.group("properties", "Properties");
for p in props {
pg.children.push(p.into());
}
g.with(sels).with(pg)
}
pub fn range_selector(ids: &mut Ids, name: &str) -> PropGroup {
let mut g = ids.group("rangeSelector", name);
g.kind = GroupKind::Indexed;
let adv = ids
.group("advanced", "Advanced")
.with(ids.prop("units", "Units", Value::Enum(0)).with_ui(popup(&["Percentage", "Index"])))
.with(ids.prop("basedOn", "Based On", Value::Enum(0)).with_ui(popup(&["Characters", "Characters Excluding Spaces", "Words", "Lines"])))
.with(ids.prop("mode", "Mode", Value::Enum(0)).with_ui(popup(&["Add", "Subtract", "Intersect", "Min", "Max", "Difference"])))
.with(ids.prop("amount", "Amount", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("shape", "Shape", Value::Enum(0)).with_ui(popup(&["Square", "Ramp Up", "Ramp Down", "Triangle", "Round", "Smooth"])))
.with(ids.prop("smoothness", "Smoothness", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("easeHigh", "Ease High", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(ids.prop("easeLow", "Ease Low", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(ids.prop("randomize", "Randomize Order", Value::Bool(false)).with_ui(ParamUi::Checkbox))
.with(ids.prop("randomSeed", "Random Seed", Value::Scalar(0.0)));
g.with(ids.prop("start", "Start", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(ids.prop("end", "End", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("offset", "Offset", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(adv)
}
/// Text animator properties by id (Animate ▸ …).
pub fn text_anim_prop(ids: &mut Ids, kind: &str) -> Option<Property> {
Some(match kind {
"anchor" => ids.prop("anchor", "Anchor Point", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point),
"position" => ids.prop("position", "Position", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point),
"scale" => ids.prop("scale", "Scale", Value::Vec2([100.0, 100.0])).with_ui(ParamUi::Percent),
"skew" => ids.prop("skew", "Skew", Value::Scalar(0.0)),
"rotation" => ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle),
"opacity" => ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(ParamUi::Percent),
"fillColor" => ids.prop("fillColor", "Fill Color", Value::Color([1.0, 0.0, 0.0, 1.0])).with_ui(ParamUi::Color),
"strokeColor" => ids.prop("strokeColor", "Stroke Color", Value::Color([1.0, 0.0, 0.0, 1.0])).with_ui(ParamUi::Color),
"strokeWidth" => ids.prop("strokeWidth", "Stroke Width", Value::Scalar(0.0)).with_ui(ParamUi::Pixels),
"tracking" => ids.prop("tracking", "Tracking Amount", Value::Scalar(0.0)),
"lineSpacing" => ids.prop("lineSpacing", "Line Spacing", Value::Vec2([0.0, 0.0])),
"characterOffset" => ids.prop("characterOffset", "Character Offset", Value::Scalar(0.0)),
"blur" => ids.prop("blur", "Blur", Value::Vec2([0.0, 0.0])),
_ => return None,
})
}
// ---------------------------------------------------------------- shape layer contents
pub fn contents(ids: &mut Ids) -> PropGroup {
ids.group("contents", "Contents")
}
/// Shape group transform (2D).
pub fn shape_transform(ids: &mut Ids) -> PropGroup {
ids.group("transform", "Transform")
.with(ids.prop("anchor", "Anchor Point", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point))
.with(ids.prop("position", "Position", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point))
.with(ids.prop("scale", "Scale", Value::Vec2([100.0, 100.0])).with_ui(ParamUi::Percent))
.with(ids.prop("skew", "Skew", Value::Scalar(0.0)).with_ui(slider(-85.0, 85.0, -85.0, 85.0, 1)))
.with(ids.prop("skewAxis", "Skew Axis", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)))
}
fn indexed(mut g: PropGroup) -> PropGroup {
g.kind = GroupKind::Indexed;
g
}
pub fn shape_group(ids: &mut Ids, name: &str, items: Vec<PropGroup>) -> PropGroup {
let mut c = ids.group("contents", "Contents");
for i in items {
c.children.push(i.into());
}
let mut g = indexed(ids.group("group", name));
g.children.push(ids.prop("blend", "Blend Mode", Value::Enum(0)).with_ui(ParamUi::Hidden).into());
g.with(c).with(shape_transform(ids))
}
pub fn shape_rect(ids: &mut Ids, size: [f64; 2], position: [f64; 2], roundness: f64) -> PropGroup {
indexed(ids.group("rect", "Rectangle Path 1"))
.with(ids.prop("direction", "Path Direction", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("size", "Size", Value::Vec2(size)).with_ui(ParamUi::Pixels))
.with(ids.prop("position", "Position", Value::Vec2(position)).with_ui(ParamUi::Point))
.with(ids.prop("roundness", "Roundness", Value::Scalar(roundness)).with_ui(ParamUi::Pixels))
}
pub fn shape_ellipse(ids: &mut Ids, size: [f64; 2], position: [f64; 2]) -> PropGroup {
indexed(ids.group("ellipse", "Ellipse Path 1"))
.with(ids.prop("direction", "Path Direction", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("size", "Size", Value::Vec2(size)).with_ui(ParamUi::Pixels))
.with(ids.prop("position", "Position", Value::Vec2(position)).with_ui(ParamUi::Point))
}
/// Polystar: `star = false` makes a polygon.
pub fn shape_star(ids: &mut Ids, star: bool, points: f64, position: [f64; 2], outer: f64, inner: f64) -> PropGroup {
let mut g = indexed(ids.group("star", "Polystar Path 1"))
.with(ids.prop("direction", "Path Direction", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("type", "Type", Value::Enum(if star { 0 } else { 1 })).with_ui(popup(&["Star", "Polygon"])))
.with(ids.prop("points", "Points", Value::Scalar(points)).with_ui(slider(3.0, 100.0, 3.0, 20.0, 1)))
.with(ids.prop("position", "Position", Value::Vec2(position)).with_ui(ParamUi::Point))
.with(ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle));
if star {
g = g.with(ids.prop("innerRadius", "Inner Radius", Value::Scalar(inner)).with_ui(ParamUi::Pixels));
}
g = g.with(ids.prop("outerRadius", "Outer Radius", Value::Scalar(outer)).with_ui(ParamUi::Pixels));
if star {
g = g.with(ids.prop("innerRoundness", "Inner Roundness", Value::Scalar(0.0)).with_ui(ParamUi::Percent));
}
g.with(ids.prop("outerRoundness", "Outer Roundness", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
}
pub fn shape_path(ids: &mut Ids, path: ShapePath) -> PropGroup {
indexed(ids.group("path", "Path 1"))
.with(ids.prop("direction", "Path Direction", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("path", "Path", Value::Path(path)).with_ui(ParamUi::Path))
}
pub fn shape_fill(ids: &mut Ids, color: [f64; 4]) -> PropGroup {
indexed(ids.group("fill", "Fill 1"))
.with(ids.prop("blend", "Blend Mode", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("composite", "Composite", Value::Enum(0)).with_ui(popup(&["Below Previous in Same Group", "Above Previous in Same Group"])))
.with(ids.prop("rule", "Fill Rule", Value::Enum(0)).with_ui(popup(&["Non-Zero Winding", "Even-Odd"])))
.with(ids.prop("color", "Color", Value::Color(color)).with_ui(ParamUi::Color))
.with(ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)))
}
pub fn shape_stroke(ids: &mut Ids, color: [f64; 4], width: f64) -> PropGroup {
indexed(ids.group("stroke", "Stroke 1"))
.with(ids.prop("blend", "Blend Mode", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("composite", "Composite", Value::Enum(0)).with_ui(popup(&["Below Previous in Same Group", "Above Previous in Same Group"])))
.with(ids.prop("color", "Color", Value::Color(color)).with_ui(ParamUi::Color))
.with(ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)))
.with(ids.prop("width", "Stroke Width", Value::Scalar(width)).with_ui(ParamUi::Pixels))
.with(ids.prop("cap", "Line Cap", Value::Enum(0)).with_ui(popup(&["Butt Cap", "Round Cap", "Projecting Cap"])))
.with(ids.prop("join", "Line Join", Value::Enum(0)).with_ui(popup(&["Miter Join", "Round Join", "Bevel Join"])))
.with(ids.prop("miter", "Miter Limit", Value::Scalar(4.0)))
.with(
ids.group("dashes", "Dashes")
.with(ids.prop("dash", "Dash", Value::Scalar(0.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("gap", "Gap", Value::Scalar(0.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("offset", "Offset", Value::Scalar(0.0)).with_ui(ParamUi::Pixels)),
)
}
pub fn shape_gradient_fill(ids: &mut Ids, radial: bool, start: [f64; 2], end: [f64; 2], g: Gradient) -> PropGroup {
indexed(ids.group("gfill", "Gradient Fill 1"))
.with(ids.prop("blend", "Blend Mode", Value::Enum(0)).with_ui(ParamUi::Hidden))
.with(ids.prop("rule", "Fill Rule", Value::Enum(0)).with_ui(popup(&["Non-Zero Winding", "Even-Odd"])))
.with(ids.prop("type", "Type", Value::Enum(radial as u32)).with_ui(popup(&["Linear", "Radial"])))
.with(ids.prop("start", "Start Point", Value::Vec2(start)).with_ui(ParamUi::Point))
.with(ids.prop("end", "End Point", Value::Vec2(end)).with_ui(ParamUi::Point))
.with(ids.prop("highlightLength", "Highlight Length", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(ids.prop("highlightAngle", "Highlight Angle", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("colors", "Colors", Value::Gradient(g)).with_ui(ParamUi::Gradient))
.with(ids.prop("opacity", "Opacity", Value::Scalar(100.0)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 0)))
}
pub fn shape_trim(ids: &mut Ids, start: f64, end: f64, offset: f64) -> PropGroup {
indexed(ids.group("trim", "Trim Paths 1"))
.with(ids.prop("start", "Start", Value::Scalar(start)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 1)))
.with(ids.prop("end", "End", Value::Scalar(end)).with_ui(slider(0.0, 100.0, 0.0, 100.0, 1)))
.with(ids.prop("offset", "Offset", Value::Scalar(offset)).with_ui(ParamUi::Angle))
.with(ids.prop("mode", "Trim Multiple Shapes", Value::Enum(0)).with_ui(popup(&["Simultaneously", "Individually"])))
}
pub fn shape_repeater(ids: &mut Ids, copies: f64, offset_pos: [f64; 2]) -> PropGroup {
let tr = ids
.group("transform", "Transform")
.with(ids.prop("anchor", "Anchor Point", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point))
.with(ids.prop("position", "Position", Value::Vec2(offset_pos)).with_ui(ParamUi::Point))
.with(ids.prop("scale", "Scale", Value::Vec2([100.0, 100.0])).with_ui(ParamUi::Percent))
.with(ids.prop("rotation", "Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("startOpacity", "Start Opacity", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("endOpacity", "End Opacity", Value::Scalar(100.0)).with_ui(ParamUi::Percent));
indexed(ids.group("repeater", "Repeater 1"))
.with(ids.prop("copies", "Copies", Value::Scalar(copies)))
.with(ids.prop("offset", "Offset", Value::Scalar(0.0)))
.with(ids.prop("composite", "Composite", Value::Enum(0)).with_ui(popup(&["Below", "Above"])))
.with(tr)
}
pub fn shape_simple_op(ids: &mut Ids, kind: &str) -> Option<PropGroup> {
let g = match kind {
"round" => indexed(ids.group("round", "Round Corners 1")).with(ids.prop("radius", "Radius", Value::Scalar(10.0)).with_ui(ParamUi::Pixels)),
"offset" => indexed(ids.group("offset", "Offset Paths 1"))
.with(ids.prop("amount", "Amount", Value::Scalar(10.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("join", "Line Join", Value::Enum(0)).with_ui(popup(&["Miter Join", "Round Join", "Bevel Join"])))
.with(ids.prop("miter", "Miter Limit", Value::Scalar(4.0)))
.with(ids.prop("copies", "Copies", Value::Scalar(1.0)))
.with(ids.prop("copyOffset", "Copy Offset", Value::Scalar(0.0))),
"pucker" => indexed(ids.group("pucker", "Pucker & Bloat 1")).with(ids.prop("amount", "Amount", Value::Scalar(0.0)).with_ui(slider(-100.0, 100.0, -100.0, 100.0, 1))),
"twist" => indexed(ids.group("twist", "Twist 1"))
.with(ids.prop("angle", "Angle", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("center", "Center", Value::Vec2([0.0, 0.0])).with_ui(ParamUi::Point)),
"zigzag" => indexed(ids.group("zigzag", "Zig Zag 1"))
.with(ids.prop("size", "Size", Value::Scalar(10.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("ridges", "Ridges per segment", Value::Scalar(5.0)))
.with(ids.prop("points", "Points", Value::Enum(0)).with_ui(popup(&["Corner", "Smooth"]))),
"wiggle" => indexed(ids.group("wiggle", "Wiggle Paths 1"))
.with(ids.prop("size", "Size", Value::Scalar(10.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("detail", "Detail", Value::Scalar(10.0)))
.with(ids.prop("points", "Points", Value::Enum(1)).with_ui(popup(&["Corner", "Smooth"])))
.with(ids.prop("speed", "Wiggles/Second", Value::Scalar(2.0)))
.with(ids.prop("correlation", "Correlation", Value::Scalar(50.0)).with_ui(ParamUi::Percent))
.with(ids.prop("phase", "Temporal Phase", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("seed", "Random Seed", Value::Scalar(0.0))),
"merge" => indexed(ids.group("merge", "Merge Paths 1"))
.with(ids.prop("mode", "Mode", Value::Enum(0)).with_ui(popup(&["Merge", "Add", "Subtract", "Intersect", "Exclude Intersections"]))),
_ => return None,
};
Some(g)
}
// ---------------------------------------------------------------- camera / light / 3D
pub fn camera_options(ids: &mut Ids, zoom: f64) -> PropGroup {
ids.group("cameraOptions", "Camera Options")
.with(ids.prop("zoom", "Zoom", Value::Scalar(zoom)).with_ui(ParamUi::Pixels))
.with(ids.prop("dof", "Depth of Field", Value::Bool(false)).with_ui(ParamUi::Checkbox))
.with(ids.prop("focusDistance", "Focus Distance", Value::Scalar(zoom)).with_ui(ParamUi::Pixels))
.with(ids.prop("aperture", "Aperture", Value::Scalar(25.3)).with_ui(ParamUi::Pixels))
.with(ids.prop("blurLevel", "Blur Level", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
}
pub fn light_options(ids: &mut Ids, kind: LightKind) -> PropGroup {
let mut g = ids
.group("lightOptions", "Light Options")
.with(ids.prop("intensity", "Intensity", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("color", "Color", Value::Color([1.0, 1.0, 1.0, 1.0])).with_ui(ParamUi::Color));
if kind == LightKind::Spot {
g = g
.with(ids.prop("coneAngle", "Cone Angle", Value::Scalar(90.0)).with_ui(ParamUi::Angle))
.with(ids.prop("coneFeather", "Cone Feather", Value::Scalar(50.0)).with_ui(ParamUi::Percent));
}
if kind != LightKind::Ambient {
g = g
.with(ids.prop("falloff", "Falloff", Value::Enum(0)).with_ui(popup(&["None", "Smooth", "Inverse Square Clamped"])))
.with(ids.prop("radius", "Radius", Value::Scalar(500.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("falloffDistance", "Falloff Distance", Value::Scalar(500.0)).with_ui(ParamUi::Pixels))
.with(ids.prop("castsShadows", "Casts Shadows", Value::Bool(false)).with_ui(ParamUi::Checkbox))
.with(ids.prop("shadowDarkness", "Shadow Darkness", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("shadowDiffusion", "Shadow Diffusion", Value::Scalar(0.0)).with_ui(ParamUi::Pixels));
}
g
}
pub fn material_options(ids: &mut Ids) -> PropGroup {
ids.group("materialOptions", "Material Options")
.with(ids.prop("castsShadows", "Casts Shadows", Value::Enum(0)).with_ui(popup(&["Off", "On", "Only"])))
.with(ids.prop("lightTransmission", "Light Transmission", Value::Scalar(0.0)).with_ui(ParamUi::Percent))
.with(ids.prop("acceptsShadows", "Accepts Shadows", Value::Enum(1)).with_ui(popup(&["Off", "On", "Only"])))
.with(ids.prop("acceptsLights", "Accepts Lights", Value::Bool(true)).with_ui(ParamUi::Checkbox))
.with(ids.prop("ambient", "Ambient", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
.with(ids.prop("diffuse", "Diffuse", Value::Scalar(50.0)).with_ui(ParamUi::Percent))
.with(ids.prop("specularIntensity", "Specular Intensity", Value::Scalar(50.0)).with_ui(ParamUi::Percent))
.with(ids.prop("specularShininess", "Specular Shininess", Value::Scalar(5.0)).with_ui(ParamUi::Percent))
.with(ids.prop("metal", "Metal", Value::Scalar(100.0)).with_ui(ParamUi::Percent))
}
pub fn audio(ids: &mut Ids) -> PropGroup {
ids.group("audio", "Audio").with(ids.prop("levels", "Audio Levels", Value::Vec2([0.0, 0.0])))
}
// ---------------------------------------------------------------- layers
/// Default label colour for a layer source (Labels preferences defaults).
pub fn default_label(src: &LayerSource, project: &Project) -> Label {
match src {
LayerSource::Comp { .. } => Label::Sandstone,
LayerSource::Footage { item } => match project.item(*item).map(|i| i.type_name()) {
Some("Image") | Some("Image Sequence") => Label::Lavender,
Some("Audio") => Label::SeaFoam,
_ => Label::Aqua,
},
LayerSource::Solid { .. } => Label::Red,
LayerSource::Text => Label::Red,
LayerSource::Shape => Label::Blue,
LayerSource::Null => Label::Red,
LayerSource::Camera | LayerSource::Light { .. } => Label::Pink,
}
}
/// A new layer spanning the whole comp, anchored at its source centre and centred in the comp.
pub fn layer(project: &mut Project, comp: &Comp, name: &str, source: LayerSource, size: (u32, u32), duration: Option<Tick>) -> Layer {
let label = default_label(&source, project);
let id = LayerId(project.alloc());
let mut ids = Ids(&mut project.next_id);
let (w, h) = (size.0 as f64, size.1 as f64);
let (cw, ch) = (comp.width as f64, comp.height as f64);
let anchor = match source {
LayerSource::Text | LayerSource::Shape | LayerSource::Camera | LayerSource::Light { .. } => [0.0, 0.0],
LayerSource::Null => [50.0, 50.0],
_ => [w / 2.0, h / 2.0],
};
let mut root = ids.group("layer", name);
match &source {
LayerSource::Text => {
root.children.push(text(&mut ids, TextDoc::default()).into());
}
LayerSource::Shape => {
root.children.push(contents(&mut ids).into());
}
_ => {}
}
if source.is_av() {
root.children.push(masks(&mut ids).into());
root.children.push(effects(&mut ids).into());
} else if matches!(source, LayerSource::Null) {
root.children.push(effects(&mut ids).into());
}
let mut tr = transform(&mut ids, anchor, [cw / 2.0, ch / 2.0]);
if let LayerSource::Camera = source {
// Two-node camera default: point of interest at the comp centre, camera at -zoom.
let zoom = effectcraft_geom::default_camera_zoom(cw);
tr = ids
.group("transform", "Transform")
.with(ids.prop("poi", "Point of Interest", Value::Vec3([cw / 2.0, ch / 2.0, 0.0])).with_ui(ParamUi::Point3).spatial())
.with(ids.prop("position", "Position", Value::Vec3([cw / 2.0, ch / 2.0, -zoom])).with_ui(ParamUi::Point3).spatial())
.with(ids.prop("orientation", "Orientation", Value::Vec3([0.0; 3])).with_ui(ParamUi::Angle))
.with(ids.prop("rotationX", "X Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("rotationY", "Y Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle))
.with(ids.prop("rotation", "Z Rotation", Value::Scalar(0.0)).with_ui(ParamUi::Angle));
root.children.push(tr.into());
root.children.push(camera_options(&mut ids, zoom).into());
} else if let LayerSource::Light { kind } = source {
let mut g = ids.group("transform", "Transform");
if matches!(kind, LightKind::Spot | LightKind::Parallel) {
g.children.push(ids.prop("poi", "Point of Interest", Value::Vec3([cw / 2.0, ch / 2.0, 0.0])).with_ui(ParamUi::Point3).spatial().into());
}
if kind != LightKind::Ambient {
g.children.push(ids.prop("position", "Position", Value::Vec3([cw / 2.0 - 260.0, ch / 2.0 - 260.0, -440.0])).with_ui(ParamUi::Point3).spatial().into());
}
root.children.push(g.into());
root.children.push(light_options(&mut ids, kind).into());
} else {
if let LayerSource::Null = source {
// Nulls are 100×100.
}
root.children.push(std::mem::replace(&mut tr, PropGroup::new(0, "", "")).into());
if source.is_av() {
root.children.push(material_options(&mut ids).into());
}
}
let has_audio = matches!(&source, LayerSource::Footage { item } if matches!(project.item(*item).map(|i| &i.kind), Some(crate::ItemKind::Footage(f)) if f.has_audio))
|| matches!(source, LayerSource::Comp { .. });
if has_audio {
let mut ids = Ids(&mut project.next_id);
root.children.push(audio(&mut ids).into());
}
let out = duration.map(|d| d.min(comp.duration)).unwrap_or(comp.duration);
Layer {
id,
name: comp.unique_layer_name(name),
source,
label,
comment: String::new(),
start_time: Tick::ZERO,
in_point: Tick::ZERO,
out_point: out,
stretch: 100.0,
switches: Switches::default(),
blend_mode: BlendMode::Normal,
preserve_transparency: false,
track_matte: None,
parent: None,
markers: vec![],
auto_orient: Default::default(),
props: root,
}
}
+679
View File
@@ -0,0 +1,679 @@
//! The EffectCraft document model.
//!
//! `Project` → items (folders, compositions, footage, solids) → `Comp` → `Layer` → property tree
//! ([`props`]). Compositions sit behind `Arc` so undo snapshots share everything that did not
//! change.
pub mod build;
pub mod props;
use std::collections::BTreeMap;
use std::sync::Arc;
use effectcraft_color::{BlendMode, Label};
use effectcraft_time::{FrameRate, Tick};
pub use props::{Expression, GroupKind, MaskMode, Node, ParamUi, PropGroup, Property, Uid, parse_path};
use serde::{Deserialize, Serialize};
pub use effectcraft_keyframe as keyframe;
pub use effectcraft_keyframe::{Keyframe, Value};
pub const SCHEMA_VERSION: u32 = 1;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ItemId(pub u64);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct LayerId(pub u64);
#[derive(Debug, thiserror::Error)]
pub enum ProjectError {
#[error("no item {0:?}")]
NoItem(ItemId),
#[error("item {0:?} is not a composition")]
NotComp(ItemId),
#[error("no layer {0:?}")]
NoLayer(LayerId),
#[error("no property `{0}`")]
NoProperty(String),
#[error("{0}")]
Invalid(String),
}
/// Project bit depth.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum BitDepth {
#[default]
Bpc8,
Bpc16,
Bpc32,
}
impl BitDepth {
pub fn label(self) -> &'static str {
match self {
BitDepth::Bpc8 => "8 bpc",
BitDepth::Bpc16 => "16 bpc",
BitDepth::Bpc32 => "32 bpc",
}
}
pub fn next(self) -> BitDepth {
match self {
BitDepth::Bpc8 => BitDepth::Bpc16,
BitDepth::Bpc16 => BitDepth::Bpc32,
BitDepth::Bpc32 => BitDepth::Bpc8,
}
}
pub fn is_float(self) -> bool {
self == BitDepth::Bpc32
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum TimeDisplayStyle {
#[default]
Timecode,
Frames,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectSettings {
pub bit_depth: BitDepth,
/// Blend in linear light instead of the sRGB-encoded working space.
pub linearize: bool,
pub time_display: TimeDisplayStyle,
/// Frame numbering starts at 0 (or 1).
pub frame_start: i64,
pub audio_sample_rate: u32,
}
impl Default for ProjectSettings {
fn default() -> Self {
ProjectSettings { bit_depth: BitDepth::Bpc8, linearize: false, time_display: TimeDisplayStyle::Timecode, frame_start: 0, audio_sample_rate: 48_000 }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Marker {
pub time: Tick,
#[serde(default)]
pub duration: Tick,
#[serde(default)]
pub comment: String,
#[serde(default)]
pub label: Label,
#[serde(default)]
pub chapter: String,
#[serde(default)]
pub url: String,
#[serde(default)]
pub protected: bool,
}
/// 3D renderer of a composition.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Renderer {
#[default]
Classic3D,
Advanced3D,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Comp {
pub width: u32,
pub height: u32,
pub pixel_aspect: f64,
pub frame_rate: FrameRate,
pub duration: Tick,
/// Start timecode/frame shown for time 0.
pub display_start: Tick,
pub background: [f32; 3],
pub work_area: (Tick, Tick),
/// Layer #1 first (top of the stack).
pub layers: Vec<Layer>,
#[serde(default)]
pub markers: Vec<Marker>,
pub shutter_angle: f64,
pub shutter_phase: f64,
pub motion_blur_samples: u32,
#[serde(default)]
pub renderer: Renderer,
/// Comp switches (timeline toolbar).
#[serde(default)]
pub hide_shy: bool,
#[serde(default = "yes")]
pub enable_motion_blur: bool,
#[serde(default = "yes")]
pub enable_frame_blending: bool,
#[serde(default)]
pub draft_3d: bool,
#[serde(default)]
pub poster_time: Tick,
}
fn yes() -> bool {
true
}
impl Comp {
pub fn new(width: u32, height: u32, frame_rate: FrameRate, duration: Tick) -> Comp {
Comp {
width,
height,
pixel_aspect: 1.0,
frame_rate,
duration,
display_start: Tick::ZERO,
background: [0.0, 0.0, 0.0],
work_area: (Tick::ZERO, duration),
layers: vec![],
markers: vec![],
shutter_angle: 180.0,
shutter_phase: -90.0,
motion_blur_samples: 16,
renderer: Renderer::Classic3D,
hide_shy: false,
enable_motion_blur: true,
enable_frame_blending: true,
draft_3d: false,
poster_time: Tick::ZERO,
}
}
pub fn layer(&self, id: LayerId) -> Option<&Layer> {
self.layers.iter().find(|l| l.id == id)
}
pub fn layer_mut(&mut self, id: LayerId) -> Option<&mut Layer> {
self.layers.iter_mut().find(|l| l.id == id)
}
/// 1-based layer number (#) of a layer.
pub fn index_of(&self, id: LayerId) -> Option<usize> {
self.layers.iter().position(|l| l.id == id).map(|i| i + 1)
}
pub fn layer_by_name(&self, name: &str) -> Option<&Layer> {
self.layers.iter().find(|l| l.name == name)
}
pub fn frame_duration(&self) -> Tick {
self.frame_rate.frame_duration()
}
/// Any 3D layer present (camera/lights or a 3D switch).
pub fn has_3d(&self) -> bool {
self.layers.iter().any(|l| l.switches.three_d || matches!(l.source, LayerSource::Camera | LayerSource::Light { .. }))
}
/// The active camera at `t`: the topmost enabled camera layer active at that time.
pub fn active_camera(&self, t: Tick) -> Option<&Layer> {
self.layers.iter().find(|l| matches!(l.source, LayerSource::Camera) && l.switches.video && l.is_active_at(t))
}
/// Unique layer name with a numeric suffix (`Shape Layer 2`).
pub fn unique_layer_name(&self, base: &str) -> String {
if !self.layers.iter().any(|l| l.name == base) {
return base.to_string();
}
let stem = base.trim_end_matches(|c: char| c.is_ascii_digit()).trim_end();
(2..).map(|i| format!("{stem} {i}")).find(|n| !self.layers.iter().any(|l| &l.name == n)).unwrap_or_default()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum LightKind {
Parallel,
Spot,
#[default]
Point,
Ambient,
Environment,
}
impl LightKind {
pub const ALL: [LightKind; 5] = [LightKind::Parallel, LightKind::Spot, LightKind::Point, LightKind::Ambient, LightKind::Environment];
pub fn label(self) -> &'static str {
match self {
LightKind::Parallel => "Parallel",
LightKind::Spot => "Spot",
LightKind::Point => "Point",
LightKind::Ambient => "Ambient",
LightKind::Environment => "Environment",
}
}
}
/// What a layer shows.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum LayerSource {
/// Footage item (video, still, sequence, audio).
Footage { item: ItemId },
/// Nested composition (precomp).
Comp { item: ItemId },
/// Solid item (solids also back adjustment layers).
Solid { item: ItemId },
Text,
Shape,
Null,
Camera,
Light { kind: LightKind },
}
impl LayerSource {
pub fn item(&self) -> Option<ItemId> {
match self {
LayerSource::Footage { item } | LayerSource::Comp { item } | LayerSource::Solid { item } => Some(*item),
_ => None,
}
}
pub fn type_name(&self) -> &'static str {
match self {
LayerSource::Footage { .. } => "Footage",
LayerSource::Comp { .. } => "Composition",
LayerSource::Solid { .. } => "Solid",
LayerSource::Text => "Text",
LayerSource::Shape => "Shape",
LayerSource::Null => "Null",
LayerSource::Camera => "Camera",
LayerSource::Light { .. } => "Light",
}
}
/// Layers with pixels (cameras, lights and nulls have none).
pub fn is_av(&self) -> bool {
!matches!(self, LayerSource::Camera | LayerSource::Light { .. } | LayerSource::Null)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Quality {
#[default]
Best,
Draft,
Wireframe,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Sampling {
#[default]
Bilinear,
Bicubic,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum FrameBlend {
#[default]
Off,
FrameMix,
PixelMotion,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Switches {
pub video: bool,
pub audio: bool,
pub solo: bool,
pub locked: bool,
pub shy: bool,
/// Collapse transformations (precomps) / continuously rasterize (vector layers).
pub collapse: bool,
pub quality: Quality,
pub sampling: Sampling,
pub effects: bool,
pub frame_blend: FrameBlend,
pub motion_blur: bool,
pub adjustment: bool,
pub three_d: bool,
pub guide: bool,
}
impl Default for Switches {
fn default() -> Self {
Switches {
video: true,
audio: true,
solo: false,
locked: false,
shy: false,
collapse: false,
quality: Quality::Best,
sampling: Sampling::Bilinear,
effects: true,
frame_blend: FrameBlend::Off,
motion_blur: false,
adjustment: false,
three_d: false,
guide: false,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum MatteKind {
#[default]
Alpha,
AlphaInverted,
Luma,
LumaInverted,
}
impl MatteKind {
pub const ALL: [MatteKind; 4] = [MatteKind::Alpha, MatteKind::AlphaInverted, MatteKind::Luma, MatteKind::LumaInverted];
pub fn label(self) -> &'static str {
match self {
MatteKind::Alpha => "Alpha Matte",
MatteKind::AlphaInverted => "Alpha Inverted Matte",
MatteKind::Luma => "Luma Matte",
MatteKind::LumaInverted => "Luma Inverted Matte",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TrackMatte {
pub layer: LayerId,
pub kind: MatteKind,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum AutoOrient {
#[default]
Off,
AlongPath,
TowardsCamera,
TowardsPointOfInterest,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layer {
pub id: LayerId,
pub name: String,
pub source: LayerSource,
pub label: Label,
#[serde(default)]
pub comment: String,
/// Comp time where the layer's time 0 sits.
pub start_time: Tick,
/// Visible span in comp time.
pub in_point: Tick,
pub out_point: Tick,
/// Time stretch in percent (100 = normal, negative = reversed).
pub stretch: f64,
pub switches: Switches,
pub blend_mode: BlendMode,
#[serde(default)]
pub preserve_transparency: bool,
#[serde(default)]
pub track_matte: Option<TrackMatte>,
#[serde(default)]
pub parent: Option<LayerId>,
#[serde(default)]
pub markers: Vec<Marker>,
#[serde(default)]
pub auto_orient: AutoOrient,
/// The property tree (Masks, Effects, Transform, Text, Contents, Camera/Light options…).
pub props: PropGroup,
}
impl Layer {
pub fn is_active_at(&self, t: Tick) -> bool {
t >= self.in_point && t < self.out_point
}
/// Layer time for a comp time (stretch-aware).
pub fn layer_time(&self, comp_t: Tick) -> Tick {
let d = comp_t - self.start_time;
if (self.stretch - 100.0).abs() < 1e-9 {
d
} else {
Tick((d.0 as f64 * 100.0 / self.stretch) as i64)
}
}
/// Comp time for a layer time.
pub fn comp_time(&self, layer_t: Tick) -> Tick {
if (self.stretch - 100.0).abs() < 1e-9 {
self.start_time + layer_t
} else {
self.start_time + Tick((layer_t.0 as f64 * self.stretch / 100.0) as i64)
}
}
pub fn transform(&self) -> Option<&PropGroup> {
self.props.sub("transform")
}
pub fn transform_mut(&mut self) -> Option<&mut PropGroup> {
self.props.sub_mut("transform")
}
pub fn effects(&self) -> Option<&PropGroup> {
self.props.sub("effects")
}
pub fn masks(&self) -> Option<&PropGroup> {
self.props.sub("masks")
}
pub fn is_camera(&self) -> bool {
matches!(self.source, LayerSource::Camera)
}
pub fn is_light(&self) -> bool {
matches!(self.source, LayerSource::Light { .. })
}
/// The layer participates in 3D (3D switch, or cameras/lights which are always 3D).
pub fn is_3d(&self) -> bool {
self.switches.three_d || self.is_camera() || self.is_light()
}
pub fn has_video(&self) -> bool {
self.source.is_av() && self.switches.video
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum FootageKind {
#[default]
Video,
Still,
Sequence,
Audio,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum AlphaMode {
#[default]
Straight,
Premultiplied,
Ignore,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Footage {
pub path: String,
pub kind: FootageKind,
pub width: u32,
pub height: u32,
pub pixel_aspect: f64,
pub frame_rate: FrameRate,
/// Native rate before "Conform to frame rate".
#[serde(default)]
pub native_rate: Option<FrameRate>,
pub duration: Tick,
pub has_video: bool,
pub has_audio: bool,
pub alpha: AlphaMode,
#[serde(default)]
pub premul_color: [f32; 3],
#[serde(default = "one")]
pub loop_count: u32,
#[serde(default)]
pub codec: String,
#[serde(default)]
pub missing: bool,
/// Image sequence files (when kind = Sequence).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub sequence: Vec<String>,
}
fn one() -> u32 {
1
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Solid {
pub color: [f32; 3],
pub width: u32,
pub height: u32,
pub pixel_aspect: f64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ItemKind {
Folder,
Comp(Arc<Comp>),
Footage(Footage),
Solid(Solid),
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Item {
pub id: ItemId,
pub name: String,
pub label: Label,
#[serde(default)]
pub comment: String,
/// Containing folder (None = project root).
#[serde(default)]
pub parent: Option<ItemId>,
pub kind: ItemKind,
}
impl Item {
pub fn type_name(&self) -> &'static str {
match &self.kind {
ItemKind::Folder => "Folder",
ItemKind::Comp(_) => "Composition",
ItemKind::Footage(f) => match f.kind {
FootageKind::Video => "Video",
FootageKind::Still => "Image",
FootageKind::Sequence => "Image Sequence",
FootageKind::Audio => "Audio",
},
ItemKind::Solid(_) => "Solid",
}
}
pub fn as_comp(&self) -> Option<&Comp> {
if let ItemKind::Comp(c) = &self.kind { Some(c) } else { None }
}
pub fn is_folder(&self) -> bool {
matches!(self.kind, ItemKind::Folder)
}
/// (width, height) for visual items.
pub fn dimensions(&self) -> Option<(u32, u32)> {
match &self.kind {
ItemKind::Comp(c) => Some((c.width, c.height)),
ItemKind::Footage(f) if f.has_video => Some((f.width, f.height)),
ItemKind::Solid(s) => Some((s.width, s.height)),
_ => None,
}
}
pub fn duration(&self) -> Option<Tick> {
match &self.kind {
ItemKind::Comp(c) => Some(c.duration),
ItemKind::Footage(f) if f.kind != FootageKind::Still => Some(f.duration),
_ => None,
}
}
pub fn frame_rate(&self) -> Option<FrameRate> {
match &self.kind {
ItemKind::Comp(c) => Some(c.frame_rate),
ItemKind::Footage(f) if f.kind == FootageKind::Video || f.kind == FootageKind::Sequence => Some(f.frame_rate),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Project {
pub schema: u32,
pub settings: ProjectSettings,
pub items: BTreeMap<ItemId, Item>,
pub next_id: u64,
}
impl Default for Project {
fn default() -> Self {
Project { schema: SCHEMA_VERSION, settings: ProjectSettings::default(), items: BTreeMap::new(), next_id: 1 }
}
}
impl Project {
/// Allocate an id (items, layers and property uids share one counter).
pub fn alloc(&mut self) -> u64 {
let id = self.next_id;
self.next_id += 1;
id
}
pub fn item(&self, id: ItemId) -> Option<&Item> {
self.items.get(&id)
}
pub fn item_mut(&mut self, id: ItemId) -> Option<&mut Item> {
self.items.get_mut(&id)
}
pub fn comp(&self, id: ItemId) -> Option<&Comp> {
self.items.get(&id)?.as_comp()
}
/// Mutable comp (copy-on-write).
pub fn comp_mut(&mut self, id: ItemId) -> Option<&mut Comp> {
match &mut self.items.get_mut(&id)?.kind {
ItemKind::Comp(c) => Some(Arc::make_mut(c)),
_ => None,
}
}
pub fn add_item(&mut self, name: &str, label: Label, parent: Option<ItemId>, kind: ItemKind) -> ItemId {
let id = ItemId(self.alloc());
self.items.insert(id, Item { id, name: name.into(), label, comment: String::new(), parent, kind });
id
}
/// Children of a folder (None = root), folders first then by name.
pub fn children(&self, folder: Option<ItemId>) -> Vec<&Item> {
let mut v: Vec<&Item> = self.items.values().filter(|i| i.parent == folder).collect();
v.sort_by(|a, b| b.is_folder().cmp(&a.is_folder()).then_with(|| a.name.to_lowercase().cmp(&b.name.to_lowercase())));
v
}
pub fn comps(&self) -> impl Iterator<Item = (&ItemId, &Comp)> {
self.items.iter().filter_map(|(id, i)| i.as_comp().map(|c| (id, c)))
}
pub fn find_by_name(&self, name: &str) -> Option<&Item> {
self.items.values().find(|i| i.name == name)
}
pub fn folder_named(&self, name: &str) -> Option<ItemId> {
self.items.values().find(|i| i.is_folder() && i.name == name).map(|i| i.id)
}
/// Find the comp that contains `layer`.
pub fn comp_of_layer(&self, layer: LayerId) -> Option<ItemId> {
self.comps().find(|(_, c)| c.layer(layer).is_some()).map(|(id, _)| *id)
}
/// Whether comp `inner` is (transitively) nested inside comp `outer` (to prevent cycles).
pub fn comp_contains(&self, outer: ItemId, inner: ItemId) -> bool {
if outer == inner {
return true;
}
let Some(c) = self.comp(outer) else { return false };
c.layers.iter().any(|l| matches!(l.source, LayerSource::Comp { item } if self.comp_contains(item, inner)))
}
/// Make sure `next_id` exceeds every id in the project (after loading or merging).
pub fn fix_next_id(&mut self) {
let mut m = self.next_id;
for (id, it) in &self.items {
m = m.max(id.0 + 1);
if let ItemKind::Comp(c) = &it.kind {
for l in &c.layers {
m = m.max(l.id.0 + 1).max(l.props.max_uid() + 1);
}
}
}
self.next_id = m;
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_default()
}
pub fn from_json(s: &str) -> Result<Project, ProjectError> {
let mut p: Project = serde_json::from_str(s).map_err(|e| ProjectError::Invalid(e.to_string()))?;
if p.schema > SCHEMA_VERSION {
return Err(ProjectError::Invalid(format!("project schema {} is newer than this version supports ({SCHEMA_VERSION})", p.schema)));
}
p.fix_next_id();
Ok(p)
}
}
#[cfg(test)]
mod tests;
+511
View File
@@ -0,0 +1,511 @@
//! The property tree: groups and properties with stable uids and match ids, addressed by paths.
use effectcraft_keyframe::{Keyframe, Value};
use effectcraft_time::Tick;
use serde::{Deserialize, Serialize};
pub type Uid = u64;
/// How a property is presented and edited.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum ParamUi {
/// Plain number with an optional valid range and a (narrower) slider range.
#[default]
Number,
Slider {
min: f64,
max: f64,
slider_min: f64,
slider_max: f64,
decimals: u8,
},
Percent,
/// Angle in degrees, shown as `revolutions x +degrees`.
Angle,
Pixels,
Point,
Point3,
Color,
Checkbox,
Popup {
options: Vec<String>,
},
Layer,
Path,
Text,
Gradient,
/// Not shown in Effect Controls / the timeline (internal data).
Hidden,
}
/// Expression attached to a property.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Expression {
pub text: String,
pub enabled: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Property {
pub uid: Uid,
/// Stable id within its parent kind (`position`, `blurriness`…).
#[serde(rename = "match")]
pub match_id: String,
pub name: String,
/// Static value (used when there are no keyframes).
pub value: Value,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub keys: Vec<Keyframe>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expr: Option<Expression>,
#[serde(default)]
pub ui: ParamUi,
/// Motion-path semantics (Position, Anchor Point, points).
#[serde(default)]
pub spatial: bool,
/// Only hold keyframes (Source Text, checkboxes, popups).
#[serde(default)]
pub hold_only: bool,
/// Valid only on 3D layers (Orientation, X/Y Rotation…).
#[serde(default)]
pub three_d_only: bool,
/// Valid only on 2D layers.
#[serde(default)]
pub two_d_only: bool,
/// Dimensions shown/edited (2 for 2D position etc.); 0 = all.
#[serde(default)]
pub shown_dims: u8,
/// Can't be keyframed (header-like values, e.g. Mask Mode). Shown without a stopwatch.
#[serde(default)]
pub static_only: bool,
}
impl Property {
pub fn new(uid: Uid, match_id: &str, name: &str, value: Value) -> Property {
let hold_only = !value.interpolates();
Property {
uid,
match_id: match_id.into(),
name: name.into(),
value,
keys: vec![],
expr: None,
ui: ParamUi::Number,
spatial: false,
hold_only,
three_d_only: false,
two_d_only: false,
shown_dims: 0,
static_only: false,
}
}
pub fn with_ui(mut self, ui: ParamUi) -> Property {
self.ui = ui;
self
}
pub fn spatial(mut self) -> Property {
self.spatial = true;
self
}
pub fn is_animated(&self) -> bool {
!self.keys.is_empty()
}
pub fn has_expression(&self) -> bool {
self.expr.as_ref().is_some_and(|e| e.enabled && !e.text.trim().is_empty())
}
/// Keyframed value at `t` (no expression).
pub fn value_at(&self, t: Tick) -> Value {
if self.keys.is_empty() {
return self.value.clone();
}
effectcraft_keyframe::evaluate(&self.keys, t, self.spatial).unwrap_or_else(|| self.value.clone())
}
/// Set the value at `t`: adds/replaces a key when animated, else sets the static value.
pub fn set_value_at(&mut self, t: Tick, v: Value) {
if self.keys.is_empty() {
self.value = v;
} else {
let mut k = Keyframe::new(t, v);
if self.hold_only {
k = k.hold();
}
effectcraft_keyframe::set_key(&mut self.keys, k);
}
}
/// Toggle the stopwatch: on → one key at `t` with the current value; off → keep value at `t`.
pub fn set_animated(&mut self, on: bool, t: Tick) {
if on && self.keys.is_empty() {
let mut k = Keyframe::new(t, self.value.clone());
if self.hold_only {
k = k.hold();
}
self.keys.push(k);
} else if !on && !self.keys.is_empty() {
self.value = self.value_at(t);
self.keys.clear();
}
}
}
/// What a group represents, with its non-animatable header data.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind")]
pub enum GroupKind {
#[default]
Plain,
/// An instance in an indexed list (masks, effects, shape contents, animators): these can be
/// renamed, reordered, duplicated and deleted.
Indexed,
Mask {
mode: MaskMode,
inverted: bool,
color: [u8; 3],
locked: bool,
},
Effect {
/// Effect spec id, e.g. `ec.blur.gaussian`.
effect: String,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum MaskMode {
None,
#[default]
Add,
Subtract,
Intersect,
Lighten,
Darken,
Difference,
}
impl MaskMode {
pub const ALL: [MaskMode; 7] = [MaskMode::None, MaskMode::Add, MaskMode::Subtract, MaskMode::Intersect, MaskMode::Lighten, MaskMode::Darken, MaskMode::Difference];
pub fn label(self) -> &'static str {
match self {
MaskMode::None => "None",
MaskMode::Add => "Add",
MaskMode::Subtract => "Subtract",
MaskMode::Intersect => "Intersect",
MaskMode::Lighten => "Lighten",
MaskMode::Darken => "Darken",
MaskMode::Difference => "Difference",
}
}
pub fn from_name(s: &str) -> Option<MaskMode> {
MaskMode::ALL.into_iter().find(|m| m.label().eq_ignore_ascii_case(s))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PropGroup {
pub uid: Uid,
#[serde(rename = "match")]
pub match_id: String,
pub name: String,
#[serde(default)]
pub kind: GroupKind,
/// fx switch for effects, eye for shape groups, etc.
#[serde(default = "yes")]
pub enabled: bool,
#[serde(default)]
pub children: Vec<Node>,
}
fn yes() -> bool {
true
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "node")]
pub enum Node {
Prop(Property),
Group(PropGroup),
}
impl Node {
pub fn uid(&self) -> Uid {
match self {
Node::Prop(p) => p.uid,
Node::Group(g) => g.uid,
}
}
pub fn match_id(&self) -> &str {
match self {
Node::Prop(p) => &p.match_id,
Node::Group(g) => &g.match_id,
}
}
pub fn name(&self) -> &str {
match self {
Node::Prop(p) => &p.name,
Node::Group(g) => &g.name,
}
}
pub fn as_prop(&self) -> Option<&Property> {
if let Node::Prop(p) = self { Some(p) } else { None }
}
pub fn as_group(&self) -> Option<&PropGroup> {
if let Node::Group(g) = self { Some(g) } else { None }
}
pub fn as_group_mut(&mut self) -> Option<&mut PropGroup> {
if let Node::Group(g) = self { Some(g) } else { None }
}
}
/// One step of a property path.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Seg {
Uid(Uid),
/// Match id and 1-based occurrence among siblings with that match id.
Match(String, usize),
/// 1-based child index.
Index(usize),
}
/// Parse `transform/position`, `effects/#1/blurriness`, `effects/@57/blurriness`,
/// `contents/rect#2/size`.
pub fn parse_path(s: &str) -> Vec<Seg> {
s.split(['/', '.'])
.filter(|x| !x.is_empty())
.map(|seg| {
if let Some(u) = seg.strip_prefix('@').and_then(|u| u.parse().ok()) {
Seg::Uid(u)
} else if let Some(i) = seg.strip_prefix('#').and_then(|u| u.parse().ok()) {
Seg::Index(i)
} else if let Some((m, n)) = seg.rsplit_once('#')
&& let Ok(n) = n.parse()
{
Seg::Match(m.to_string(), n)
} else {
Seg::Match(seg.to_string(), 1)
}
})
.collect()
}
impl PropGroup {
pub fn new(uid: Uid, match_id: &str, name: &str) -> PropGroup {
PropGroup { uid, match_id: match_id.into(), name: name.into(), kind: GroupKind::Plain, enabled: true, children: vec![] }
}
pub fn with(mut self, n: impl Into<Node>) -> PropGroup {
self.children.push(n.into());
self
}
fn child_index(&self, seg: &Seg) -> Option<usize> {
match seg {
Seg::Uid(u) => self.children.iter().position(|c| c.uid() == *u),
Seg::Index(i) => (*i >= 1 && *i <= self.children.len()).then(|| i - 1),
Seg::Match(m, n) => self
.children
.iter()
.enumerate()
.filter(|(_, c)| c.match_id() == m || c.name().eq_ignore_ascii_case(m))
.nth(n.saturating_sub(1))
.map(|(i, _)| i),
}
}
pub fn node(&self, path: &str) -> Option<&Node> {
let segs = parse_path(path);
let (last, init) = segs.split_last()?;
let mut g = self;
for s in init {
g = g.children.get(g.child_index(s)?)?.as_group()?;
}
g.children.get(g.child_index(last)?)
}
pub fn node_mut(&mut self, path: &str) -> Option<&mut Node> {
let segs = parse_path(path);
let (last, init) = segs.split_last()?;
let mut g = self;
for s in init {
let i = g.child_index(s)?;
g = g.children.get_mut(i)?.as_group_mut()?;
}
let i = g.child_index(last)?;
g.children.get_mut(i)
}
pub fn prop(&self, path: &str) -> Option<&Property> {
self.node(path)?.as_prop()
}
pub fn prop_mut(&mut self, path: &str) -> Option<&mut Property> {
match self.node_mut(path)? {
Node::Prop(p) => Some(p),
_ => None,
}
}
pub fn group(&self, path: &str) -> Option<&PropGroup> {
self.node(path)?.as_group()
}
pub fn group_mut(&mut self, path: &str) -> Option<&mut PropGroup> {
self.node_mut(path)?.as_group_mut()
}
/// Direct child property by match id.
pub fn get(&self, match_id: &str) -> Option<&Property> {
self.children.iter().find_map(|c| c.as_prop().filter(|p| p.match_id == match_id))
}
pub fn get_mut(&mut self, match_id: &str) -> Option<&mut Property> {
self.children.iter_mut().find_map(|c| match c {
Node::Prop(p) if p.match_id == match_id => Some(p),
_ => None,
})
}
pub fn sub(&self, match_id: &str) -> Option<&PropGroup> {
self.children.iter().find_map(|c| c.as_group().filter(|g| g.match_id == match_id))
}
pub fn sub_mut(&mut self, match_id: &str) -> Option<&mut PropGroup> {
self.children.iter_mut().find_map(|c| match c {
Node::Group(g) if g.match_id == match_id => Some(g),
_ => None,
})
}
pub fn groups(&self) -> impl Iterator<Item = &PropGroup> {
self.children.iter().filter_map(Node::as_group)
}
pub fn props(&self) -> impl Iterator<Item = &Property> {
self.children.iter().filter_map(Node::as_prop)
}
/// Visit every property depth-first with its uid-path (`@g/@g/@p`).
pub fn walk<'a>(&'a self, prefix: &str, f: &mut dyn FnMut(&str, &'a Property)) {
for c in &self.children {
let p = format!("{prefix}@{}", c.uid());
match c {
Node::Prop(pr) => f(&p, pr),
Node::Group(g) => g.walk(&format!("{p}/"), f),
}
}
}
pub fn walk_mut(&mut self, f: &mut dyn FnMut(&mut Property)) {
for c in &mut self.children {
match c {
Node::Prop(p) => f(p),
Node::Group(g) => g.walk_mut(f),
}
}
}
/// Uid path (`@1/@2/@3`) of the node with `uid`.
pub fn path_of(&self, uid: Uid) -> Option<String> {
for c in &self.children {
if c.uid() == uid {
return Some(format!("@{uid}"));
}
if let Node::Group(g) = c
&& let Some(p) = g.path_of(uid)
{
return Some(format!("@{}/{p}", g.uid));
}
}
None
}
/// Human path (`Transform/Position`) of the node with `uid`.
pub fn name_path_of(&self, uid: Uid) -> Option<String> {
for c in &self.children {
if c.uid() == uid {
return Some(c.name().to_string());
}
if let Node::Group(g) = c
&& let Some(p) = g.name_path_of(uid)
{
return Some(format!("{}/{p}", g.name));
}
}
None
}
/// Find a property anywhere in the tree by uid.
pub fn find(&self, uid: Uid) -> Option<&Property> {
for c in &self.children {
match c {
Node::Prop(p) if p.uid == uid => return Some(p),
Node::Group(g) => {
if let Some(p) = g.find(uid) {
return Some(p);
}
}
_ => {}
}
}
None
}
pub fn find_mut(&mut self, uid: Uid) -> Option<&mut Property> {
for c in &mut self.children {
match c {
Node::Prop(p) if p.uid == uid => return Some(p),
Node::Group(g) => {
if let Some(p) = g.find_mut(uid) {
return Some(p);
}
}
_ => {}
}
}
None
}
pub fn find_group(&self, uid: Uid) -> Option<&PropGroup> {
if self.uid == uid {
return Some(self);
}
self.groups().find_map(|g| g.find_group(uid))
}
pub fn find_group_mut(&mut self, uid: Uid) -> Option<&mut PropGroup> {
if self.uid == uid {
return Some(self);
}
self.children.iter_mut().find_map(|c| match c {
Node::Group(g) => g.find_group_mut(uid),
_ => None,
})
}
/// Parent group of the node with `uid`.
pub fn parent_of_mut(&mut self, uid: Uid) -> Option<&mut PropGroup> {
if self.children.iter().any(|c| c.uid() == uid) {
return Some(self);
}
self.children.iter_mut().find_map(|c| match c {
Node::Group(g) => g.parent_of_mut(uid),
_ => None,
})
}
/// Any property in this subtree animated (keys or expression).
pub fn any_animated(&self) -> bool {
self.children.iter().any(|c| match c {
Node::Prop(p) => p.is_animated() || p.has_expression(),
Node::Group(g) => g.any_animated(),
})
}
/// Re-assign fresh uids (after duplicating a subtree).
pub fn reassign_uids(&mut self, next: &mut Uid) {
*next += 1;
self.uid = *next;
for c in &mut self.children {
match c {
Node::Prop(p) => {
*next += 1;
p.uid = *next;
}
Node::Group(g) => g.reassign_uids(next),
}
}
}
pub fn max_uid(&self) -> Uid {
self.children.iter().map(|c| match c {
Node::Prop(p) => p.uid,
Node::Group(g) => g.max_uid(),
}).fold(self.uid, Uid::max)
}
}
impl From<Property> for Node {
fn from(p: Property) -> Node {
Node::Prop(p)
}
}
impl From<PropGroup> for Node {
fn from(g: PropGroup) -> Node {
Node::Group(g)
}
}
+81
View File
@@ -0,0 +1,81 @@
use effectcraft_keyframe::{Keyframe, ShapePath, Value};
use effectcraft_time::{FrameRate, Tick};
use crate::build::{self, Ids};
use crate::{Comp, ItemKind, LayerSource, MaskMode, Project, Solid};
fn project_with_layer() -> (Project, crate::ItemId) {
let mut p = Project::default();
let comp = Comp::new(1920, 1080, FrameRate::FPS_29_97, Tick::from_seconds_f64(10.0));
let cid = p.add_item("Main", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.clone().into()));
let sid = p.add_item("Red Solid", effectcraft_color::Label::Red, None, ItemKind::Solid(Solid { color: [1.0, 0.0, 0.0], width: 1920, height: 1080, pixel_aspect: 1.0 }));
let layer = build::layer(&mut p, &comp, "Red Solid 1", LayerSource::Solid { item: sid }, (1920, 1080), None);
p.comp_mut(cid).unwrap().layers.push(layer);
(p, cid)
}
#[test]
fn paths_resolve() {
let (p, cid) = project_with_layer();
let l = &p.comp(cid).unwrap().layers[0];
assert_eq!(l.props.prop("transform/position").unwrap().value, Value::Vec3([960.0, 540.0, 0.0]));
assert_eq!(l.props.prop("Transform/Opacity").unwrap().value, Value::Scalar(100.0));
assert_eq!(l.props.prop("transform/#7").unwrap().match_id, "rotation");
let uid = l.props.prop("transform/scale").unwrap().uid;
let path = l.props.path_of(uid).unwrap();
assert_eq!(l.props.prop(&path).unwrap().match_id, "scale");
assert_eq!(l.props.name_path_of(uid).unwrap(), "Transform/Scale");
}
#[test]
fn masks_and_occurrence_paths() {
let (mut p, cid) = project_with_layer();
let mut next = p.next_id;
let m1 = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([0.0, 0.0], 10.0, 10.0), MaskMode::Add, [255, 0, 0]);
let m2 = build::mask(&mut Ids(&mut next), "Mask 2", ShapePath::ellipse([0.0, 0.0], 10.0, 10.0), MaskMode::Subtract, [0, 255, 0]);
p.next_id = next;
let l = &mut p.comp_mut(cid).unwrap().layers[0];
let masks = l.props.sub_mut("masks").unwrap();
masks.children.push(m1.into());
masks.children.push(m2.into());
assert_eq!(l.props.group("masks/mask#2").unwrap().name, "Mask 2");
assert_eq!(l.props.group("masks/Mask 2").unwrap().name, "Mask 2");
assert!(l.props.prop("masks/mask#2/feather").is_some());
}
#[test]
fn animate_and_roundtrip_json() {
let (mut p, cid) = project_with_layer();
{
let l = &mut p.comp_mut(cid).unwrap().layers[0];
let op = l.props.prop_mut("transform/opacity").unwrap();
op.set_animated(true, Tick::ZERO);
op.set_value_at(Tick::from_seconds_f64(1.0), Value::Scalar(0.0));
assert_eq!(op.keys.len(), 2);
assert_eq!(op.value_at(Tick::from_seconds_f64(0.5)), Value::Scalar(50.0));
}
let json = p.to_json();
let q = Project::from_json(&json).unwrap();
assert_eq!(p, q);
let _ = Keyframe::new(Tick::ZERO, Value::Scalar(0.0));
}
#[test]
fn unique_names_and_cycles() {
let (p, cid) = project_with_layer();
let c = p.comp(cid).unwrap();
assert_eq!(c.unique_layer_name("Red Solid 1"), "Red Solid 2");
assert_eq!(c.unique_layer_name("Shape Layer 1"), "Shape Layer 1");
assert!(p.comp_contains(cid, cid));
}
#[test]
fn camera_and_light_layers_build() {
let (mut p, cid) = project_with_layer();
let comp = p.comp(cid).unwrap().clone();
let cam = build::layer(&mut p, &comp, "Camera 1", LayerSource::Camera, (0, 0), None);
assert!(cam.props.prop("cameraOptions/zoom").is_some());
assert!(cam.props.prop("transform/poi").is_some());
let light = build::layer(&mut p, &comp, "Light 1", LayerSource::Light { kind: crate::LightKind::Spot }, (0, 0), None);
assert!(light.props.prop("lightOptions/coneAngle").is_some());
}