From 9f3e8ef8106e67bf29ce79537a35da9114c9f23d Mon Sep 17 00:00:00 2001 From: Bar Borer Date: Tue, 1 Dec 2026 12:21:08 +0200 Subject: [PATCH] Shapes: Add Merge Paths merges what's above it and paints the result (#2889) * Shapes: Add Merge Paths merges what's above it and paints the result (#2175) Co-Authored-By: Claude Opus 5.5 * Tests: check the fix directly instead of assuming history or the tool's colour Co-Authored-By: Claude Opus 5.5 * Shapes: only the Add menu's Merge Paths gets Mode Add and a paint (#2175) Scripts keep Mode Merge and their own list: `layer.addShapeItem` does what it did unless the menu passes `paint`, so the public `append` option goes. Co-Authored-By: Claude Opus 5.5 * Shapes: Add Merge Paths' gradient runs across paths with no paint yet (#2175) Co-Authored-By: Claude Opus 5.5 * Shapes: a Repeater below an added Merge Paths doesn't widen its gradient (#2175) Co-Authored-By: Claude Opus 5.5 * Shapes: a Stroke among the paths doesn't widen an added Merge Paths' gradient (#2175) Co-Authored-By: Claude Opus 5.5 * Shapes: Add > Merge Paths gradient ignores an open line apart from the shapes (#2175) Co-Authored-By: Claude Opus 5.5 * Shapes: format the Merge Paths gradient test (#2175) Co-Authored-By: Claude Opus 5.5 * #2175: saved projects keep their Merge Paths artwork The renderer now drops every draw above a Merge Paths, as After Effects does, so a project saved with painted groups above a Merge Paths and no paint below it reopened blank (and exported blank). Merge Paths gets a hidden Keep Group Paint property. New merges have it off and render the After Effects way. A Merge Paths without it was saved before this change: opening the project adds it on (build::upgrade_shape_contents, next to Wiggle Paths' Spatial Phase), and with it on, or missing, the renderer keeps the pre-#2175 rule (drop only the paint above the merge in its own group, #1174), so saved artwork renders as it did, with or without paint below the merge. Tests: the #1174 pixel assertions come back as a saved-project case in the render tests (as saved and as opened), and an engine test opens a project file in the pre-PR shape, renders it, saves and reopens it. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/layer.rs | 2 +- crates/engine/src/cmd/layer/contents.rs | 48 ++++- crates/engine/src/cmd/prop_groups.rs | 18 +- crates/engine/src/tests/menu_cmds.rs | 194 ++++++++++++++++++ crates/project/src/build.rs | 32 ++- crates/render/src/shapes.rs | 19 +- crates/render/src/shapes/tests.rs | 95 ++++++++- crates/ui-egui/src/panels/timeline.rs | 3 + crates/ui-egui/tests/it/ui_timeline_shapes.rs | 34 +++ 9 files changed, 412 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index de43454f4..9ad89532b 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -209,7 +209,7 @@ pub fn specs() -> Vec { "Add (Shape)", [], None, - "{layer?, kind: group|rect|ellipse|star|polygon|path|fill|stroke|gfill|gstroke|trim|repeater|round|offset|pucker|twist|zigzag|wiggle|wiggler|merge|frontColor|bevelColor|sideColor|backColor, group?: uid|path} → {uid, path} (frontColor…backColor: the group's Front / Bevel / Side / Back item, which colours that surface of every extruded paint in the group in Advanced 3D)", + "{layer?, kind: group|rect|ellipse|star|polygon|path|fill|stroke|gfill|gstroke|trim|repeater|round|offset|pucker|twist|zigzag|wiggle|wiggler|merge|frontColor|bevelColor|sideColor|backColor, group?: uid|path, paint?: bool} → {uid, path} (frontColor…backColor: the group's Front / Bevel / Side / Back item, which colours that surface of every extruded paint in the group in Advanced 3D; merge with paint: Mode Add, below the last path or group, with the Tools bar's Stroke and Fill below it if no paint is there)", has_layers, add_shape_item ), diff --git a/crates/engine/src/cmd/layer/contents.rs b/crates/engine/src/cmd/layer/contents.rs index 3015f4ecf..36f6f6053 100644 --- a/crates/engine/src/cmd/layer/contents.rs +++ b/crates/engine/src/cmd/layer/contents.rs @@ -3,6 +3,8 @@ use super::{ EngineError, GroupKind, Ids, ItemId, KV, LayerId, MaskMode, Node, Project, PropGroup, Result, Session, TextDoc, Value, b_p, bad, build, json, layer_mut, layer_p, merge_p, str_p, }; +use crate::cmd::shape_tool::ShapeTool; +use effectcraft_time::Tick; /// Add a tool-shaped mask in one document edit, then request its Timeline controls separately. pub(super) fn add_mask(s: &mut Session, p: &Value) -> Result { @@ -97,7 +99,10 @@ pub(super) fn add_shape_item(s: &mut Session, p: &Value) -> Result { ), v => v.and_then(Value::as_u64), }; - let uid = s.edit("Add Shape Item", None, |proj, _| { + // The Add menu's Merge Paths. Scripts and importers build the list themselves and keep Merge. + let paint = kind == "merge" && b_p(p, "paint") == Some(true); + let time = s.time_of(cid); + let uid = s.edit("Add Shape Item", None, |proj, st| { let mut next = proj.next_id; let mut ids = Ids(&mut next); // Front / Bevel / Side / Back ▸ property: into the group's surface item (one per group). @@ -120,7 +125,7 @@ pub(super) fn add_shape_item(s: &mut Session, p: &Value) -> Result { proj.next_id = next; return Ok(uid); } - let g = match kind.as_str() { + let mut g = match kind.as_str() { "group" => build::shape_group(&mut ids, "Group 1", vec![]), "rect" | "rectangle" => build::shape_rect(&mut ids, [200.0, 200.0], [0.0, 0.0], 0.0), "ellipse" => build::shape_ellipse(&mut ids, [200.0, 200.0], [0.0, 0.0]), @@ -136,6 +141,18 @@ pub(super) fn add_shape_item(s: &mut Session, p: &Value) -> Result { k => build::shape_simple_op(&mut ids, k).ok_or_else(|| bad("layer.addShapeItem", format!("unknown kind `{k}`")))?, }; let uid = g.uid; + if paint { + // Mode Add, as a new Merge Paths has in After Effects. + if let Some(mode) = g.get_mut("mode") { + mode.value = KV::Enum(1); + } + let paints = merge_paints(proj, cid, lid, group_uid, time, &mut ids, &st.shape_tool)?; + proj.next_id = next; + let target = shape_item_target(proj, cid, lid, group_uid)?; + let at = crate::cmd::prop_groups::after_last_path(target); + target.children.splice(at..at, std::iter::once(g).chain(paints).map(Node::from)); + return Ok(uid); + } proj.next_id = next; shape_item_target(proj, cid, lid, group_uid)?.children.push(g.into()); Ok(uid) @@ -145,6 +162,33 @@ pub(super) fn add_shape_item(s: &mut Session, p: &Value) -> Result { Ok(json!({"uid": uid, "path": path})) } +/// The paint a new Merge Paths in the shape item target needs: the renderer paints the merged path +/// with the paint items below it alone, so with none below where it goes, the Tools bar's Stroke +/// and Fill (gradients run across what the merge takes in). +fn merge_paints(proj: &mut Project, cid: ItemId, lid: LayerId, group_uid: Option, time: Tick, ids: &mut Ids, tool: &ShapeTool) -> Result> { + let mut target = shape_item_target(proj, cid, lid, group_uid)?.clone(); + let at = crate::cmd::prop_groups::after_last_path(&target); + if target.children.get(at..).is_some_and(|below| below.iter().any(crate::cmd::prop_groups::is_paint)) { + return Ok(vec![]); + } + // (bounds cover painted paths only: a stand-in merge drops the paints among them, a stand-in Fill + // below it counts those with no paint yet, and what's below the merge, a Repeater say, doesn't + // reach what it takes in) + target.children.truncate(at); + let mut merge = build::shape_simple_op(ids, "merge").ok_or_else(|| bad("layer.addShapeItem", "unknown kind `merge`"))?; + // Mode Add, as the inserted merge has, so the bounds match what it renders. + if let Some(mode) = merge.get_mut("mode") { + mode.value = KV::Enum(1); + } + target.children.push(merge.into()); + target.children.push(build::shape_fill(ids, [1.0; 4]).into()); + let comp = proj.comp(cid).ok_or(EngineError::NoComp)?; + let layer = comp.layer(lid).ok_or(EngineError::NoComp)?; + let ctx = effectcraft_render::EvalCtx::new(proj, cid, comp, time); + let bounds = effectcraft_render::shapes::content_bounds(&ctx, layer, &target).map_or([-50.0, -50.0, 100.0, 100.0], |r| [r.x0, r.y0, r.width(), r.height()]); + Ok(crate::cmd::shape_tool::paint_items(ids, tool, bounds)) +} + /// The contents a new shape item goes into: the shape group `group_uid` (its Contents), else the /// layer's Contents. fn shape_item_target(proj: &mut Project, cid: ItemId, lid: LayerId, group_uid: Option) -> Result<&mut PropGroup> { diff --git a/crates/engine/src/cmd/prop_groups.rs b/crates/engine/src/cmd/prop_groups.rs index b3e9baf14..560847c06 100644 --- a/crates/engine/src/cmd/prop_groups.rs +++ b/crates/engine/src/cmd/prop_groups.rs @@ -261,12 +261,18 @@ pub(crate) fn paste_contents(s: &mut Session, p: &Value) -> Result { /// paints still draw the merged path (the renderer drops the draws above a Merge Paths), else after /// the last path item. fn merge_spot(contents: &PropGroup) -> usize { - let is = |n: &Node, ids: &[&str]| matches!(n, Node::Group(g) if ids.contains(&g.match_id.as_str())); - let paints = ["fill", "stroke", "gfill", "gstroke"]; - match contents.children.iter().position(|n| is(n, &paints)) { - Some(i) => i, - None => contents.children.iter().rposition(|n| is(n, &["rect", "ellipse", "star", "path"])).map_or(0, |i| i + 1), - } + contents.children.iter().position(is_paint).unwrap_or_else(|| after_last_path(contents)) +} + +/// A Fill, Stroke, Gradient Fill or Gradient Stroke item. +pub(super) fn is_paint(n: &Node) -> bool { + matches!(n, Node::Group(g) if ["fill", "stroke", "gfill", "gstroke"].contains(&g.match_id.as_str())) +} + +/// Just below the last path or group of `contents`: a Merge Paths here takes them all in. +pub(super) fn after_last_path(contents: &PropGroup) -> usize { + let is_path = |n: &Node| matches!(n, Node::Group(g) if ["rect", "ellipse", "star", "path", "group"].contains(&g.match_id.as_str())); + contents.children.iter().rposition(is_path).map_or(0, |i| i + 1) } /// Edit ▸ Duplicate with shape items, text animators or selectors selected: each is copied in diff --git a/crates/engine/src/tests/menu_cmds.rs b/crates/engine/src/tests/menu_cmds.rs index 4cf0a4205..ed281b2ab 100644 --- a/crates/engine/src/tests/menu_cmds.rs +++ b/crates/engine/src/tests/menu_cmds.rs @@ -1805,6 +1805,200 @@ fn pasted_merge_paths_keeps_the_targets_paint() { assert_eq!(opaque_centroid(&s).2, before); } +/// A new shape layer's Contents names after adding `items` and then Add ▸ Merge Paths. +fn with_added_merge(s: &mut Session, items: &[&str]) -> (u64, Vec) { + let l = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + for kind in items { + s.execute("layer.addShapeItem", json!({"layer": l, "kind": kind})).unwrap(); + } + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "merge", "paint": true})).unwrap(); + (l, contents_names(s, l)) +} + +/// Add ▸ Merge Paths takes in every path and group above it, whatever stands around them, and +/// paints the result: Mode Add, the paint below it kept, or the Tools bar's added in one undo step +/// (#2175). +#[test] +fn add_merge_paths_goes_below_the_paths_and_paints_the_result() { + let mut s = comp(); + // No paint: the Tools bar's Fill follows it (Stroke Width is 0 by default, so no Stroke). + let (l, names) = with_added_merge(&mut s, &["rect", "ellipse"]); + assert_eq!(names, ["Rectangle Path 1", "Ellipse Path 1", "Merge Paths 1", "Fill 1"]); + let contents = layer(&s, l).props.sub("contents").unwrap().clone(); + let merge = contents.groups().find(|g| g.match_id == "merge").unwrap(); + assert_eq!(merge.get("mode").unwrap().value, KV::Enum(1), "Mode Add"); + let fill = contents.groups().find(|g| g.match_id == "fill").unwrap(); + let [r, g, b] = s.state.shape_tool.fill.color; + assert_eq!(fill.get("color").unwrap().value.as_color(), [r, g, b, 1.0]); + s.execute("edit.undo", json!({})).unwrap(); + assert_eq!(contents_names(&s, l), ["Rectangle Path 1", "Ellipse Path 1"], "one undo step"); + // Groups count as paths, and a paint below them is kept, with nothing added. + let (_, names) = with_added_merge(&mut s, &["rect", "group", "fill"]); + assert_eq!(names, ["Rectangle Path 1", "Group 1", "Merge Paths 1", "Fill 1"]); + // A paint between the paths stays above the merge and goes with them; a new one is added. + let (_, names) = with_added_merge(&mut s, &["rect", "fill", "ellipse"]); + assert_eq!(names, ["Rectangle Path 1", "Fill 1", "Ellipse Path 1", "Merge Paths 1", "Fill 1"]); + // Both of the Tools bar's paints, Stroke first as on a drawn shape. + s.execute("shape.toolOptions", json!({"strokeWidth": 3, "stroke": "#00ff00"})).unwrap(); + let (_, names) = with_added_merge(&mut s, &["rect"]); + assert_eq!(names, ["Rectangle Path 1", "Merge Paths 1", "Stroke 1", "Fill 1"]); + // Scripts build the list themselves, and keep Merge. + let a = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.addShapeItem", json!({"layer": a, "kind": "rect"})).unwrap(); + s.execute("layer.addShapeItem", json!({"layer": a, "kind": "fill"})).unwrap(); + s.execute("layer.addShapeItem", json!({"layer": a, "kind": "merge"})).unwrap(); + assert_eq!(contents_names(&s, a), ["Rectangle Path 1", "Fill 1", "Merge Paths 1"]); + let contents = layer(&s, a).props.sub("contents").unwrap().clone(); + assert_eq!(contents.groups().find(|g| g.match_id == "merge").unwrap().get("mode").unwrap().value, KV::Enum(0), "Mode Merge"); +} + +/// Opaque pixels of the active comp's first frame. +fn opaque_pixels(s: &Session) -> u32 { + let img = s.render(s.active_comp_id().unwrap(), Tick::ZERO, Default::default()); + let mut n = 0u32; + for y in 0..img.height { + for x in 0..img.width { + n += u32::from(img.get(x as i64, y as i64)[3] > 0.5); + } + } + n +} + +/// Removes every property `id` from a project file's property trees; returns how many it removed. +fn strip_prop(v: &mut Value, id: &str) -> usize { + let mut removed = 0; + let mut todo = vec![v]; + while let Some(v) = todo.pop() { + match v { + Value::Array(a) => { + let before = a.len(); + a.retain(|c| c.get("match").and_then(Value::as_str) != Some(id)); + removed += before - a.len(); + todo.extend(a.iter_mut()); + } + Value::Object(o) => todo.extend(o.values_mut()), + _ => {} + } + } + removed +} + +/// A project saved before #2175 with two groups and then Merge Paths in a shape layer's +/// Contents, each group a rectangle with its own Fill and no paint below the merge: Merge Paths had +/// Mode alone then, and the renderer kept the groups' paint. Reopened, and saved and reopened +/// again, it renders that artwork still; a Merge Paths made now renders the AE way, nothing without +/// a paint below it (#2175). +#[test] +fn saved_merge_paths_below_painted_groups_keeps_its_artwork() { + let mut s = comp(); + let l = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + for x in [-30, 30] { + let group = s.execute("layer.addShapeItem", json!({"layer": l, "kind": "group"})).unwrap(); + let uid = group["uid"].as_u64().unwrap(); + let rect = s.execute("layer.addShapeItem", json!({"layer": l, "kind": "rect", "group": uid})).unwrap()["path"].as_str().unwrap().to_string(); + s.execute("prop.set", json!({"layer": l, "path": format!("{rect}/position"), "value": [x, 0]})).unwrap(); + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "fill", "group": uid})).unwrap(); + } + let painted = opaque_pixels(&s); + assert!(painted > 0, "the groups render"); + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "merge"})).unwrap(); + assert_eq!(contents_names(&s, l), ["Group 1", "Group 1", "Merge Paths 1"]); + assert_eq!(opaque_pixels(&s), 0, "a new Merge Paths takes the groups' paint in with their paths"); + + // The file as the version before #2175 wrote it. + let mut old: Value = serde_json::from_str(&s.project.to_file_json().unwrap()).unwrap(); + assert_eq!(strip_prop(&mut old, effectcraft_project::build::MERGE_KEEP_GROUP_PAINT), 1); + let dir = std::env::temp_dir().join(format!("ec-saved-merge-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("old.ecproj").to_string_lossy().to_string(); + std::fs::write(&path, serde_json::to_string_pretty(&old).unwrap()).unwrap(); + + let mut s2 = Session::default(); + s2.execute("file.open", json!({"path": path})).unwrap(); + assert_eq!(opaque_pixels(&s2), painted, "the saved artwork still renders"); + let again = dir.join("again.ecproj").to_string_lossy().to_string(); + s2.execute("file.save", json!({"path": again})).unwrap(); + let mut s3 = Session::default(); + s3.execute("file.open", json!({"path": again})).unwrap(); + assert_eq!(opaque_pixels(&s3), painted, "and still does once saved again"); + std::fs::remove_dir_all(&dir).ok(); +} + +/// The gradient Add ▸ Merge Paths brings runs across what the merge takes in, in the space of the +/// group it goes into, painted or not (#2175). +#[test] +fn add_merge_paths_gradient_runs_across_its_inputs() { + let mut s = comp(); + s.execute("shape.toolOptions", json!({"fillType": "linear"})).unwrap(); + let ends = |s: &Session, l: u64, group: Option| { + let l = layer(s, l); + let contents = l.props.sub("contents").unwrap(); + let contents = group.map_or(contents, |g| contents.find_group(g).unwrap().sub("contents").unwrap()); + let fill = contents.groups().filter(|g| g.match_id == "gfill").last().unwrap(); + (fill.get("start").unwrap().value.components(), fill.get("end").unwrap().value.components()) + }; + // Into a moved, scaled group: its own space, not the layer's. + let l = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + let group = s.execute("layer.addShapeItem", json!({"layer": l, "kind": "group"})).unwrap(); + let (uid, path) = (group["uid"].as_u64().unwrap(), group["path"].as_str().unwrap().to_string()); + s.execute("prop.set", json!({"layer": l, "path": format!("{path}/transform/position"), "value": [500, 0]})).unwrap(); + s.execute("prop.set", json!({"layer": l, "path": format!("{path}/transform/scale"), "value": [50, 50]})).unwrap(); + for kind in ["rect", "fill", "rect"] { + s.execute("layer.addShapeItem", json!({"layer": l, "kind": kind, "group": uid})).unwrap(); + } + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "merge", "paint": true, "group": uid})).unwrap(); + assert_eq!(ends(&s, l, Some(uid)), (vec![-100.0, 0.0], vec![100.0, 0.0])); + // Paths with no paint yet. + let (l, _) = with_added_merge(&mut s, &["rect"]); + assert_eq!(ends(&s, l, None), (vec![-100.0, 0.0], vec![100.0, 0.0])); + // A Repeater below the merge repeats the gradient with each copy: it spans one. + let (l, _) = with_added_merge(&mut s, &["rect", "repeater"]); + assert_eq!(ends(&s, l, None), (vec![-100.0, 0.0], vec![100.0, 0.0])); + // A Stroke among the paths goes with them: its width doesn't widen the gradient. + let (l, _) = with_added_merge(&mut s, &["rect", "stroke", "rect"]); + assert_eq!(ends(&s, l, None), (vec![-100.0, 0.0], vec![100.0, 0.0])); +} + +/// The gradient is measured with the same Mode Add the inserted merge has: an open line apart from +/// the shapes adds no area under Add, so it doesn't stretch the gradient (#2175). +#[test] +fn add_merge_paths_gradient_ignores_an_open_line_apart() { + use effectcraft_keyframe::{ShapePath, Value}; + let mut s = comp(); + s.execute("shape.toolOptions", json!({"fillType": "linear"})).unwrap(); + let l = s.execute("layer.newShape", json!({"kind": "none"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "rect"})).unwrap(); + let line = s.execute("layer.addShapeItem", json!({"layer": l, "kind": "path"})).unwrap()["path"].as_str().unwrap().to_string(); + let open = ShapePath { + vertices: vec![[800.0, 0.0], [900.0, 0.0]], + in_tangents: vec![[0.0; 2]; 2], + out_tangents: vec![[0.0; 2]; 2], + closed: false, + feather: Vec::new(), + }; + s.execute("prop.set", json!({"layer": l, "path": format!("{line}/path"), "value": Value::Path(open).to_json()})).unwrap(); + s.execute("layer.addShapeItem", json!({"layer": l, "kind": "merge", "paint": true})).unwrap(); + let l = layer(&s, l); + let fill = l.props.sub("contents").unwrap().groups().filter(|g| g.match_id == "gfill").last().unwrap().clone(); + assert_eq!((fill.get("start").unwrap().value.components(), fill.get("end").unwrap().value.components()), (vec![-100.0, 0.0], vec![100.0, 0.0])); +} + +/// Pasted with nothing selected, Merge Paths goes below the groups too, not above them where it +/// would take in nothing (#2175). +#[test] +fn pasted_merge_paths_goes_below_the_targets_groups() { + let mut s = comp(); + let a = s.execute("layer.newShape", json!({"kind": "none", "name": "A"})).unwrap()["layer"].as_u64().unwrap(); + let merge = s.execute("layer.addShapeItem", json!({"layer": a, "kind": "merge"})).unwrap()["uid"].as_u64().unwrap(); + let b = s.execute("layer.newShape", json!({"kind": "none", "name": "B"})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.addShapeItem", json!({"layer": b, "kind": "group"})).unwrap(); + s.execute("prop.select", json!({"layer": a, "prop": merge})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("layer.select", json!({"layers": [b]})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert_eq!(contents_names(&s, b), ["Group 1", "Merge Paths 1"]); +} + /// Edit ▸ Duplicate with shape items selected duplicates them in their layer, above the /// original and named "Rectangle 2", not the layer (#227). #[test] diff --git a/crates/project/src/build.rs b/crates/project/src/build.rs index 7a960dbfb..ac70be1d0 100644 --- a/crates/project/src/build.rs +++ b/crates/project/src/build.rs @@ -619,27 +619,35 @@ pub fn shape_simple_op(ids: &mut Ids, kind: &str) -> Option { .with(ids.prop("seed", "Random Seed", Value::Scalar(0.0))) .with(tr) } - "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", - ]))), + "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"]))) + .with(merge_keep_group_paint(ids, false)), _ => return None, }; Some(g) } +/// Merge Paths' hidden Keep Group Paint: whether the fills and strokes inside the groups above it +/// keep rendering. Off, as in After Effects, the merge takes them in with their paths and only the +/// paint below it renders (#2175). A Merge Paths saved before #2175 has no such property and gets it +/// on, so its artwork renders as it did when it was saved ([`upgrade_shape_contents`]). +fn merge_keep_group_paint(ids: &mut Ids, on: bool) -> Property { + ids.prop(MERGE_KEEP_GROUP_PAINT, "Keep Group Paint", Value::Bool(on)).with_ui(ParamUi::Hidden) +} + +/// Match id of Merge Paths' hidden Keep Group Paint ([`merge_keep_group_paint`]). +pub const MERGE_KEEP_GROUP_PAINT: &str = "keepGroupPaint"; + /// Wiggle Paths' Spatial Phase. fn wiggle_spatial_phase(ids: &mut Ids) -> Property { ids.prop("spatialPhase", "Spatial Phase", Value::Scalar(0.0)).with_ui(ParamUi::Angle) } /// Adds the properties that shape path operations have gained since a project was saved (Wiggle -/// Paths' Spatial Phase), at their defaults, to the operations in `contents` and its nested -/// groups. Returns whether anything was added. It walks the nested groups with a work list and -/// does not recurse. +/// Paths' Spatial Phase at its default; Merge Paths' Keep Group Paint on, which keeps the +/// rendering it was saved with, #2175), to the operations in `contents` and its nested groups. +/// Returns whether anything was added. It walks the nested groups with a work list and does not +/// recurse. pub fn upgrade_shape_contents(ids: &mut Ids, contents: &mut PropGroup) -> bool { let mut changed = false; let mut todo = vec![contents]; @@ -651,6 +659,10 @@ pub fn upgrade_shape_contents(ids: &mut Ids, contents: &mut PropGroup) -> bool { g.children.insert(at, wiggle_spatial_phase(ids).into()); changed = true; } + if g.match_id == "merge" && !g.children.iter().any(|c| c.match_id() == MERGE_KEEP_GROUP_PAINT) { + g.children.push(merge_keep_group_paint(ids, true).into()); + changed = true; + } todo.push(g); } } diff --git a/crates/render/src/shapes.rs b/crates/render/src/shapes.rs index df92846ce..f83ecea00 100644 --- a/crates/render/src/shapes.rs +++ b/crates/render/src/shapes.rs @@ -60,8 +60,8 @@ struct Draw { /// Front / Bevel / Side / Back colours of the paint's extrusion (Advanced 3D). surfaces: SurfaceColors, /// Paint item of the contents group this draw was collected in (as opposed to one bubbled up - /// from a nested group). Merge Paths drops only these paints above it (#1174); a group's own - /// fill or stroke keeps rendering inside the group. + /// from a nested group). A Merge Paths saved before #2175 (Keep Group Paint on) drops only + /// these paints above it, as the renderer did then (#1174). local: bool, } @@ -417,10 +417,17 @@ fn collect_in(ctx: &EvalCtx, layer: &Layer, contents: &PropGroup, arena: &mut Ve let input: Vec = live.iter().map(|&i| arena[i].clone()).collect(); arena.push(ops::merge(&input, mode)); live = vec![arena.len() - 1]; - // As in After Effects, fills and strokes above a Merge Paths in its group are not - // rendered: the merged path is painted by the paint items below it. Paint inside - // groups above the merge still renders — it belongs to those groups (#1174). - draws.retain(|d| !d.local); + // As in After Effects, the merged path replaces its inputs and only the paint items + // below it paint it: every draw so far paints inputs of this merge, in its own group + // or in the groups above it, so none of them renders (#2175). A Merge Paths saved + // before that (Keep Group Paint on, or no such property) keeps the paint inside the + // groups above it, so saved artwork renders as it did (#1174). + let keep_groups = ctx.group_value(layer, g, effectcraft_project::build::MERGE_KEEP_GROUP_PAINT).is_none_or(|v| v.as_bool()); + if keep_groups { + draws.retain(|d| !d.local); + } else { + draws.clear(); + } } "group" => { let Some(inner) = g.sub("contents") else { continue }; diff --git a/crates/render/src/shapes/tests.rs b/crates/render/src/shapes/tests.rs index ba7028a25..ae13264a4 100644 --- a/crates/render/src/shapes/tests.rs +++ b/crates/render/src/shapes/tests.rs @@ -76,24 +76,103 @@ fn merge_add_feeds_fill_below_and_drops_paint_above() { assert!((coverage(&img) - 80.0 * 40.0).abs() < 20.0, "{}", coverage(&img)); } -/// #1174: Adding Merge Paths to a shape layer's Contents, after the group that holds the -/// shape and its paint, erased the render. The merge drops paints above it *in its group* — -/// not paint that belongs to a group above it. +/// A shape layer's Contents of two whole groups, each with its own red fill, and a Merge Paths in +/// `mode`, with a green fill below it if `fill`. The rectangles span x 70..110 (on top) and 90..130. +fn merged_groups(mode: u32, fill: bool) -> Image { + let (p, cid) = shape_comp(|ids| { + let (r1, f1) = (build::shape_rect(ids, [40.0, 40.0], [-10.0, 0.0], 0.0), build::shape_fill(ids, RED)); + let (r2, f2) = (build::shape_rect(ids, [40.0, 40.0], [10.0, 0.0], 0.0), build::shape_fill(ids, RED)); + let mut items = vec![ + build::shape_group(ids, "Group 1", vec![r1, f1]), + build::shape_group(ids, "Group 2", vec![r2, f2]), + op(ids, "merge", &[("mode", Value::Enum(mode))]), + ]; + if fill { + items.push(build::shape_fill(ids, GREEN)); + } + items + }); + frame(&p, cid) +} + +/// #2175: Merge Paths below whole groups merges them. Their paths go into the merge and their own +/// paints stop rendering, so the paint below it alone paints the result, in every mode. #[test] -fn merge_paths_below_a_group_keeps_the_group_paint() { - for mode in [0u32, 1] { +fn merge_paths_below_groups_merges_them_in_every_mode() { + // Mode, area, and whether the top rectangle's own part, the overlap and the other's own part + // are covered. + let cases = [ + (0, 60.0 * 40.0, [true, true, true]), + (1, 60.0 * 40.0, [true, true, true]), + (2, 20.0 * 40.0, [true, false, false]), + (3, 20.0 * 40.0, [false, true, false]), + (4, 40.0 * 40.0, [true, false, true]), + ]; + for (mode, area, covered) in cases { + let img = merged_groups(mode, true); + assert!((coverage(&img) - area).abs() < 20.0, "mode {mode}: {}", coverage(&img)); + for (x, inside) in [80, 100, 120].into_iter().zip(covered) { + let c = img.get(x, 50); + assert_eq!(c[3] > 0.99, inside, "mode {mode} at x {x}: {c:?}"); + assert!(c[0] < 0.01, "mode {mode} at x {x}: the groups' red does not render: {c:?}"); + } + } +} + +/// A Merge Paths with no paint below it paints nothing: the paint above it, in the groups too, has +/// gone with its paths into the merge. Add ▸ Merge Paths adds the paint (#2175). +#[test] +fn merge_paths_with_no_paint_below_renders_nothing() { + for mode in 0..5 { + assert_eq!(coverage(&merged_groups(mode, false)), 0.0, "mode {mode}"); + } +} + +/// #1174, for projects saved before #2175: a Merge Paths below a group that holds the shape and its +/// paint kept the group's paint rendering. Saved that way (Mode alone, no Keep Group Paint), and +/// opened (Keep Group Paint added on), the group rectangle still renders, also with a paint above +/// the merge in its own group, which it drops as it did. +#[test] +fn merge_paths_saved_before_2175_keeps_the_group_paint() { + for (mode, opened) in [(0u32, false), (1, false), (0, true), (1, true)] { let (p, cid) = shape_comp(|ids| { let rect = build::shape_rect(ids, [40.0, 40.0], [0.0, 0.0], 0.0); let fill = build::shape_fill(ids, RED); - vec![build::shape_group(ids, "Group 1", vec![rect, fill]), op(ids, "merge", &[("mode", Value::Enum(mode))])] + let mut contents = ids.group("contents", "Contents"); + contents.children.push(build::shape_group(ids, "Group 1", vec![rect, fill]).into()); + contents.children.push(build::shape_rect(ids, [20.0, 20.0], [60.0, 0.0], 0.0).into()); + contents.children.push(build::shape_fill(ids, GREEN).into()); + let mut merge = op(ids, "merge", &[("mode", Value::Enum(mode))]); + merge.children.retain(|c| c.match_id() != build::MERGE_KEEP_GROUP_PAINT); + contents.children.push(merge.into()); + if opened { + assert!(build::upgrade_shape_contents(ids, &mut contents)); + let merge = contents.groups().find(|g| g.match_id == "merge").unwrap(); + assert_eq!(merge.get(build::MERGE_KEEP_GROUP_PAINT).unwrap().value, Value::Bool(true)); + assert!(!build::upgrade_shape_contents(ids, &mut contents), "once"); + } + contents.groups().cloned().collect() }); let img = frame(&p, cid); let c = img.get(100, 50); - assert!(c[0] > 0.99 && c[1] < 0.01 && c[3] > 0.99, "mode {mode}: group rectangle must still render, got {c:?}"); - assert!((coverage(&img) - 40.0 * 40.0).abs() < 20.0, "mode {mode}: {}", coverage(&img)); + assert!(c[0] > 0.99 && c[1] < 0.01 && c[3] > 0.99, "mode {mode}, opened {opened}: group rectangle must still render, got {c:?}"); + assert!((coverage(&img) - 40.0 * 40.0).abs() < 20.0, "mode {mode}, opened {opened}: {}", coverage(&img)); + assert!(alpha(&img, 160, 50) < 0.01, "mode {mode}, opened {opened}: the Fill above the merge in its own group is dropped"); } } +/// A Merge Paths made now has Keep Group Paint off and isn't upgraded: the saved-project +/// compatibility above leaves new merges alone (#2175). +#[test] +fn new_merge_paths_has_keep_group_paint_off() { + let mut next = 1; + let mut ids = Ids(&mut next); + let merge = build::shape_simple_op(&mut ids, "merge").unwrap(); + assert_eq!(merge.get(build::MERGE_KEEP_GROUP_PAINT).unwrap().value, Value::Bool(false)); + let mut contents = ids.group("contents", "Contents").with(merge); + assert!(!build::upgrade_shape_contents(&mut ids, &mut contents)); +} + #[test] fn merge_subtract_and_intersect() { let sub = |mode: u32| { diff --git a/crates/ui-egui/src/panels/timeline.rs b/crates/ui-egui/src/panels/timeline.rs index 4ae1a96f4..101e05c95 100644 --- a/crates/ui-egui/src/panels/timeline.rs +++ b/crates/ui-egui/src/panels/timeline.rs @@ -5451,6 +5451,9 @@ fn shape_add_popup( && let Some((kind, _)) = SHAPE_ADD_ITEMS.get(i).filter(|(k, _)| *k != "-") { let mut params = json!({"layer": layer.id.0, "kind": kind}); + if *kind == "merge" { + params["paint"] = json!(true); + } // Into the selected shape group, as After Effects does. let group = app.session.state.selected_props.iter().filter(|(l, _)| *l == layer.id).find_map(|(_, u)| { let g = layer.props.find_group(*u)?; diff --git a/crates/ui-egui/tests/it/ui_timeline_shapes.rs b/crates/ui-egui/tests/it/ui_timeline_shapes.rs index 5dcafad3a..38fc4adcb 100644 --- a/crates/ui-egui/tests/it/ui_timeline_shapes.rs +++ b/crates/ui-egui/tests/it/ui_timeline_shapes.rs @@ -6,6 +6,8 @@ use effectcraft_engine::Session; use effectcraft_engine::project::LayerId; +use effectcraft_engine::render::RenderOpts; +use effectcraft_time::Tick; use effectcraft_ui_egui::{Dialog, EffectcraftApp}; use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; use egui_kittest::Harness; @@ -95,6 +97,38 @@ fn shape_contents_add_menu_adds_wiggle_transform() { assert_eq!(items, ["group", "wiggler"]); } +/// #2175: two shapes drawn with the tool, Add ▸ Merge Paths on the layer's Contents and Mode +/// Subtract: the layer's list merges them, with a paint, and the top shape gets a hole. +#[test] +fn shape_contents_add_menu_merges_two_tool_shapes() { + let mut s = session(); + let l = + s.execute("shape.newShape", json!({"kind": "rect", "size": [40, 40], "position": [160, 90], "fill": "#ff0000"})).unwrap()["layer"].as_u64().unwrap(); + // The newest shape goes on top of the list. + s.execute("shape.newShape", json!({"kind": "rect", "size": [100, 100], "position": [160, 90], "fill": "#ff0000"})).unwrap(); + let contents = s.active_comp().unwrap().layer(LayerId(l)).unwrap().props.sub("contents").unwrap().uid; + let mut h = harness(s); + open_layer(&mut h, l); + click(&mut h, &format!("timeline.group.{contents}.add")); + let entry = h.get_by_label("Merge Paths").rect(); + click_at(&mut h, entry.center()); + let s = &mut h.state_mut().session; + let layer = s.active_comp().unwrap().layer(LayerId(l)).unwrap().clone(); + let c = layer.props.sub("contents").unwrap(); + let items: Vec<&str> = c.groups().map(|g| g.match_id.as_str()).collect(); + assert_eq!(items, ["group", "group", "merge", "fill"]); + let cid = s.active_comp_id().unwrap(); + let frame = |s: &Session| s.render(cid, Tick::ZERO, RenderOpts::default()); + // Mode Add: the new fill alone paints the union. + s.execute("prop.set", json!({"layer": l, "path": "contents/fill/color", "value": [0.0, 0.0, 1.0, 1.0]})).unwrap(); + let added = frame(s).get(160, 90); + assert!(added[2] > added[0] && added[3] > 0.99, "the merged path takes the new blue fill, not the groups' red: {added:?}"); + s.execute("prop.set", json!({"layer": l, "path": "contents/merge/mode", "value": 2})).unwrap(); + let img = frame(s); + assert!(img.get(160, 90)[3] < 0.01, "Subtract cuts a hole: {:?}", img.get(160, 90)); + assert!(img.get(120, 90)[3] > 0.99, "and keeps the rest: {:?}", img.get(120, 90)); +} + /// A shape group's inner Contents is elided in After Effects: opening the group lists its items /// (here the path) directly, with no "Contents" row between them. #[test]