diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 96ce1679..c1b35195 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -178,6 +178,7 @@ pub(crate) fn evaluate_symbol(doc: &Document, tl: &Timeline, frame: u32, xf: Aff let mut out = DisplayList::default(); let mut cx = Ctx::top(xf); cx.depth = 1; + cx.stage = false; eval_timeline(doc, tl, frame, &cx, &mut out, play); out } @@ -300,6 +301,9 @@ struct Ctx { /// The top-level layer and element everything inside belongs to (for picking). root: Option<(LayerId, ElementId)>, outline: Option, + /// The stage as edited (ADR 0061): layers in outline mode are drawn as outlines. Off for + /// the movie (every export, the player): View as Outlines is an editing aid. + stage: bool, /// The clip everything inside is drawn within. clip: Option, /// Set while evaluating mask artwork: everything inside forms this clip. @@ -318,12 +322,13 @@ struct Ctx { impl Ctx { fn top(xf: Affine) -> Ctx { - Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } + Ctx { xf, color: ColorTransform::IDENTITY, depth: 0, root: None, outline: None, stage: true, clip: None, masks: None, guide: false, group: None, camera: None, slice: None } } /// A main timeline seen through `camera`: its tint colours everything. fn through(camera: Option) -> Ctx { let mut cx = Ctx::top(Affine::IDENTITY); + cx.stage = false; if let Some(c) = camera { cx.color = c.color(); cx.camera = Some(c); @@ -418,7 +423,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut // A layer guided by a guide layer: its tweens follow the guide's first path. let walk = layer.parent.and_then(|p| tl.layer(p)).filter(|g| g.kind == LayerKind::Guide).and_then(|g| guide_walk(g, frame)); let Some((kf_start, elements)) = evaluate_guided(layer, frame, walk.as_ref()) else { continue }; - let layer_outline = cx.outline.or(if layer.outline { Some(layer.color) } else { None }); + let layer_outline = cx.outline.or(if layer.outline && cx.stage { Some(layer.color) } else { None }); // Through a camera, each layer is placed by the camera and its own depth. let layer_xf = cx.camera.map_or(cx.xf, |c| c.view(&doc.stage, layer.depth)); for el in elements.iter() { @@ -523,7 +528,7 @@ fn eval_timeline(doc: &Document, tl: &Timeline, frame: u32, cx: &Ctx, out: &mut }; // A symbol with 9-slice guides, scaled: its shapes are sliced (ADR 0055). let slice = crate::nine_slice::slicing(doc, sym, &el.transform).map(|s| Slicing { post: layer_xf.mul(&s.post), ..s }); - let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, clip, masks, guide, group, camera: None, slice }; + let inner = Ctx { xf, color, depth: cx.depth + 1, root: Some((root_layer, root_el)), outline: layer_outline, stage: cx.stage, clip, masks, guide, group, camera: None, slice }; eval_timeline(doc, &sym.timeline, local, &inner, out, child.as_ref()); } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index f877eb6b..60315027 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -645,10 +645,20 @@ pub struct Layer { pub visible: bool, #[serde(default)] pub locked: bool, + /// View as Outlines (ADR 0061): the stage draws the layer's artwork as hairlines in + /// [`Layer::color`]. Never in the movie or an export. #[serde(default)] pub outline: bool, #[serde(default = "default_layer_color")] pub color: Rgba, + /// Onion skin draws this layer's frames around the playhead (ADR 0061); off, only its + /// playhead frame shows. + #[serde(default = "yes", skip_serializing_if = "is_true")] + pub onion: bool, + /// Row height on the timeline as a multiple of a normal row (ADR 0061): 1, 2 or 3 (100, + /// 200 or 300 %), as Animate's Layer Properties offer. Read through [`Layer::height`]. + #[serde(default = "one", skip_serializing_if = "is_one", rename = "height")] + pub height_rows: u8, #[serde(default)] pub keyframes: Vec>, /// Layer depth (ADR 0027), pixels behind the stage (negative: in front): the camera's pans @@ -675,6 +685,18 @@ fn full() -> f32 { fn is_full(v: &f32) -> bool { *v == 1.0 } +fn is_true(v: &bool) -> bool { + *v +} +fn one() -> u8 { + 1 +} +fn is_one(v: &u8) -> bool { + *v == 1 +} + +/// Tallest a layer's timeline row gets, in normal rows (300 %). +pub const MAX_LAYER_HEIGHT: u8 = 3; impl PartialEq for Layer { fn eq(&self, o: &Layer) -> bool { @@ -686,6 +708,8 @@ impl PartialEq for Layer { && self.locked == o.locked && self.outline == o.outline && self.color == o.color + && self.onion == o.onion + && self.height_rows == o.height_rows && self.depth.to_bits() == o.depth.to_bits() && self.volume.to_bits() == o.volume.to_bits() && self.muted == o.muted @@ -715,6 +739,8 @@ impl Layer { locked: false, outline: false, color: default_layer_color(), + onion: true, + height_rows: 1, keyframes: vec![Arc::new(Keyframe::new(0, 1))], depth: 0.0, volume: 1.0, @@ -722,6 +748,10 @@ impl Layer { armature: None, } } + /// The row height in normal rows, `1..=MAX_LAYER_HEIGHT` whatever a file says. + pub fn height(&self) -> u8 { + self.height_rows.clamp(1, MAX_LAYER_HEIGHT) + } /// The gain this layer gives its sounds: its volume, or silence when muted. pub fn sound_gain(&self) -> f32 { if self.muted { diff --git a/crates/engine/src/cmds_layer.rs b/crates/engine/src/cmds_layer.rs new file mode 100644 index 00000000..3289e0a6 --- /dev/null +++ b/crates/engine/src/cmds_layer.rs @@ -0,0 +1,161 @@ +//! Layer view properties saved in the document (ADR 0061): each layer's onion skin toggle, its +//! colour (outlines and the timeline bar), View as Outlines, its row height, and Layer +//! Properties, which sets several of them (and the name, type, show and lock) as one step. +//! +//! Behaviour learned from Adobe's public help pages on layers and onion skinning and from +//! watching the program; nothing was copied. + +use crate::params::*; +use crate::{CommandSpec, EngineError, Result, Session}; +use anicraft_doc::{Layer, LayerId, LayerKind, MAX_LAYER_HEIGHT}; +use serde_json::{Value, json}; +use std::sync::Arc; + +pub fn specs() -> Vec { + let c = |id, label, menu, shortcut, params, mutates, run| CommandSpec { id, label, menu, shortcut, params, mutates, run }; + vec![ + c( + "layer.set_onion", + "Onion Skin Layer", + "", + None, + "{onion?: bool (default: the other way), solo?: bool, layer?} whether onion skin draws the layer's frames around the playhead. solo: only this layer is onion-skinned (every other layer off); solo again on the only layer on turns them all back on (Alt-click)", + true, + set_onion as crate::RunFn, + ), + c("layer.set_color", "Layer Colour", "", None, "{color: \"#rrggbb\", layer?} the layer's colour: its outlines in outline mode and its bar on the timeline", true, set_color), + c("layer.set_height", "Layer Height", "", None, "{height: 100 | 200 | 300 (percent of a normal row), layer?} the layer's row height on the timeline", true, set_height), + c( + "layer.set_properties", + "Layer Properties", + "Modify/Timeline", + None, + "{layer?, name?, type?: normal|mask|masked|guide|guided, color?, outline?: bool (view as outlines), height?: 100|200|300, visible?, locked?, onion?} sets several at once, as one undo step; answers with the layer's properties", + true, + set_properties, + ), + c("layer.properties", "Get Layer Properties", "", None, "{layer?} the layer's name, type, colour, outline, height (percent), visible, locked and onion", false, |s, p| properties(s, layer_id(s, p)?)), + ] +} + +fn layer_id(s: &Session, p: &Value) -> Result { + let id = opt_u64(p, "layer")?.map_or(s.layer, LayerId); + s.timeline().layer(id).map(|_| id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0))) +} + +/// Whether a layer of this kind has frames onion skin can show (folders and the camera don't). +fn onion_able(l: &Layer) -> bool { + !matches!(l.kind, LayerKind::Folder | LayerKind::Camera) +} + +fn set_onion(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + let solo = opt_bool(p, "solo")?.unwrap_or(false); + let on = opt_bool(p, "onion")?; + let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); + if solo { + // Animate's Alt-click: this layer alone; again on the only one left on, every layer. + let alone = tl.layers.iter().filter(|l| onion_able(l)).all(|l| l.onion == (l.id == id)); + for l in tl.layers.iter_mut().filter(|l| onion_able(l)) { + let want = alone || l.id == id; + if l.onion != want { + Arc::make_mut(l).onion = want; + } + } + } else { + let l = tl.layer_mut(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + l.onion = on.unwrap_or(!l.onion); + } + let on: Vec = tl.layers.iter().filter(|l| onion_able(l) && l.onion).map(|l| l.id.0).collect(); + let onion = tl.layer(id).is_some_and(|l| l.onion); + Ok(json!({"layer": id.0, "onion": onion, "onion_layers": on})) +} + +fn set_color(s: &mut Session, p: &Value) -> Result { + let color = opt_color(p, "color")?.ok_or_else(|| EngineError::Param("param 'color' (like \"#ff8800\") is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + // A layer colour is opaque: it draws hairlines and a bar. + l.color = color.with_alpha(1.0); + Ok(json!({"color": l.color.to_hex()})) +} + +/// `height` in percent (100, 200 or 300) as rows. +fn height_param(p: &Value) -> Result> { + match opt_u32(p, "height")? { + None => Ok(None), + Some(h) if h > 0 && h % 100 == 0 && h / 100 <= u32::from(MAX_LAYER_HEIGHT) => Ok(u8::try_from(h / 100).ok()), + Some(_) => Err(EngineError::Param("param 'height' must be 100, 200 or 300 (percent)".into())), + } +} + +fn set_height(s: &mut Session, p: &Value) -> Result { + let rows = height_param(p)?.ok_or_else(|| EngineError::Param("param 'height' (100, 200 or 300) is required".into()))?; + let lid = opt_u64(p, "layer")?.map(LayerId); + let l = s.layer_mut(lid)?; + l.height_rows = rows; + Ok(json!({"height": u32::from(l.height()) * 100})) +} + +fn set_properties(s: &mut Session, p: &Value) -> Result { + let id = layer_id(s, p)?; + // Every param is read (and checked) before anything changes. + let name: Option = opt_str(p, "name")?.map(|n| n.chars().take(128).collect()); + if name.as_ref().is_some_and(|n| n.trim().is_empty()) { + return Err(EngineError::Param("layer name must not be empty".into())); + } + let ty = opt_str(p, "type")?; + let color = opt_color(p, "color")?; + let outline = opt_bool(p, "outline")?; + let height = height_param(p)?; + let (visible, locked, onion) = (opt_bool(p, "visible")?, opt_bool(p, "locked")?, opt_bool(p, "onion")?); + if let Some(ty) = ty { + let now = crate::cmds_timeline::layer_type_json(s, id); + if now.get("type").and_then(Value::as_str) != Some(ty) { + crate::cmds_timeline::set_type(s, id, ty)?; + } + } + let l = s.layer_mut(Some(id))?; + if let Some(n) = name { + l.name = n; + } + if let Some(c) = color { + l.color = c.with_alpha(1.0); + } + if let Some(o) = outline { + l.outline = o; + } + if let Some(h) = height { + l.height_rows = h; + } + if let Some(v) = visible { + l.visible = v; + } + if let Some(v) = locked { + l.locked = v; + } + if let Some(v) = onion { + l.onion = v; + } + properties(s, id) +} + +fn properties(s: &Session, id: LayerId) -> Result { + let l = s.timeline().layer(id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; + let ty = crate::cmds_timeline::layer_type_json(s, id).get("type").cloned().unwrap_or(Value::Null); + Ok(json!({ + "layer": id.0, + "name": l.name, + "type": ty, + "color": l.color.to_hex(), + "outline": l.outline, + "height": u32::from(l.height()) * 100, + "visible": l.visible, + "locked": l.locked, + "onion": l.onion, + })) +} + +#[cfg(test)] +#[path = "cmds_layer_tests.rs"] +mod tests; diff --git a/crates/engine/src/cmds_layer_tests.rs b/crates/engine/src/cmds_layer_tests.rs new file mode 100644 index 00000000..b7af3b2a --- /dev/null +++ b/crates/engine/src/cmds_layer_tests.rs @@ -0,0 +1,277 @@ +//! Layer view properties (ADR 0061): onion toggles and solo, colour, View as Outlines (on the +//! stage only), row height, Layer Properties as one step, the file, and onion skin of the +//! timeline around a symbol open in place. + +use crate::Session; +use crate::onion::{Markers, OnionSkin}; +use anicraft_doc::{ElementId, LayerId, Rgba}; +use serde_json::{Value, json}; + +fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) +} + +fn rect(s: &mut Session, x: f32) -> ElementId { + ElementId(run(s, "draw.rect", json!({"x": x, "y": 10, "w": 20, "h": 20, "fill": "#000000", "stroke": null, "object": true}))["element"].as_u64().unwrap()) +} + +/// Two layers, each a square that moves 40 px right on frames 0, 2 and 4: `top` starts at x 0, +/// `bottom` at x 200. The playhead is on frame 2. +fn two_walks() -> (Session, LayerId, LayerId) { + let mut s = Session::default(); + let bottom = s.layer; + let b = rect(&mut s, 200.0); + let top = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let t = rect(&mut s, 0.0); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + for (l, e) in [(bottom, b), (top, t)] { + run(&mut s, "layer.select", json!({"layer": l.0})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [e.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + } + run(&mut s, "timeline.goto", json!({"frame": 2})); + (s, top, bottom) +} + +fn layer(s: &Session, id: LayerId) -> &anicraft_doc::Layer { + s.timeline().layer(id).unwrap() +} + +/// What the stage shows with `skin`: the layers and left edges of the onion frames (tinted items). +fn ghosts(s: &Session, skin: &OnionSkin) -> Vec<(LayerId, f32)> { + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(skin)); + dl.items.iter().filter(|i| !i.color.is_identity()).map(|i| (i.layer, i.path.bounds().transformed(&i.transform).min.x)).collect() +} + +#[test] +fn a_layer_with_onion_off_is_not_onion_skinned() { + let (mut s, top, bottom) = two_walks(); + let skin = OnionSkin { keyframes_only: true, ..OnionSkin::default() }; + let mut both = ghosts(&s, &skin); + both.sort_by(|a, b| a.1.total_cmp(&b.1)); + assert_eq!(both, vec![(top, 0.0), (top, 80.0), (bottom, 200.0), (bottom, 280.0)], "frames 0 and 4 on both layers"); + let r = run(&mut s, "layer.set_onion", json!({"layer": bottom.0})); + assert_eq!(r["onion"], false, "toggles"); + assert!(!layer(&s, bottom).onion && layer(&s, top).onion); + assert!(ghosts(&s, &skin).iter().all(|(l, _)| *l == top), "only the top layer's frames show"); + // Its playhead frame still shows, at full strength. + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&skin)); + assert!(dl.items.iter().any(|i| i.layer == bottom && i.color.is_identity())); + // Edit Multiple Frames isn't onion skin: it still shows and edits the layer's keyframes. + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert!(s.multi_frame_items(0, 4).iter().any(|(it, _)| it.layer == bottom && it.frame == 0)); + let dl = crate::render_service::display_list_with_onion(&s.doc, s.frame, Some(&multi)); + assert_eq!(dl.items.iter().filter(|i| i.layer == bottom).count(), 3); + // Undo brings it back. + run(&mut s, "edit.undo", json!({})); + assert!(layer(&s, bottom).onion); + assert!(s.execute("layer.set_onion", &json!({"layer": 999_999})).is_err()); + assert!(s.execute("layer.set_onion", &json!({"onion": "yes"})).is_err()); +} + +#[test] +fn solo_onion_keeps_one_layer_and_again_brings_back_all() { + let (mut s, top, bottom) = two_walks(); + let folder = LayerId(run(&mut s, "layer.new_folder", json!({}))["layer"].as_u64().unwrap()); + let r = run(&mut s, "layer.set_onion", json!({"layer": top.0, "solo": true})); + assert_eq!(r["onion_layers"], json!([top.0])); + assert!(layer(&s, top).onion && !layer(&s, bottom).onion); + assert!(layer(&s, folder).onion, "a folder has no frames to onion-skin; solo leaves it"); + // Solo on another layer moves the solo there. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(!layer(&s, top).onion && layer(&s, bottom).onion); + // Again on the only layer left on: every layer is on again. + run(&mut s, "layer.set_onion", json!({"layer": bottom.0, "solo": true})); + assert!(layer(&s, top).onion && layer(&s, bottom).onion); + // Setting it outright. + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + run(&mut s, "layer.set_onion", json!({"layer": top.0, "onion": false})); + assert!(!layer(&s, top).onion); +} + +#[test] +fn outlines_use_the_layer_colour_on_the_stage_only() { + let mut s = Session::default(); + let l = s.layer; + rect(&mut s, 10.0); + run(&mut s, "layer.set_color", json!({"color": "#ff8800"})); + run(&mut s, "layer.toggle_outline", json!({})); + let orange = Rgba::hex(0xff8800); + assert_eq!(layer(&s, l).color, orange); + // The stage: hairlines in the layer's colour. + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(s.display_list().items.iter().all(|i| i.outline == Some(orange))); + // The movie (every export), and the player, draw the artwork as it is. + let movie = anicraft_doc::evaluate(&s.doc, 0); + assert!(!movie.items.is_empty() && movie.items.iter().all(|i| i.outline.is_none())); + let player = anicraft_doc::evaluate_player(&s.doc, &anicraft_doc::player::PlayerState::default()); + assert!(player.items.iter().all(|i| i.outline.is_none())); + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(!svg.to_ascii_lowercase().contains("ff8800"), "no outline colour in an SVG export"); + let png = |s: &Session| { + let view = anicraft_render::View { transform: anicraft_geom::Affine::IDENTITY, width: 40, height: 40, background: Some(Rgba::WHITE) }; + anicraft_render::render(&anicraft_doc::evaluate(&s.doc, 0), &view).unwrap().0.to_rgba8() + }; + let outlined = png(&s); + run(&mut s, "layer.toggle_outline", json!({})); + assert_eq!(outlined, png(&s), "an export looks the same with or without outline mode"); + // Inside a symbol on an outlined layer, the stage outlines everything in the layer's colour. + run(&mut s, "layer.toggle_outline", json!({})); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let stage = anicraft_doc::evaluate_scene(&s.doc, 0, 0); + assert!(!stage.items.is_empty() && stage.items.iter().all(|i| i.outline == Some(orange))); + assert!(anicraft_doc::evaluate(&s.doc, 0).items.iter().all(|i| i.outline.is_none())); + // A colour is opaque, and a bad one is refused. + run(&mut s, "layer.set_color", json!({"color": "#00ff0080"})); + assert_eq!(layer(&s, l).color.a, 1.0); + assert!(s.execute("layer.set_color", &json!({"color": "green"})).is_err()); + assert!(s.execute("layer.set_color", &json!({})).is_err()); +} + +#[test] +fn layer_height_is_100_200_or_300_percent() { + let mut s = Session::default(); + let l = s.layer; + assert_eq!(layer(&s, l).height(), 1); + assert_eq!(run(&mut s, "layer.set_height", json!({"height": 300}))["height"], 300); + assert_eq!(layer(&s, l).height(), 3); + for bad in [json!(0), json!(150), json!(400), json!(-100), json!("tall")] { + assert!(s.execute("layer.set_height", &json!({"height": bad})).is_err(), "{bad}"); + } + assert!(s.execute("layer.set_height", &json!({})).is_err()); + assert_eq!(layer(&s, l).height(), 3); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layer(&s, l).height(), 1); +} + +#[test] +fn layer_properties_set_everything_as_one_step_or_nothing() { + let (mut s, top, bottom) = two_walks(); + let undo = s.history.undo_len(); + let r = run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "name": "Sky", "color": "#123456", "outline": true, "height": 200, "locked": true, "visible": false, "onion": false, "type": "guide"})); + assert_eq!(r, json!({"layer": bottom.0, "name": "Sky", "type": "guide", "color": "#123456", "outline": true, "height": 200, "visible": false, "locked": true, "onion": false})); + assert_eq!(s.history.undo_len(), undo + 1, "one undo step"); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0})), r); + // The same type again changes nothing (a masked layer stays masked by the same mask). + run(&mut s, "layer.set_properties", json!({"layer": bottom.0, "type": "guide"})); + assert_eq!(run(&mut s, "layer.properties", json!({"layer": bottom.0}))["type"], "guide"); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + let back = run(&mut s, "layer.properties", json!({"layer": bottom.0})); + assert_eq!((back["name"].as_str(), back["type"].as_str(), back["height"].as_u64()), (Some("Layer 1"), Some("normal"), Some(100))); + // A bad value anywhere changes nothing. + for bad in [json!({"name": " "}), json!({"name": "X", "height": 250}), json!({"name": "X", "color": "red"}), json!({"name": "X", "type": "masked"}), json!({"name": "X", "type": "banana"}), json!({"name": "X", "locked": 1})] { + let mut p = bad.clone(); + p["layer"] = json!(top.0); + assert!(s.execute("layer.set_properties", &p).is_err(), "{bad}"); + assert_eq!(layer(&s, top).name, "Layer 2", "{bad}"); + } + assert!(s.execute("layer.properties", &json!({"layer": 999_999})).is_err()); +} + +#[test] +fn onion_and_height_are_saved_and_older_files_open_with_the_defaults() { + let (mut s, top, bottom) = two_walks(); + run(&mut s, "layer.set_onion", json!({"layer": top.0})); + run(&mut s, "layer.set_height", json!({"layer": bottom.0, "height": 200})); + let text = crate::format::to_json(&s.doc).unwrap(); + let back = crate::format::from_json(&text).unwrap(); + assert_eq!(back, s.doc); + let tl = back.timeline(0); + assert!(!tl.layer(top).unwrap().onion && tl.layer(bottom).unwrap().onion); + assert_eq!((tl.layer(top).unwrap().height(), tl.layer(bottom).unwrap().height()), (1, 2)); + // Defaults are left out of the file, so older files and files without them read the same. + let v: Value = serde_json::from_str(&text).unwrap(); + fn find(v: &Value, id: u64) -> Option { + match v { + Value::Object(m) if m.get("id") == Some(&json!(id)) && m.contains_key("keyframes") => Some(v.clone()), + Value::Object(m) => m.values().find_map(|x| find(x, id)), + Value::Array(a) => a.iter().find_map(|x| find(x, id)), + _ => None, + } + } + let by_id = |id: LayerId| find(&v, id.0).unwrap_or_default(); + assert!(by_id(top).get("name").is_some()); + assert_eq!((by_id(top).get("onion"), by_id(top).get("height")), (Some(&json!(false)), None)); + assert_eq!((by_id(bottom).get("onion"), by_id(bottom).get("height")), (None, Some(&json!(2)))); + let old: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Old"})).unwrap(); + assert!(old.onion && old.height() == 1); + // A height out of range in a file reads as the nearest one. + let tall: anicraft_doc::Layer = serde_json::from_value(json!({"id": 7, "name": "Tall", "height": 200})).unwrap(); + assert_eq!(tall.height(), 3); +} + +/// A scene with a square walking on a second layer (x 0, 40, 80 on frames 0, 2, 4), and an +/// instance of a symbol on the first, open in place on frame 2 of the scene. +fn parent_walk() -> (Session, LayerId) { + let mut s = Session::default(); + let host = s.layer; + rect(&mut s, 300.0); + run(&mut s, "edit.select_all", json!({})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + let inst = s.selection.ids().next().unwrap(); + let walker = LayerId(run(&mut s, "layer.new", json!({}))["layer"].as_u64().unwrap()); + let w = rect(&mut s, 0.0); + run(&mut s, "timeline.insert_frame", json!({"layer": host.0, "frame": 0, "count": 4})); + for f in [2, 4] { + run(&mut s, "timeline.goto", json!({"frame": f})); + run(&mut s, "timeline.insert_keyframe", json!({})); + run(&mut s, "element.select", json!({"ids": [w.0]})); + run(&mut s, "element.translate", json!({"dx": 40, "dy": 0})); + } + run(&mut s, "layer.select", json!({"layer": host.0})); + run(&mut s, "timeline.goto", json!({"frame": 2})); + run(&mut s, "symbol.edit", json!({"id": inst.0})); + assert_eq!(s.editing.len(), 1); + (s, walker) +} + +#[test] +fn onion_skin_inside_a_symbol_shows_the_parent_timeline_frames_dimmed() { + let (s, walker) = parent_walk(); + let pic = s.stage_picture(); + let front = pic.front.clone().unwrap(); + let parent = front.parent.clone().expect("the scene shows around the symbol"); + assert_eq!(parent.frame, 2); + let skin = OnionSkin { markers: Markers::Relative { before: 2, after: 2 }, keyframes_only: true, ..OnionSkin::default() }; + let dl = crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin); + let left = |i: &anicraft_doc::DisplayItem| i.path.bounds().transformed(&i.transform).min.x; + // The walker on the scene: frame 2 (x 40) dimmed, frames 0 and 4 (x 0, 80) tinted and fainter. + let mut walk: Vec<(f32, f32, bool)> = dl.items.iter().filter(|i| left(i) < 150.0).map(|i| (left(i), dl.effective_alpha(i), i.color.changes_colour())).collect(); + walk.sort_by(|a, b| a.0.total_cmp(&b.0)); + assert_eq!(walk.iter().map(|w| w.0).collect::>(), vec![0.0, 40.0, 80.0], "the parent's onion frames around its frame 2"); + let dim = parent.dim; + assert!((walk[1].1 - dim).abs() < 1e-4 && !walk[1].2, "the parent's own frame as dim as without onion skin"); + assert!(walk[0].2 && walk[2].2 && walk[0].1 < dim && walk[2].1 < dim, "its onion frames tinted, dimmer still"); + // The open symbol is in front at full strength. + let box_item = dl.items.iter().find(|i| left(i) >= 290.0).unwrap(); + assert!((dl.effective_alpha(box_item) - 1.0).abs() < 1e-4); + assert!(dl.items.last().is_some_and(|i| left(i) >= 290.0), "drawn over everything around it"); + // Without onion skin the picture is as before; the parent's layer toggle and Edit Multiple + // Frames (the open symbol's frames only) leave its onion frames out. + let plain = crate::render_service::display_list_with_onion(&pic.doc, pic.frame, None); + assert_eq!(plain.items.len(), 2); + let multi = OnionSkin { edit_multiple: true, ..skin }; + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &multi).items.len(), 2); + let mut off = s; + run(&mut off, "symbol.exit", json!({})); + let inst = off.selection.ids().next().unwrap(); + run(&mut off, "layer.set_onion", json!({"layer": walker.0})); + run(&mut off, "symbol.edit", json!({"id": inst.0})); + let pic = off.stage_picture(); + let front = pic.front.clone().unwrap(); + assert_eq!(crate::render_service::display_list_inside(&pic.doc, pic.frame, &front, &skin).items.len(), 2); +} + +#[test] +fn plug_ins_may_set_layer_properties() { + for id in ["layer.set_onion", "layer.set_color", "layer.set_height", "layer.set_properties", "layer.properties"] { + assert!(crate::find_command(id).is_some(), "{id}"); + assert!(crate::cmds_plugin::plugin_may_call(id).is_ok(), "{id}"); + } +} diff --git a/crates/engine/src/cmds_plugin.rs b/crates/engine/src/cmds_plugin.rs index 80cb336d..98281a92 100644 --- a/crates/engine/src/cmds_plugin.rs +++ b/crates/engine/src/cmds_plugin.rs @@ -79,7 +79,7 @@ fn document_view(s: &Session) -> Value { .timeline() .layers .iter() - .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "parent": l.parent.map(|p| p.0)})) + .map(|l| json!({"id": l.id.0, "name": l.name, "kind": format!("{:?}", l.kind).to_lowercase(), "visible": l.visible, "locked": l.locked, "outline": l.outline, "onion": l.onion, "height": u32::from(l.height()) * 100, "parent": l.parent.map(|p| p.0)})) .collect(); json!({ "abi": anicraft_plugins::ABI_VERSION, diff --git a/crates/engine/src/cmds_timeline.rs b/crates/engine/src/cmds_timeline.rs index e173b55d..eb57c705 100644 --- a/crates/engine/src/cmds_timeline.rs +++ b/crates/engine/src/cmds_timeline.rs @@ -126,7 +126,7 @@ fn set_layer_type(s: &mut Session, p: &Value) -> Result { Ok(layer_type_json(s, id)) } -fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { +pub(crate) fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { let tl = crate::editing::edited_mut(&mut s.doc, s.scene, &s.editing); let i = tl.layers.iter().position(|l| l.id == id).ok_or_else(|| EngineError::State(format!("no layer with id {}", id.0)))?; if tl.layers.get(i).is_some_and(|l| l.kind == LayerKind::Folder) { @@ -161,7 +161,7 @@ fn set_type(s: &mut Session, id: LayerId, ty: &str) -> Result<()> { Ok(()) } -fn layer_type_json(s: &Session, id: LayerId) -> Value { +pub(crate) fn layer_type_json(s: &Session, id: LayerId) -> Value { let Some(l) = s.timeline().layer(id) else { return json!({}) }; let tl = s.timeline(); let parent_kind = l.parent.and_then(|p| tl.layer(p)).map(|x| x.kind); diff --git a/crates/engine/src/editing.rs b/crates/engine/src/editing.rs index 037f29ad..46747f03 100644 --- a/crates/engine/src/editing.rs +++ b/crates/engine/src/editing.rs @@ -103,6 +103,20 @@ pub struct Front { pub timeline: Timeline, pub frame: u32, pub at: Affine, + /// The timeline the symbol was opened from, when it shows around it (in place): with onion + /// skin on, its frames around its own playhead show dimmed too (ADR 0061). + pub parent: Option, +} + +/// A timeline drawn dimmed around an open symbol: the picture's layer `layer` shows `timeline` +/// (without the instance that was opened) at its `frame`, placed by `at`, at opacity `dim`. +#[derive(Clone, Debug)] +pub struct Around { + pub layer: LayerId, + pub timeline: Timeline, + pub frame: u32, + pub at: Affine, + pub dim: f32, } impl Session { @@ -196,7 +210,7 @@ impl Session { tl.layers.push(placed(&mut doc, hit_timeline(&open), at, frame, ColorEffect::Advanced(hit_tint(tint, alpha)))); } let layer = placed(&mut doc, open.clone(), at, self.frame, ColorEffect::default()); - let front = Arc::new(Front { layer: layer.id, timeline: open, frame: self.frame, at }); + let mut front = Front { layer: layer.id, timeline: open, frame: self.frame, at, parent: None }; tl.layers.push(layer); // Around it, dimmed: each timeline below, without the instance opened from it. if view.in_place { @@ -207,9 +221,16 @@ impl Session { Some(p) => self.doc.symbol(p.symbol).map(|s| s.timeline.clone()).unwrap_or_default(), }; let xf = parent.map_or(Affine::IDENTITY, |p| p.transform); - tl.layers.push(placed(&mut doc, without(below, l.instance), xf, l.frame, ColorEffect::opacity(DIM))); + let around = without(below, l.instance); + let layer = placed(&mut doc, around.clone(), xf, l.frame, ColorEffect::opacity(DIM)); + // The timeline right under the open symbol is the one onion skin shows around it. + if front.parent.is_none() { + front.parent = Some(Around { layer: layer.id, timeline: around, frame: l.frame, at: xf, dim: DIM }); + } + tl.layers.push(layer); } } + let front = Arc::new(front); *doc.timeline_mut(self.scene) = tl; // Apart from document states (counted up from 1), and the same for the same picture. let pic = Arc::new(StagePicture { frame: doc.scene_start(self.scene), doc, state: key | 1 << 63, front: Some(front) }); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index db1a6012..9239be2f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -17,6 +17,7 @@ mod cmds_frames; mod cmds_modify; mod cmds_motion; mod cmds_hints; +mod cmds_layer; pub mod cmds_library; mod cmds_paint; mod cmds_path; @@ -116,6 +117,7 @@ pub fn commands() -> Vec { v.extend(cmds_drop::specs()); v.extend(cmds_recovery::specs()); v.extend(cmds_timeline::specs()); + v.extend(cmds_layer::specs()); v.extend(cmds_camera::specs()); v.extend(cmds_bone::specs()); v.extend(cmds_motion::specs()); diff --git a/crates/engine/src/onion.rs b/crates/engine/src/onion.rs index 594f98da..156dd8a8 100644 --- a/crates/engine/src/onion.rs +++ b/crates/engine/src/onion.rs @@ -199,15 +199,22 @@ pub struct Extra { pub distance: u32, } -/// Whether onion skin draws `layer` (Animate doesn't onion-skin locked layers). -fn ghosted(tl: &Timeline, i: usize) -> bool { +/// Whether `layer` is shown and unlocked artwork (not a folder), itself and through its folders. +fn open_artwork(tl: &Timeline, i: usize) -> bool { tl.layers.get(i).is_some_and(|l| l.visible && !l.locked && l.kind != LayerKind::Folder && !tl.locked_by_folder(l.id) && !tl.hidden_by_folder(i)) } +/// Whether onion skin draws `layer`: shown and unlocked (Animate doesn't onion-skin locked +/// layers), with its own onion toggle on (ADR 0061). +pub fn ghosted(tl: &Timeline, i: usize) -> bool { + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| l.onion) +} + /// Whether Edit Multiple Frames shows and edits `layer`'s other keyframes: it is shown and /// unlocked, and holds artwork (not a folder, the camera or an armature posed by its bones). +/// A layer's onion toggle doesn't apply: it is about the faded frames, not editing. pub fn multi_editable(tl: &Timeline, i: usize) -> bool { - ghosted(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) + open_artwork(tl, i) && tl.layers.get(i).is_some_and(|l| !matches!(l.kind, LayerKind::Camera | LayerKind::Armature)) } /// The onion frames to draw for the playhead on `playhead`, farthest first (nearest on top), diff --git a/crates/engine/src/render_service.rs b/crates/engine/src/render_service.rs index c28e4ecf..01014d59 100644 --- a/crates/engine/src/render_service.rs +++ b/crates/engine/src/render_service.rs @@ -94,14 +94,48 @@ impl FrameJob { } /// A stage picture's frame with the open symbol in front composed by `skin`: the timelines around -/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. +/// it as they are, then the symbol's frames, each layer's onion frames under its artwork. With +/// onion skin on (not Edit Multiple Frames), the timeline the symbol was opened from shows its +/// own onion frames too, dimmed with it (ADR 0061). pub fn display_list_inside(doc: &Document, frame: u32, front: &Front, skin: &OnionSkin) -> DisplayList { let (scene, local) = doc.locate(frame); - let mut around = doc.timeline(scene).clone(); - around.layers.retain(|l| l.id != front.layer); - let mut dl = anicraft_doc::evaluate_timeline(doc, &around, local); let tl = &front.timeline; - dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + let parent = front.parent.as_ref().filter(|_| skin.ghosts && !skin.edit_multiple); + let mut dl = DisplayList::default(); + // Back to front: the picture's layers from the bottom up, each its own timeline. + for l in doc.timeline(scene).layers.iter().rev() { + if l.id == front.layer { + dl.append(crate::onion::compose_timeline(tl, front.frame, Some(skin), |f| anicraft_doc::evaluate_timeline_at(doc, tl, f, front.at))); + } else if let Some(p) = parent.filter(|p| p.layer == l.id) { + dl.append(parent_onion(doc, p, front, skin)); + } else { + dl.append(anicraft_doc::evaluate_timeline(doc, &anicraft_doc::Timeline { layers: vec![l.clone()] }, local)); + } + } + dl +} + +/// The timeline around an open symbol with its onion frames, all at its dim opacity. Markers that +/// follow the playhead reach as many frames from the parent's frame; anchored ones (which name +/// the symbol's frames) as far as they reach from the symbol's playhead. +fn parent_onion(doc: &Document, p: &crate::editing::Around, front: &Front, skin: &OnionSkin) -> DisplayList { + let mut own = *skin; + if skin.anchored() { + let (first, last) = skin.range(front.frame, front.timeline.frame_count()); + own.markers = crate::onion::Markers::Relative { before: front.frame.saturating_sub(first), after: last.saturating_sub(front.frame) }; + } + let composed = crate::onion::compose_timeline(&p.timeline, p.frame, Some(&own), |f| anicraft_doc::evaluate_timeline_at(doc, &p.timeline, f, p.at)); + // It fades as one, as the dimmed instance it replaces does: everything in a group at `dim`. + let alpha = if p.dim.is_finite() { p.dim.clamp(0.0, 1.0) } else { 1.0 }; + let mut dl = DisplayList::default(); + dl.groups.push(anicraft_doc::Group { parent: None, alpha, blend: Default::default(), filters: Arc::from(Vec::new()), clip: None }); + dl.append(composed); + for g in dl.groups.iter_mut().skip(1) { + g.parent = Some(g.parent.unwrap_or(0)); + } + for it in dl.items.iter_mut().filter(|i| i.masks.is_none()) { + it.group = Some(it.group.unwrap_or(0)); + } dl } diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 60a333da..6954a59c 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -531,6 +531,8 @@ impl<'a> Builder<'a> { layer.locked = l.bool("locked").unwrap_or(false); layer.outline = l.bool("outline").unwrap_or(false); layer.color = color(l, "color", "__none"); + // Layer Properties' height, 100 / 200 / 300 % (ADR 0061), as a multiple of a row. + layer.height_rows = l.u32("heightMultiplier").map_or(1, |h| h.clamp(1, u32::from(anicraft_doc::MAX_LAYER_HEIGHT)) as u8); let mut keys = Vec::new(); let mut raw_hints: HashMap> = HashMap::new(); for f in l.list("frames").iter().filter(|f| f.name == "DOMFrame") { diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 648130f9..362ef090 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -32,7 +32,7 @@ const DOC: &str = r##" + @@ -90,6 +90,7 @@ fn stage_layers_frames_and_tweens() { assert_eq!(ball.keyframes[0].label, "start"); assert!(matches!(ball.keyframes[0].tween.map(|t| t.easing), Some(anicraft_doc::Easing::Classic(e)) if e == -50.0)); assert!(doc.timeline(0).layers[1].locked); + assert_eq!((doc.timeline(0).layers[0].height(), doc.timeline(0).layers[1].height()), (1, 2), "Layer Properties height"); assert_eq!(doc.timeline(0).layers[2].kind, LayerKind::Guide); assert_eq!(doc.timeline(0).frame_count(), 15); assert_eq!(doc.frame_count(), 16, "the movie: scene 1, then the one-frame scene 2");