diff --git a/crates/doc/src/filter.rs b/crates/doc/src/filter.rs index 92167504..add42b4a 100644 --- a/crates/doc/src/filter.rs +++ b/crates/doc/src/filter.rs @@ -1,8 +1,8 @@ -//! Filters on movie clip and button instances, as Animate's Filters panel: Blur, Drop Shadow, -//! Glow and Adjust Color. Sizes are in stage pixels (they don't scale with the instance, as in -//! Animate); they scale with the view. +//! Filters on movie clip and button instances, as Animate's Filters panel: Drop Shadow, Blur, +//! Glow, Bevel, Gradient Glow, Gradient Bevel and Adjust Color. Sizes are in stage pixels (they +//! don't scale with the instance, as in Animate); they scale with the view. -use crate::Rgba; +use crate::{GradientStop, Rgba}; use serde::{Deserialize, Serialize}; /// Blur passes: Low, Medium, High (each pass is a box blur; three approach a Gaussian). @@ -28,6 +28,108 @@ fn four() -> f32 { fn five() -> f32 { 5.0 } +fn white() -> Rgba { + Rgba::WHITE +} +fn outer() -> FilterSide { + FilterSide::Outer +} + +/// Most colour stops in a gradient filter's ramp (Animate's limit). +pub const MAX_RAMP_STOPS: usize = 15; + +/// Where a bevel or gradient filter draws: inside the artwork's edge, outside it, or both +/// (Animate's Type menu). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum FilterSide { + #[default] + Inner, + Outer, + Full, +} + +impl FilterSide { + pub const ALL: [FilterSide; 3] = [FilterSide::Inner, FilterSide::Outer, FilterSide::Full]; + pub fn label(self) -> &'static str { + match self { + FilterSide::Inner => "Inner", + FilterSide::Outer => "Outer", + FilterSide::Full => "Full", + } + } +} + +fn stop(offset: f32, color: Rgba) -> GradientStop { + GradientStop { offset, color } +} + +/// Animate's default Gradient Glow ramp: transparent white into black. +pub fn default_glow_ramp() -> Vec { + vec![stop(0.0, Rgba::WHITE.with_alpha(0.0)), stop(1.0, Rgba::BLACK)] +} + +/// Animate's default Gradient Bevel ramp: white highlight, transparent middle, black shadow. +pub fn default_bevel_ramp() -> Vec { + vec![stop(0.0, Rgba::WHITE), stop(0.5, Rgba::BLACK.with_alpha(0.0)), stop(1.0, Rgba::BLACK)] +} + +/// The ramp's colour at `t` (stops sorted by offset; the ends extend). +pub fn ramp_at(stops: &[GradientStop], t: f32) -> Rgba { + let Some(first) = stops.first() else { return Rgba::TRANSPARENT }; + if t.is_nan() || t <= first.offset { + return first.color; + } + for w in stops.windows(2) { + if let [a, b] = w + && t <= b.offset + { + let span = b.offset - a.offset; + let k = if span > 1e-6 { (t - a.offset) / span } else { 1.0 }; + return a.color.lerp(b.color, k); + } + } + stops.last().map_or(first.color, |s| s.color) +} + +/// A ramp with finite stops in order, at most [`MAX_RAMP_STOPS`], and a transparent stop where +/// the filter rests (`rest`: no glow, or a flat bevel). Animate pins that stop, so a gradient +/// filter paints nothing away from the edges. +fn sanitized_ramp(stops: &[GradientStop], rest: f32, fallback: fn() -> Vec) -> Vec { + let mut v: Vec = stops.iter().filter(|s| s.offset.is_finite()).map(|s| stop(s.offset.clamp(0.0, 1.0), s.color.sanitized())).collect(); + if v.is_empty() { + v = fallback(); + } + v.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + v.truncate(MAX_RAMP_STOPS); + if let Some(s) = v.iter_mut().find(|s| (s.offset - rest).abs() < 1e-3) { + s.offset = rest; + s.color.a = 0.0; + return v; + } + // Insert a transparent stop of the ramp's colour there, keeping within the limit (the + // stop nearest the rest point makes room). + let c = ramp_at(&v, rest); + if v.len() >= MAX_RAMP_STOPS { + let far = |s: &GradientStop| (s.offset - rest).abs(); + if let Some(i) = (0..v.len()).min_by(|&a, &b| far(&v[a]).total_cmp(&far(&v[b]))) { + v.remove(i); + } + } + let at = v.iter().position(|s| s.offset > rest).unwrap_or(v.len()); + v.insert(at, stop(rest, c.with_alpha(0.0))); + v +} + +/// The offset of the ramp stop that can't move, be removed or be seen: the Gradient Glow's +/// start, the Gradient Bevel's middle. +pub fn pinned_stop(f: &Filter) -> Option { + match f { + Filter::GradientGlow { .. } => Some(0.0), + Filter::GradientBevel { .. } => Some(0.5), + _ => None, + } +} #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] @@ -80,6 +182,76 @@ pub enum Filter { #[serde(default)] knockout: bool, }, + /// A raised edge: a highlight on the side the light comes from and a shadow on the other, + /// from the blurred opacity offset both ways along the angle. + Bevel { + #[serde(default = "five")] + blur_x: f32, + #[serde(default = "five")] + blur_y: f32, + #[serde(default = "full")] + strength: f32, + #[serde(default = "one")] + quality: u8, + /// Degrees, clockwise from the right: the shadow falls this way, the highlight opposite + /// (45 = light from the top left). + #[serde(default = "angle")] + angle: f32, + #[serde(default = "five")] + distance: f32, + #[serde(default = "black")] + shadow_color: Rgba, + #[serde(default = "white")] + highlight_color: Rgba, + #[serde(default)] + side: FilterSide, + #[serde(default)] + knockout: bool, + }, + /// A glow coloured by a ramp: the glow's intensity (0 where it fades out, 1 at full) + /// picks the colour. The ramp's start is pinned transparent. + GradientGlow { + #[serde(default = "five")] + blur_x: f32, + #[serde(default = "five")] + blur_y: f32, + #[serde(default = "full")] + strength: f32, + #[serde(default = "one")] + quality: u8, + #[serde(default = "angle")] + angle: f32, + #[serde(default = "five")] + distance: f32, + #[serde(default = "default_glow_ramp")] + stops: Vec, + #[serde(default = "outer")] + side: FilterSide, + #[serde(default)] + knockout: bool, + }, + /// A bevel coloured by a ramp: the highlight at 0, flat at the middle (pinned + /// transparent), the shadow at 1. + GradientBevel { + #[serde(default = "five")] + blur_x: f32, + #[serde(default = "five")] + blur_y: f32, + #[serde(default = "full")] + strength: f32, + #[serde(default = "one")] + quality: u8, + #[serde(default = "angle")] + angle: f32, + #[serde(default = "five")] + distance: f32, + #[serde(default = "default_bevel_ramp")] + stops: Vec, + #[serde(default)] + side: FilterSide, + #[serde(default)] + knockout: bool, + }, /// Each in −100..=100 (hue in −180..=180 degrees), 0 = unchanged. AdjustColor { #[serde(default)] @@ -100,24 +272,38 @@ impl Filter { Filter::Blur { .. } => "Blur", Filter::DropShadow { .. } => "Drop Shadow", Filter::Glow { .. } => "Glow", + Filter::Bevel { .. } => "Bevel", + Filter::GradientGlow { .. } => "Gradient Glow", + Filter::GradientBevel { .. } => "Gradient Bevel", Filter::AdjustColor { .. } => "Adjust Color", } } - /// A new filter of `kind` (`blur`, `drop_shadow`, `glow`, `adjust_color`) with Animate's - /// defaults. + /// A new filter of `kind` (`blur`, `drop_shadow`, `glow`, `bevel`, `gradient_glow`, + /// `gradient_bevel`, `adjust_color`) with Animate's defaults. pub fn new(kind: &str) -> Option { Some(match kind { "blur" => Filter::Blur { blur_x: five(), blur_y: five(), quality: one() }, "drop_shadow" => Filter::DropShadow { blur_x: five(), blur_y: five(), strength: full(), quality: one(), angle: angle(), distance: four(), color: black(), inner: false, knockout: false, hide_object: false }, "glow" => Filter::Glow { blur_x: five(), blur_y: five(), strength: full(), quality: one(), color: Rgba::hex(0xff0000), inner: false, knockout: false }, + "bevel" => Filter::Bevel { blur_x: five(), blur_y: five(), strength: full(), quality: one(), angle: angle(), distance: five(), shadow_color: black(), highlight_color: white(), side: FilterSide::Inner, knockout: false }, + "gradient_glow" => Filter::GradientGlow { blur_x: five(), blur_y: five(), strength: full(), quality: one(), angle: angle(), distance: five(), stops: default_glow_ramp(), side: FilterSide::Outer, knockout: false }, + "gradient_bevel" => Filter::GradientBevel { blur_x: five(), blur_y: five(), strength: full(), quality: one(), angle: angle(), distance: five(), stops: default_bevel_ramp(), side: FilterSide::Inner, knockout: false }, "adjust_color" => Filter::AdjustColor { brightness: 0.0, contrast: 0.0, saturation: 0.0, hue: 0.0 }, _ => return None, }) } /// The kinds [`Filter::new`] makes, in Animate's menu order. - pub const KINDS: [(&'static str, &'static str); 4] = [("drop_shadow", "Drop Shadow"), ("blur", "Blur"), ("glow", "Glow"), ("adjust_color", "Adjust Color")]; + pub const KINDS: [(&'static str, &'static str); 7] = [ + ("drop_shadow", "Drop Shadow"), + ("blur", "Blur"), + ("glow", "Glow"), + ("bevel", "Bevel"), + ("gradient_glow", "Gradient Glow"), + ("gradient_bevel", "Gradient Bevel"), + ("adjust_color", "Adjust Color"), + ]; /// The same filter with every value finite and in range. pub fn sanitized(&self) -> Filter { @@ -125,15 +311,17 @@ impl Filter { let blur = |v: f32| fin(v, 0.0).clamp(0.0, MAX_BLUR); let q = |v: u8| v.clamp(1, MAX_QUALITY); let strength = |v: f32| fin(v, 1.0).clamp(0.0, 10.0); + let angle = |v: f32| fin(v, 45.0).rem_euclid(360.0); + let distance = |v: f32| fin(v, 0.0).clamp(-1000.0, 1000.0); match self { Filter::Blur { blur_x, blur_y, quality } => Filter::Blur { blur_x: blur(*blur_x), blur_y: blur(*blur_y), quality: q(*quality) }, - Filter::DropShadow { blur_x, blur_y, strength: s, quality, angle, distance, color, inner, knockout, hide_object } => Filter::DropShadow { + Filter::DropShadow { blur_x, blur_y, strength: s, quality, angle: a, distance: d, color, inner, knockout, hide_object } => Filter::DropShadow { blur_x: blur(*blur_x), blur_y: blur(*blur_y), strength: strength(*s), quality: q(*quality), - angle: fin(*angle, 45.0).rem_euclid(360.0), - distance: fin(*distance, 0.0).clamp(-1000.0, 1000.0), + angle: angle(*a), + distance: distance(*d), color: color.sanitized(), inner: *inner, knockout: *knockout, @@ -142,6 +330,40 @@ impl Filter { Filter::Glow { blur_x, blur_y, strength: s, quality, color, inner, knockout } => { Filter::Glow { blur_x: blur(*blur_x), blur_y: blur(*blur_y), strength: strength(*s), quality: q(*quality), color: color.sanitized(), inner: *inner, knockout: *knockout } } + Filter::Bevel { blur_x, blur_y, strength: s, quality, angle: a, distance: d, shadow_color, highlight_color, side, knockout } => Filter::Bevel { + blur_x: blur(*blur_x), + blur_y: blur(*blur_y), + strength: strength(*s), + quality: q(*quality), + angle: angle(*a), + distance: distance(*d), + shadow_color: shadow_color.sanitized(), + highlight_color: highlight_color.sanitized(), + side: *side, + knockout: *knockout, + }, + Filter::GradientGlow { blur_x, blur_y, strength: s, quality, angle: a, distance: d, stops, side, knockout } => Filter::GradientGlow { + blur_x: blur(*blur_x), + blur_y: blur(*blur_y), + strength: strength(*s), + quality: q(*quality), + angle: angle(*a), + distance: distance(*d), + stops: sanitized_ramp(stops, 0.0, default_glow_ramp), + side: *side, + knockout: *knockout, + }, + Filter::GradientBevel { blur_x, blur_y, strength: s, quality, angle: a, distance: d, stops, side, knockout } => Filter::GradientBevel { + blur_x: blur(*blur_x), + blur_y: blur(*blur_y), + strength: strength(*s), + quality: q(*quality), + angle: angle(*a), + distance: distance(*d), + stops: sanitized_ramp(stops, 0.5, default_bevel_ramp), + side: *side, + knockout: *knockout, + }, Filter::AdjustColor { brightness, contrast, saturation, hue } => Filter::AdjustColor { brightness: fin(*brightness, 0.0).clamp(-100.0, 100.0), contrast: fin(*contrast, 0.0).clamp(-100.0, 100.0), @@ -157,6 +379,9 @@ impl Filter { Filter::Blur { blur_x, blur_y, quality } => blur_x.max(blur_y) * 0.5 * f32::from(quality) + 1.0, Filter::DropShadow { blur_x, blur_y, quality, distance, inner, .. } => if inner { 0.0 } else { blur_x.max(blur_y) * 0.5 * f32::from(quality) + distance.abs() + 1.0 }, Filter::Glow { blur_x, blur_y, quality, inner, .. } => if inner { 0.0 } else { blur_x.max(blur_y) * 0.5 * f32::from(quality) + 1.0 }, + // A bevel samples the opacity a distance both ways, inner ones too. + Filter::Bevel { blur_x, blur_y, quality, distance, .. } | Filter::GradientBevel { blur_x, blur_y, quality, distance, .. } => blur_x.max(blur_y) * 0.5 * f32::from(quality) + distance.abs() + 1.0, + Filter::GradientGlow { blur_x, blur_y, quality, distance, side, .. } => if side == FilterSide::Inner { 0.0 } else { blur_x.max(blur_y) * 0.5 * f32::from(quality) + distance.abs() + 1.0 }, Filter::AdjustColor { .. } => 0.0, } } @@ -178,4 +403,55 @@ mod tests { let json = serde_json::to_string(&Filter::new("adjust_color").unwrap()).unwrap(); assert_eq!(json, r#"{"type":"adjust_color","brightness":0.0,"contrast":0.0,"saturation":0.0,"hue":0.0}"#); } + + #[test] + fn bevels_and_gradient_filters_default_like_animate_and_old_files_open() { + let Some(Filter::Bevel { distance, side, shadow_color, highlight_color, knockout, .. }) = Filter::new("bevel") else { panic!() }; + assert_eq!((distance, side, shadow_color, highlight_color, knockout), (5.0, FilterSide::Inner, Rgba::BLACK, Rgba::WHITE, false)); + assert!(matches!(Filter::new("gradient_glow"), Some(Filter::GradientGlow { side: FilterSide::Outer, .. }))); + // Every kind round-trips, and a bare type opens with the defaults. + for (kind, label) in Filter::KINDS { + let f = Filter::new(kind).unwrap(); + assert_eq!(f.label(), label); + assert_eq!(f.sanitized(), f, "{kind}: defaults are already in range"); + let back: Filter = serde_json::from_str(&serde_json::to_string(&f).unwrap()).unwrap(); + assert_eq!(back, f); + } + for kind in ["bevel", "gradient_glow", "gradient_bevel"] { + let bare: Filter = serde_json::from_str(&format!(r#"{{"type":"{kind}"}}"#)).unwrap(); + assert_eq!(Some(bare), Filter::new(kind), "{kind}: missing values take the defaults"); + } + let side: FilterSide = serde_json::from_str(r#""full""#).unwrap(); + assert_eq!(side, FilterSide::Full); + // Bevels reach out by blur and distance (inner ones read that far); inner glows don't. + let bevel = |side| Filter::Bevel { blur_x: 4.0, blur_y: 8.0, strength: 1.0, quality: 2, angle: 45.0, distance: -3.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side, knockout: false }; + assert_eq!(bevel(FilterSide::Inner).margin(), 12.0); + assert_eq!(bevel(FilterSide::Full).margin(), 12.0); + let Some(Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, knockout, .. }) = Filter::new("gradient_glow") else { panic!() }; + assert_eq!(Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, knockout, side: FilterSide::Inner }.margin(), 0.0); + } + + #[test] + fn ramps_keep_their_rest_stop_transparent_and_in_range() { + let st = |offset: f32, c: u32, a: f32| GradientStop { offset, color: Rgba::hex(c).with_alpha(a) }; + // A glow ramp with an opaque start gets it pinned transparent; order and range fixed. + let Filter::GradientGlow { stops, .. } = (Filter::GradientGlow { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 5.0, stops: vec![st(2.0, 0xff0000, 1.0), st(0.0, 0x00ff00, 1.0), st(f32::NAN, 0, 1.0)], side: FilterSide::Outer, knockout: false }).sanitized() else { panic!() }; + assert_eq!(stops, vec![st(0.0, 0x00ff00, 0.0), st(1.0, 0xff0000, 1.0)]); + // A bevel ramp without a middle gets one, of the ramp's colour there. + let Filter::GradientBevel { stops, .. } = (Filter::GradientBevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 5.0, stops: vec![st(0.0, 0xffffff, 1.0), st(1.0, 0x000000, 1.0)], side: FilterSide::Inner, knockout: false }).sanitized() else { panic!() }; + assert_eq!(stops.len(), 3); + assert_eq!(stops[1].offset, 0.5); + assert_eq!(stops[1].color.a, 0.0); + assert!((stops[1].color.r - 0.5).abs() < 1e-6); + // Empty ramps take the default; long ones stay within the limit, the pin included. + let Filter::GradientBevel { stops, .. } = (Filter::GradientBevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 5.0, stops: vec![], side: FilterSide::Inner, knockout: false }).sanitized() else { panic!() }; + assert_eq!(stops, default_bevel_ramp()); + let many: Vec = (0..40).map(|i| st(i as f32 / 41.0, 0x336699, 1.0)).collect(); + let Filter::GradientBevel { stops, .. } = (Filter::GradientBevel { blur_x: 5.0, blur_y: 5.0, strength: 1.0, quality: 1, angle: 45.0, distance: 5.0, stops: many, side: FilterSide::Inner, knockout: false }).sanitized() else { panic!() }; + assert_eq!(stops.len(), MAX_RAMP_STOPS); + assert!(stops.iter().any(|s| s.offset == 0.5 && s.color.a == 0.0)); + assert!(stops.windows(2).all(|w| w[0].offset <= w[1].offset)); + assert_eq!(ramp_at(&default_bevel_ramp(), 0.25), Rgba::new(0.5, 0.5, 0.5, 0.5)); + assert_eq!(ramp_at(&[], 0.5), Rgba::TRANSPARENT); + } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index b6e17ffd..38b8d17d 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -17,7 +17,7 @@ pub mod width; pub mod sample; pub mod sound; -pub use filter::{Filter, MAX_BLUR, MAX_QUALITY}; +pub use filter::{Filter, FilterSide, MAX_BLUR, MAX_QUALITY, MAX_RAMP_STOPS, default_bevel_ramp, default_glow_ramp, pinned_stop, ramp_at}; pub use bitmap::{Bitmap, BitmapId, ImageError, MAX_BITMAP_EDGE, Pixels, base64_encode, decode_png, image_to_png}; pub use easing::Easing; pub use hints::{HINT_TOLERANCE, HintSide, MAX_SHAPE_HINTS, ShapeHint, hint_index, hint_letter, nearest_outline, placed_on, shapes_centre}; diff --git a/crates/engine/src/cmds_draw.rs b/crates/engine/src/cmds_draw.rs index b3e9efc5..0fcdea7a 100644 --- a/crates/engine/src/cmds_draw.rs +++ b/crates/engine/src/cmds_draw.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec { c("element.set_stroke", "Stroke", "", None, "{color?: \"#rrggbb\" | null, width?, profile?: uniform|taper_both|taper_start|taper_end|bulge|pinch | [[t, left, right], ..]}", true, set_stroke), c("element.set_alpha", "Alpha", "", None, "{alpha: 0..1}", true, set_alpha), c("element.set_blend", "Blending", "", None, "{mode: normal|layer|darken|multiply|lighten|screen|overlay|hardlight|add|subtract|difference|invert|alpha|erase} on the selected movie clip and button instances", true, set_blend), - c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them)", true, set_filters), + c("element.set_filters", "Filters", "", None, "{filters: [{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …values}]} replaces the selected movie clip and button instances' filters (in order; [] removes them). Bevel: shadow_color, highlight_color, side: inner|outer|full, knockout; gradient filters: stops: [{offset 0..1, color \"#rrggbbaa\"}] (Gradient Glow's start and Gradient Bevel's middle stay transparent)", true, set_filters), c("element.set_loop", "Looping", "", None, "{loop?: loop|play_once|single_frame, first_frame?}", true, set_loop), c("symbol.set_kind", "Symbol Type", "", None, "{kind: graphic|movie_clip|button, symbol?: id (default: the selected instance's)}", true, set_symbol_kind), c("element.rename", "Instance Name", "", None, "{name}", true, rename), @@ -320,14 +320,29 @@ const MAX_FILTERS: usize = 16; /// Filters for the selected movie clip and button instances (Animate offers them on those only). fn set_filters(s: &mut Session, p: &Value) -> Result { let mut list = p.get("filters").cloned().ok_or_else(|| EngineError::Param("param 'filters' is required (a list; [] removes them)".into()))?; - // Colours may be written "#rrggbb" (or "#rrggbbaa"), as everywhere in commands. + // Colours may be written "#rrggbb" (or "#rrggbbaa"), as everywhere in commands: the filter's + // own and its ramp stops'. + fn hex_colors(v: &mut Value, keys: &[&str]) -> Result<()> { + for k in keys { + if v.get(*k).is_some_and(Value::is_string) { + let c = opt_color(v, k)?.unwrap_or(anicraft_doc::Rgba::BLACK); + v[*k] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); + } + } + Ok(()) + } for f in list.as_array_mut().into_iter().flatten() { - if f.get("color").is_some_and(Value::is_string) { - let c = opt_color(f, "color")?.unwrap_or(anicraft_doc::Rgba::BLACK); - f["color"] = json!({"r": c.r, "g": c.g, "b": c.b, "a": c.a}); + hex_colors(f, &["color", "shadow_color", "highlight_color"])?; + if let Some(stops) = f.get_mut("stops").and_then(Value::as_array_mut) { + if stops.len() > anicraft_doc::MAX_RAMP_STOPS { + return Err(EngineError::Param(format!("a ramp has at most {} stops", anicraft_doc::MAX_RAMP_STOPS))); + } + for st in stops.iter_mut() { + hex_colors(st, &["color"])?; + } } } - let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|adjust_color, …}}: {e}")))?; + let filters: Vec = serde_json::from_value(list).map_err(|e| EngineError::Param(format!("'filters' must be a list of {{type: blur|drop_shadow|glow|bevel|gradient_glow|gradient_bevel|adjust_color, …}}: {e}")))?; if filters.len() > MAX_FILTERS { return Err(EngineError::Param(format!("at most {MAX_FILTERS} filters per instance"))); } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 6566a128..2937d776 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -555,6 +555,9 @@ fn panic_hunt_every_command() { json!({"hint": "a", "x": 1e7, "y": -1e7, "side": "end"}), json!({"hint": u64::MAX, "side": "middle", "x": 0, "y": 0}), json!({"hint": "zz", "frame": 0}), + json!({"filters": [{"type": "bevel", "blur_x": 1e30, "distance": -1e30, "angle": f64::MAX, "side": "full", "shadow_color": "#zz"}]}), + json!({"filters": [{"type": "gradient_glow", "stops": [1, "x", null]}, {"type": "gradient_bevel", "stops": "x"}]}), + json!({"filters": [{"type": "gradient_bevel", "stops": [{"offset": 1e30, "color": {"r": 9, "g": -9, "b": 0, "a": 2}}], "strength": -1, "quality": 255}]}), ]; // File commands are exercised separately (they touch the disk). let skip = |id: &str| id.starts_with("file."); @@ -1903,3 +1906,76 @@ fn filters_render_on_movie_clips_clip_after_masks_and_save() { run(&mut s, "edit.undo", json!({})); assert!(px(&s, 160, 150)[1] < 0.5, "unmasked again: the box shows"); } + +/// Extreme values in every new filter, on a movie clip: sanitized, rendered at several scales +/// and exported, never a panic or a non-number. +#[test] +fn hostile_bevel_and_gradient_filters_render_and_export() { + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 10, "y": 10, "w": 30, "h": 20, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + let stops = json!([{"offset": -5, "color": "#ff000000"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 99, "color": "#ffffff"}]); + for side in ["inner", "outer", "full"] { + for knockout in [false, true] { + // Huge values once (they clamp to the largest reach, which is slow to draw). + let huge = side == "full" && knockout; + let cases: &[(f64, f64, f64)] = if huge { &[(1e30, 1e30, 1e30), (255.0, -1000.0, 10.0)] } else { &[(0.0, 0.0, 0.0), (0.5, 0.3, 0.001), (12.0, -40.0, 3.0)] }; + for &(blur, distance, strength) in cases { + let common = json!({"blur_x": blur, "blur_y": blur / 3.0, "distance": distance, "strength": strength, "quality": 3, "angle": -720, "side": side, "knockout": knockout}); + let with = |t: &str| { + let mut f = common.clone(); + f["type"] = json!(t); + f["stops"] = stops.clone(); + f + }; + run(&mut s, "element.set_filters", json!({"filters": [with("bevel"), with("gradient_glow"), with("gradient_bevel")]})); + for scale in [0.05, if huge { 0.25 } else { 1.0 }] { + let img = anicraft_render::render_frame(&s.doc, 0, scale).unwrap(); + assert!(img.pixel(0, 0).unwrap().iter().all(|v| v.is_finite())); + } + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + assert!(!svg.contains("NaN") && !svg.contains("inf")); + } + } + } +} + +#[test] +fn bevel_and_gradient_filters_render_save_and_export() { + use anicraft_doc::{ElementKind, Filter, FilterSide}; + let mut s = Session::default(); + run(&mut s, "draw.rect", json!({"x": 100, "y": 100, "w": 100, "h": 100, "fill": "#ff0000", "stroke": null})); + run(&mut s, "modify.convert_to_symbol", json!({"name": "Box"})); + run(&mut s, "symbol.set_kind", json!({"kind": "movie_clip"})); + let px = |s: &Session, x, y| anicraft_render::render_frame(&s.doc, 0, 1.0).unwrap().pixel(x, y).unwrap(); + // A bevel lit from the top left, hex colours as in every command. + run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel", "blur_x": 0, "blur_y": 0, "distance": 6, "highlight_color": "#00ff00", "shadow_color": "#0000ff"}]})); + assert_eq!(px(&s, 102, 102), [0.0, 1.0, 0.0, 1.0], "highlight inside the top-left corner"); + assert_eq!(px(&s, 197, 197), [0.0, 0.0, 1.0, 1.0], "shadow inside the bottom-right corner"); + assert_eq!(px(&s, 150, 150), [1.0, 0.0, 0.0, 1.0]); + assert_eq!(px(&s, 95, 95), [1.0, 1.0, 1.0, 1.0], "inner: nothing outside"); + run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel", "blur_x": 0, "blur_y": 0, "distance": 6, "side": "outer", "knockout": true, "highlight_color": "#00ff00"}]})); + assert_eq!(px(&s, 97, 97), [0.0, 1.0, 0.0, 1.0], "outer: highlight outside the lit corner"); + assert_eq!(px(&s, 150, 150), [1.0, 1.0, 1.0, 1.0], "knocked out"); + // A gradient glow whose ramp ends in blue; its start stays transparent whatever is sent. + run(&mut s, "element.set_filters", json!({"filters": [{"type": "gradient_glow", "blur_x": 0, "blur_y": 0, "distance": 0, "stops": [{"offset": 0, "color": "#ff00ffff"}, {"offset": 1, "color": "#0000ff"}]}]})); + let ElementKind::Symbol { filters, .. } = &s.doc.timeline(s.scene).layers[0].keyframes[0].elements[0].kind else { panic!() }; + let Some(Filter::GradientGlow { stops, side: FilterSide::Outer, .. }) = filters.first() else { panic!("{filters:?}") }; + assert_eq!(stops[0].color.a, 0.0, "pinned transparent"); + assert_eq!(px(&s, 150, 150), [1.0, 0.0, 0.0, 1.0]); + assert!(s.execute("element.set_filters", &json!({"filters": [{"type": "gradient_bevel", "stops": vec![json!({"offset": 0.5, "color": "#ffffff"}); 16]}]})).is_err(), "too many stops"); + assert!(s.execute("element.set_filters", &json!({"filters": [{"type": "bevel", "side": "sideways"}]})).is_err()); + assert!(s.execute("element.set_filters", &json!({"filters": [{"type": "gradient_glow", "stops": [{"offset": 0, "color": "red"}]}]})).is_err()); + // All three save, load and export to SVG with standard primitives. + run(&mut s, "element.set_filters", json!({"filters": [{"type": "bevel", "side": "full"}, {"type": "gradient_glow", "side": "full", "knockout": true}, {"type": "gradient_bevel"}]})); + let text = crate::format::to_json(&s.doc).unwrap(); + assert_eq!(crate::format::from_json(&text).unwrap(), s.doc); + let svg = crate::cmds_file::frame_svg(&s.doc, 0); + for want in ["operator=\"arithmetic\" k2=\"1\" k3=\"-1\"", " { shadow(buf, w, h, Shadow { blur_x: blur_x * scale, blur_y: blur_y * scale, strength, quality, dx: 0, dy: 0, color, inner, knockout, hide_object: false }); } + Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, shadow_color, highlight_color, side, knockout } => { + let (dx, dy) = offset(angle, distance * scale); + let field = bevel_field(buf, w, h, blur_x * scale, blur_y * scale, quality, dx, dy); + let (hl, sh) = (premultiply(highlight_color), premultiply(shadow_color)); + let effect: Vec = field + .iter() + .map(|&d| { + let v = (d * strength).clamp(-1.0, 1.0); + if v >= 0.0 { scaled(hl, v) } else { scaled(sh, -v) } + }) + .collect(); + composite(buf, &effect, &effect, side, knockout); + } + Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } => { + let (dx, dy) = offset(angle, distance * scale); + let field = bevel_field(buf, w, h, blur_x * scale, blur_y * scale, quality, dx, dy); + let lut = ramp_lut(&stops); + let effect: Vec = field.iter().map(|&d| lut_at(&lut, 0.5 - 0.5 * (d * strength).clamp(-1.0, 1.0))).collect(); + composite(buf, &effect, &effect, side, knockout); + } + Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } => { + let (dx, dy) = offset(angle, distance * scale); + let lut = ramp_lut(&stops); + let glow = |inner: bool| -> Vec { + let mut cov = shifted_coverage(buf, w, h, dx, dy, inner); + blur_channels(&mut cov, w, h, blur_x * scale, blur_y * scale, quality); + cov.iter().map(|k| lut_at(&lut, (k[0] * strength).clamp(0.0, 1.0))).collect() + }; + let none = Vec::new(); + let inner = if side == FilterSide::Outer { None } else { Some(glow(true)) }; + let outer = if side == FilterSide::Inner { None } else { Some(glow(false)) }; + composite(buf, inner.as_ref().unwrap_or(&none), outer.as_ref().unwrap_or(&none), side, knockout); + } Filter::AdjustColor { brightness, contrast, saturation, hue } => adjust(buf, &color_matrix(brightness, contrast, saturation, hue)), } } } +/// Whole-pixel offset of `distance` along `angle` (degrees, clockwise from the right). +fn offset(angle: f32, distance: f32) -> (i64, i64) { + let a = angle.to_radians(); + ((distance * a.cos()).round() as i64, (distance * a.sin()).round() as i64) +} + +fn scaled(c: Premul, k: f32) -> Premul { + [c[0] * k, c[1] * k, c[2] * k, c[3] * k] +} + +/// The artwork's opacity (or, `inverse`, its transparency) moved by `(dx, dy)`; outside the +/// buffer the artwork is transparent. +fn shifted_coverage(buf: &[Premul], w: usize, h: usize, dx: i64, dy: i64, inverse: bool) -> Vec<[f32; 1]> { + let mut cov = vec![[0.0f32]; w * h]; + for y in 0..h as i64 { + for x in 0..w as i64 { + let a = alpha_at(buf, w, h, x - dx, y - dy); + if let Some(c) = cov.get_mut(y as usize * w + x as usize) { + c[0] = if inverse { 1.0 - a } else { a }; + } + } + } + cov +} + +fn alpha_at(buf: &[Premul], w: usize, h: usize, x: i64, y: i64) -> f32 { + if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { buf.get(y as usize * w + x as usize).map_or(0.0, |p| p[3]) } else { 0.0 } +} + +/// The bevel's signed field in −1..=1: the blurred opacity a distance towards the light +/// (`−(dx, dy)`) minus the blurred opacity a distance away from it. Positive where an edge faces +/// the light (highlight), negative where it faces away (shadow), 0 where flat. +#[allow(clippy::too_many_arguments)] +fn bevel_field(buf: &[Premul], w: usize, h: usize, bx: f32, by: f32, quality: u8, dx: i64, dy: i64) -> Vec { + let mut b: Vec<[f32; 1]> = buf.iter().map(|p| [p[3]]).collect(); + blur_channels(&mut b, w, h, bx, by, quality); + let at = |x: i64, y: i64| if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h { b.get(y as usize * w + x as usize).map_or(0.0, |v| v[0]) } else { 0.0 }; + let mut out = Vec::with_capacity(w * h); + for y in 0..h as i64 { + for x in 0..w as i64 { + out.push((at(x + dx, y + dy) - at(x - dx, y - dy)).clamp(-1.0, 1.0)); + } + } + out +} + +/// Steps in a gradient filter's ramp table: even, so 0, ½ and 1 (the ends and the bevel's +/// flat middle) are samples exactly. +const RAMP_STEPS: usize = 256; + +/// A gradient filter's ramp (sanitized stops) as `RAMP_STEPS + 1` premultiplied colours. +fn ramp_lut(stops: &[GradientStop]) -> Vec { + (0..=RAMP_STEPS).map(|i| premultiply(ramp_at(stops, i as f32 / RAMP_STEPS as f32))).collect() +} + +fn lut_at(lut: &[Premul], t: f32) -> Premul { + let i = if t.is_finite() { (t.clamp(0.0, 1.0) * RAMP_STEPS as f32).round() as usize } else { 0 }; + lut.get(i).copied().unwrap_or([0.0; 4]) +} + +/// Puts an effect with the artwork: `inner` atop it (inside its edge, over it), `outer` under +/// it (outside its edge), as `side` says; Knockout keeps only the effect, cut to its side. +/// Both are premultiplied, one per pixel (an empty list is no effect). +fn composite(buf: &mut [Premul], inner: &[Premul], outer: &[Premul], side: FilterSide, knockout: bool) { + let zero = [0.0f32; 4]; + for (i, p) in buf.iter_mut().enumerate() { + let ei = if side == FilterSide::Outer { zero } else { inner.get(i).copied().unwrap_or(zero) }; + let eo = if side == FilterSide::Inner { zero } else { outer.get(i).copied().unwrap_or(zero) }; + let src = *p; + let ba = src[3]; + for c in 0..4 { + p[c] = if knockout { ei[c] * ba + eo[c] * (1.0 - ba) } else { ei[c] * ba + src[c] * (1.0 - ei[3]) + eo[c] * (1.0 - ba) }; + } + } +} + /// Box blur of width `n` along rows (`stride` 1) or columns, `passes` times, of any number of /// channels per pixel. Outside the buffer is transparent. fn box_pass(buf: &mut [[f32; C]], w: usize, h: usize, n: usize, horizontal: bool, tmp: &mut Vec<[f32; C]>) { @@ -248,6 +365,99 @@ mod tests { assert_eq!(g[20 * w + 5][3], 0.0, "nothing outside"); } + fn bevel(side: FilterSide, knockout: bool) -> Filter { + Filter::Bevel { blur_x: 3.0, blur_y: 3.0, strength: 1.0, quality: 1, angle: 45.0, distance: 3.0, shadow_color: Rgba::BLACK, highlight_color: Rgba::WHITE, side, knockout } + } + + /// Red square `x0..x1` on a 40 × 40 buffer, through `f`. + fn filtered(f: &Filter) -> Vec { + let mut b = square(40, 40, 12, 28); + apply(&mut b, 40, 40, std::slice::from_ref(f), 1.0); + b + } + + #[test] + fn bevels_light_the_top_left_and_shade_the_bottom_right_symmetrically() { + let w = 40; + let b = filtered(&bevel(FilterSide::Inner, false)); + // Inside the top-left edge: white over red; inside the bottom-right: darkened red. + let tl = b[13 * w + 13]; + let br = b[26 * w + 26]; + assert!(tl[1] > 0.3 && (tl[3] - 1.0).abs() < 1e-5, "highlight: {tl:?}"); + assert!(br[0] < 0.7 && br[1] < 1e-5 && (br[3] - 1.0).abs() < 1e-5, "shadow: {br:?}"); + assert_eq!(b[20 * w + 20], [1.0, 0.0, 0.0, 1.0], "the flat middle is untouched"); + assert_eq!(b[5 * w + 5], [0.0; 4], "nothing outside an inner bevel"); + // Point symmetry: highlight at a pixel is the shadow at its mirror (white ↔ black). + for (x, y) in [(13, 13), (14, 20), (20, 13), (12, 27)] { + let (p, q) = (b[y * w + x], b[(39 - y) * w + (39 - x)]); + let lit = p[1]; // white added (green was 0) + let dark = 1.0 - q[0]; // red taken away by black + assert!((lit - dark).abs() < 1e-5, "({x}, {y}): {p:?} vs {q:?}"); + } + // The other diagonal corners see as much light as shade: they stay red. + let tr = b[13 * w + 26]; + assert!(tr[1] < 0.2 && tr[0] > 0.8, "{tr:?}"); + } + + #[test] + fn outer_full_and_knockout_bevels() { + let w = 40; + let outer = filtered(&bevel(FilterSide::Outer, false)); + assert_eq!(outer[20 * w + 20], [1.0, 0.0, 0.0, 1.0], "the artwork is on top"); + let out_tl = outer[11 * w + 11]; + let out_br = outer[28 * w + 28]; + assert!(out_tl[3] > 0.2 && (out_tl[0] - out_tl[3]).abs() < 1e-5 && (out_tl[1] - out_tl[3]).abs() < 1e-5, "white outside the lit edge: {out_tl:?}"); + assert!(out_br[3] > 0.2 && out_br[0] < 1e-5, "black outside the shaded edge: {out_br:?}"); + assert!((out_tl[3] - out_br[3]).abs() < 1e-5, "symmetric: {out_tl:?} {out_br:?}"); + assert_eq!(outer[13 * w + 13], [1.0, 0.0, 0.0, 1.0], "inside untouched"); + // Full: both, and knockout: only the effect (the flat middle and far outside clear). + let full = filtered(&bevel(FilterSide::Full, false)); + assert!(full[13 * w + 13][1] > 0.3 && full[11 * w + 11][3] > 0.2); + let ko = filtered(&bevel(FilterSide::Full, true)); + assert_eq!(ko[20 * w + 20][3], 0.0, "the artwork is knocked out"); + assert_eq!(ko[2 * w + 2][3], 0.0); + assert!((ko[13 * w + 13][3] - full[13 * w + 13][1]).abs() < 1e-5, "the highlight alone: {:?}", ko[13 * w + 13]); + let ko_in = filtered(&bevel(FilterSide::Inner, true)); + assert_eq!(ko_in[11 * w + 11][3], 0.0, "inner knockout has nothing outside"); + // Strength 0 changes nothing. + let Filter::Bevel { blur_x, blur_y, quality, angle, distance, shadow_color, highlight_color, .. } = bevel(FilterSide::Full, false) else { panic!() }; + let none = filtered(&Filter::Bevel { strength: 0.0, blur_x, blur_y, quality, angle, distance, shadow_color, highlight_color, side: FilterSide::Full, knockout: false }); + assert_eq!(none, square(40, 40, 12, 28)); + } + + #[test] + fn gradient_ramps_map_their_ends() { + let w = 40; + let st = |offset: f32, c: u32, a: f32| GradientStop { offset, color: Rgba::hex(c).with_alpha(a) }; + // A hard-edged glow (no blur) at full strength takes the ramp's end colour; past its + // reach, the transparent start. + let glow = |side, knockout, stops: Vec| Filter::GradientGlow { blur_x: 0.0, blur_y: 0.0, strength: 1.0, quality: 1, angle: 0.0, distance: 4.0, stops, side, knockout }.sanitized(); + let ramp = vec![st(0.0, 0xffffff, 0.0), st(1.0, 0x0000ff, 1.0)]; + let g = filtered(&glow(FilterSide::Outer, false, ramp.clone())); + assert_eq!(g[20 * w + 30], [0.0, 0.0, 1.0, 1.0], "blue glow, offset right"); + assert_eq!(g[20 * w + 10], [0.0; 4], "nothing on the far side"); + assert_eq!(g[20 * w + 20], [1.0, 0.0, 0.0, 1.0]); + // Blurred, the ramp's middle shows where the glow is half: here green. + let mid = vec![st(0.0, 0xffffff, 0.0), st(0.5, 0x00ff00, 1.0), st(1.0, 0x0000ff, 1.0)]; + let soft = filtered(&Filter::GradientGlow { blur_x: 9.0, blur_y: 0.0, strength: 1.0, quality: 1, angle: 0.0, distance: 0.0, stops: mid, side: FilterSide::Outer, knockout: false }); + let edge = soft[20 * w + 28]; // just outside the right edge: 4 of 9 covered + assert!(edge[1] > edge[2] && edge[1] > 0.4, "{edge:?}"); + // Inner gradient glow: the ramp's end inside the left edge (the transparency moved + // right into it), nothing outside; knockout keeps it alone. + let gi = filtered(&glow(FilterSide::Inner, true, ramp)); + assert_eq!(gi[20 * w + 13], [0.0, 0.0, 1.0, 1.0]); + assert_eq!(gi[20 * w + 20][3], 0.0); + assert_eq!(gi[20 * w + 5][3], 0.0); + // Gradient bevel: the highlight end on the lit edge, the shadow end on the other, + // the transparent middle in the flat. + let gb = Filter::GradientBevel { blur_x: 0.0, blur_y: 0.0, strength: 1.0, quality: 1, angle: 0.0, distance: 3.0, stops: vec![st(0.0, 0x00ff00, 1.0), st(0.5, 0, 0.0), st(1.0, 0x0000ff, 1.0)], side: FilterSide::Full, knockout: true }; + let b = filtered(&gb); + assert_eq!(b[20 * w + 13], [0.0, 1.0, 0.0, 1.0], "lit left edge (light from the left)"); + assert_eq!(b[20 * w + 26], [0.0, 0.0, 1.0, 1.0], "shaded right edge"); + assert_eq!(b[20 * w + 20][3], 0.0, "flat: the transparent middle"); + assert_eq!(b[20 * w + 10], [0.0, 1.0, 0.0, 1.0], "full: outside too"); + } + #[test] fn adjust_color_matrix() { let mut p = vec![[0.5, 0.25, 0.0, 1.0]]; diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 51494d23..7c4aa529 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -154,14 +154,13 @@ fn color_attrs(attr: &str, c: Rgba) -> String { /// An SVG `` for `filters` in `defs`, and its id; `None` when nothing carries across. /// Blur becomes a Gaussian of the same spread as the box-blur passes; outer drop shadows and -/// glows become `feDropShadow`; Adjust Color becomes its colour matrix. Inner and knockout -/// shadows and glows have no simple SVG equivalent and are left out. +/// glows become `feDropShadow`; Adjust Color becomes its colour matrix; bevels and gradient +/// filters are built from standard primitives ([`effect_svg`]). Inner and knockout shadows and +/// glows have no simple SVG equivalent and are left out. fn svg_filter(filters: &[anicraft_doc::Filter], defs: &mut String, n: &mut usize) -> Option { use anicraft_doc::Filter; - // A box of width b has variance (b² − 1) / 12; passes add. - let sigma = |b: f32, q: u8| ((f32::from(q) * (b * b - 1.0).max(0.0)) / 12.0).sqrt(); let mut prims = String::new(); - for f in filters.iter().map(Filter::sanitized) { + for (i, f) in filters.iter().map(Filter::sanitized).enumerate() { match f { Filter::Blur { blur_x, blur_y, quality } => { let _ = write!(prims, "", num(sigma(blur_x, quality)), num(sigma(blur_y, quality))); @@ -187,6 +186,7 @@ fn svg_filter(filters: &[anicraft_doc::Filter], defs: &mut String, n: &mut usize let values: Vec = m.iter().flatten().map(|v| num(*v)).collect(); let _ = write!(prims, "", values.join(" ")); } + Filter::Bevel { .. } | Filter::GradientGlow { .. } | Filter::GradientBevel { .. } => effect_svg(&f, i, &mut prims), Filter::DropShadow { .. } | Filter::Glow { .. } => {} } } @@ -199,6 +199,108 @@ fn svg_filter(filters: &[anicraft_doc::Filter], defs: &mut String, n: &mut usize Some(id) } +/// The Gaussian of the same spread as `q` box-blur passes of width `b` (a box of width `b` has +/// variance (b² − 1) / 12; passes add). +fn sigma(b: f32, q: u8) -> f32 { + ((f32::from(q) * (b * b - 1.0).max(0.0)) / 12.0).sqrt() +} + +/// Primitives for a bevel, gradient glow or gradient bevel (the `i`th filter): they take the +/// previous result (or the source) and leave the filtered image as the last result. The same +/// steps as the CPU renderer (`filters.rs`): the blurred opacity offset towards and away from +/// the light, and their difference (`feComposite` arithmetic) for a bevel's highlight and +/// shadow, or the offset blurred opacity for a glow's intensity, mapped through the ramp +/// (`feComponentTransfer` tables); then put atop the artwork (inner), under it (outer), both +/// (full), or alone (knockout). +fn effect_svg(f: &anicraft_doc::Filter, i: usize, prims: &mut String) { + use anicraft_doc::{Filter, FilterSide}; + let (blur_x, blur_y, strength, quality, angle, distance, side, knockout) = match f { + Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, side, knockout, .. } + | Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, side, knockout, .. } + | Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, side, knockout, .. } => (*blur_x, *blur_y, *strength, *quality, *angle, *distance, *side, *knockout), + _ => return, + }; + let a = angle.to_radians(); + let (dx, dy) = (num(distance * a.cos()), num(distance * a.sin())); + let (ndx, ndy) = (num(-distance * a.cos()), num(-distance * a.sin())); + let blur = format!("stdDeviation=\"{} {}\"", num(sigma(blur_x, quality)), num(sigma(blur_y, quality))); + let s = num(strength); + // The input, and its opacity alone. + let _ = write!(prims, ""); + // `stops` over the opacity of `from`, into `to`: opaque ramp colours from tables, cut by + // the ramp's own opacity. + let ramp = |prims: &mut String, stops: &[anicraft_doc::GradientStop], from: &str, to: &str| { + let table = |ch: fn(anicraft_doc::Rgba) -> f32| (0..=32).map(|j| num(ch(anicraft_doc::ramp_at(stops, j as f32 / 32.0)))).collect::>().join(" "); + let _ = write!( + prims, + "\ + \ + \ + ", + table(|c| c.r), + table(|c| c.g), + table(|c| c.b), + table(|c| c.a) + ); + }; + // Both bevels: the blurred opacity towards the light (l) and away from it (d). + let bevel_offsets = |prims: &mut String| { + let _ = write!(prims, ""); + }; + let (inner, outer) = match f { + Filter::Bevel { shadow_color, highlight_color, .. } => { + bevel_offsets(prims); + let flood = |c: anicraft_doc::Rgba| format!("flood-color=\"{}\" flood-opacity=\"{}\"", hex(c), num(c.a)); + let _ = write!( + prims, + "\ + \ + \ + \ + ", + flood(*highlight_color), + flood(*shadow_color) + ); + (format!("e{i}"), format!("e{i}")) + } + Filter::GradientBevel { stops, .. } => { + // The ramp position: 0.5 − strength × (towards − away) / 2. + bevel_offsets(prims); + let half = num(strength * 0.5); + let _ = write!(prims, ""); + ramp(prims, stops, &format!("t{i}"), &format!("e{i}")); + (format!("e{i}"), format!("e{i}")) + } + Filter::GradientGlow { stops, .. } => { + // Intensity: the blurred opacity (outside) or transparency (inside), offset. + let glow = |prims: &mut String, src: &str, to: &str| { + let _ = write!(prims, ""); + ramp(prims, stops, &format!("{to}t"), to); + }; + if side != FilterSide::Outer { + let _ = write!(prims, ""); + glow(prims, &format!("v{i}"), &format!("ei{i}")); + } + if side != FilterSide::Inner { + glow(prims, &format!("a{i}"), &format!("eo{i}")); + } + (format!("ei{i}"), format!("eo{i}")) + } + _ => return, + }; + let _ = match (side, knockout) { + (FilterSide::Inner, false) => write!(prims, ""), + (FilterSide::Inner, true) => write!(prims, ""), + (FilterSide::Outer, false) => write!(prims, ""), + (FilterSide::Outer, true) => write!(prims, ""), + (FilterSide::Full, false) => write!(prims, ""), + (FilterSide::Full, true) => write!( + prims, + "" + ), + }; +} + /// The fill attribute for `paint`, defining a gradient in `defs` when needed. `None` when the /// paint draws nothing. fn paint_attr(paint: &Paint, xf: &Affine, fx: &ColorEffect, defs: &mut String, n: &mut usize, image: Option<&std::sync::Arc>, images: &mut Vec<(usize, String)>) -> Option { diff --git a/crates/xfl/src/import.rs b/crates/xfl/src/import.rs index 640cf340..c9722fdf 100644 --- a/crates/xfl/src/import.rs +++ b/crates/xfl/src/import.rs @@ -8,13 +8,13 @@ //! library symbols (graphic, movie clip, button) with their own timelines, nested to any //! depth; bitmaps (library items, instances and bitmap fills) whose image is stored as PNG or //! JPEG in the package; text fields, laid out with this computer's fonts (`text`, ADR 0014). -//! Everything else (sound, motion tweens with property curves, bevel and gradient filters, +//! Everything else (sound, motion tweens with property curves, unknown filters, //! bitmaps kept only in Animate's own storage) is counted in the report instead of guessed at. use crate::edges::{self, Edge}; use crate::xml::{self, Element as X}; use anicraft_doc::{ - Bitmap, BitmapId, BlendMode, ColorEffect, Filter, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, + Bitmap, BitmapId, BlendMode, ColorEffect, Filter, FilterSide, Document, Easing, Element, ElementId, ElementKind, GradientStop, Keyframe, Layer, LayerId, LayerKind, LoopMode, Paint, Rgba, Shape, Stage, Stroke, Symbol, SymbolId, Scene, ShapeHint, SymbolKind, Timeline, Tween, TweenKind, }; use anicraft_geom::{Affine, FillRule, Path, Vec2}; @@ -107,6 +107,31 @@ struct Builder<'a> { faces: HashMap, } +/// A bevel or gradient filter's `type`: `inner`, `outer` or `full` (`default` when missing). +fn filter_side(el: &X, default: FilterSide) -> FilterSide { + match el.attr("type").map(str::trim) { + Some("inner") => FilterSide::Inner, + Some("outer") => FilterSide::Outer, + Some("full") => FilterSide::Full, + _ => default, + } +} + +/// A gradient filter's ramp: its `GradientEntry` children (directly, or in a wrapper), with +/// ratios 0..1 (or Flash's 0..255). +fn ramp(el: &X) -> Vec { + let entries = el.children.iter().flat_map(|c| if c.name == "GradientEntry" { std::slice::from_ref(c) } else { c.children.as_slice() }).filter(|g| g.name == "GradientEntry"); + let mut stops: Vec = entries + .take(anicraft_doc::MAX_RAMP_STOPS) + .map(|g| { + let r = g.f32("ratio").filter(|r| r.is_finite()).unwrap_or(0.0); + GradientStop { offset: if r > 1.0 { r / 255.0 } else { r }.clamp(0.0, 1.0), color: color(g, "color", "alpha") } + }) + .collect(); + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + stops +} + pub(crate) fn color(el: &X, key: &str, alpha_key: &str) -> Rgba { let rgb = el.attr(key).and_then(|c| u32::from_str_radix(c.trim().trim_start_matches('#'), 16).ok()).unwrap_or(0); Rgba::hex(rgb).with_alpha(el.f32(alpha_key).unwrap_or(1.0).clamp(0.0, 1.0)) @@ -229,8 +254,8 @@ impl<'a> Builder<'a> { out.push(self.element(ElementKind::Shape(shape), parent.mul(&matrix(el)), ColorEffect::default())); } - /// An instance's filters, by Animate's element names. Bevel and gradient filters are - /// reported, and switched-off filters left out. + /// An instance's filters, by Animate's element names; switched-off filters are left out, + /// and unknown ones reported. fn filters(&mut self, el: &X) -> Vec { let mut out = Vec::new(); for f in el.list("filters") { @@ -256,8 +281,30 @@ impl<'a> Builder<'a> { }, "GlowFilter" => Filter::Glow { blur_x: num("blurX", 5.0), blur_y: num("blurY", 5.0), strength: num("strength", 1.0), quality, color: color(f, "color", "alpha"), inner: flag("inner"), knockout: flag("knockout") }, "AdjustColorFilter" => Filter::AdjustColor { brightness: num("brightness", 0.0), contrast: num("contrast", 0.0), saturation: num("saturation", 0.0), hue: num("hue", 0.0) }, + "BevelFilter" => Filter::Bevel { + blur_x: num("blurX", 5.0), + blur_y: num("blurY", 5.0), + strength: num("strength", 1.0), + quality, + angle: num("angle", 45.0), + distance: num("distance", 5.0), + shadow_color: color(f, "shadowColor", "shadowAlpha"), + highlight_color: if f.attr("highlightColor").is_some() { color(f, "highlightColor", "highlightAlpha") } else { Rgba::WHITE.with_alpha(num("highlightAlpha", 1.0).clamp(0.0, 1.0)) }, + side: filter_side(f, FilterSide::Inner), + knockout: flag("knockout"), + }, + "GradientGlowFilter" | "GradientBevelFilter" => { + let glow = f.name == "GradientGlowFilter"; + let (blur_x, blur_y, strength, angle, distance, knockout) = (num("blurX", 5.0), num("blurY", 5.0), num("strength", 1.0), num("angle", 45.0), num("distance", 5.0), flag("knockout")); + let stops = ramp(f); + if glow { + Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops: if stops.is_empty() { anicraft_doc::default_glow_ramp() } else { stops }, side: filter_side(f, FilterSide::Outer), knockout } + } else { + Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops: if stops.is_empty() { anicraft_doc::default_bevel_ramp() } else { stops }, side: filter_side(f, FilterSide::Inner), knockout } + } + } _ => { - self.report.skip("bevel and gradient filters"); + self.report.skip("unknown filters"); continue; } }; diff --git a/crates/xfl/src/tests.rs b/crates/xfl/src/tests.rs index 9064337c..32301a0a 100644 --- a/crates/xfl/src/tests.rs +++ b/crates/xfl/src/tests.rs @@ -16,7 +16,11 @@ const DOC: &str = r##" - + + + + + @@ -93,6 +97,7 @@ fn stage_layers_frames_and_tweens() { assert!(report.skipped.keys().all(|k| !k.contains("text")), "an empty text field makes nothing and reports nothing"); assert_eq!(report.skipped.get("instances of missing bitmaps"), Some(&1)); assert_eq!(report.skipped.get("missing library files"), Some(&1)); + assert_eq!(report.skipped.get("unknown filters"), Some(&1)); // Frame scripts, on the scene's frames and inside symbols, are counted (ADR 0013). assert_eq!(report.skipped.get("frame scripts (ActionScript isn't supported yet)"), Some(&2)); // Every scene comes across, in order. @@ -138,9 +143,21 @@ fn symbols_instances_and_the_tween_between_them() { let inst = &doc.timeline(0).layers[0].keyframes[0].elements[0]; let ElementKind::Symbol { symbol, loop_mode, first_frame, blend, filters } = &inst.kind else { panic!("an instance") }; assert_eq!(*blend, anicraft_doc::BlendMode::HardLight, "Animate's blend mode names"); - assert_eq!(filters.len(), 2, "{filters:?}"); + assert_eq!(filters.len(), 5, "{filters:?}"); assert!(matches!(filters[0], anicraft_doc::Filter::DropShadow { distance, inner: false, .. } if distance == 8.0)); assert!(matches!(filters[1], anicraft_doc::Filter::Blur { blur_x, quality: 2, .. } if blur_x == 10.0)); + use anicraft_doc::{Filter, FilterSide}; + let Filter::Bevel { blur_x, blur_y, distance, angle, highlight_color, shadow_color, side, knockout, strength, .. } = filters[2] else { panic!("{:?}", filters[2]) }; + assert_eq!((blur_x, blur_y, distance, angle, side, knockout, strength), (4.0, 6.0, 3.0, 135.0, FilterSide::Full, true, 1.0)); + assert_eq!((highlight_color, shadow_color), (Rgba::hex(0xffff00).with_alpha(0.75), Rgba::BLACK.with_alpha(0.5))); + // Ramps: ratios 0..1 or 0..255; the glow's start pinned transparent, the bevel given a + // transparent middle (as Animate's panel keeps them). + let Filter::GradientGlow { stops, side: FilterSide::Inner, strength, .. } = &filters[3] else { panic!("{:?}", filters[3]) }; + assert_eq!(*strength, 2.0); + assert_eq!(stops.iter().map(|s| (s.offset, s.color.a)).collect::>(), vec![(0.0, 0.0), (128.0 / 255.0, 1.0), (1.0, 1.0)]); + let Filter::GradientBevel { stops, side: FilterSide::Inner, quality: 3, .. } = &filters[4] else { panic!("{:?}", filters[4]) }; + assert_eq!(stops.len(), 3); + assert_eq!((stops[1].offset, stops[1].color.a), (0.5, 0.0)); assert_eq!((*symbol, *loop_mode, *first_frame), (sym.id, LoopMode::PlayOnce, 2)); assert_eq!(inst.transform.m, [2.0, 0.0, 0.0, 2.0, 100.0, 50.0]); assert_eq!(inst.color.alpha, 0.5); diff --git a/src/app.rs b/src/app.rs index 93283796..e0e3d343 100644 --- a/src/app.rs +++ b/src/app.rs @@ -594,6 +594,20 @@ impl App { None => self.show_plugins = true, } } + Some("filters") => { + // A movie clip with a bevel and a gradient glow, selected: Properties › Filters + // shows both (scrolled to the glow's ramp editor). + self.run("draw.rect", json!({"x": 960, "y": 470, "w": 200, "h": 130, "fill": "#e8553b", "stroke": null})); + self.run("modify.convert_to_symbol", json!({"name": "Badge"})); + self.run("symbol.set_kind", json!({"kind": "movie_clip"})); + self.run( + "element.set_filters", + json!({"filters": [ + {"type": "bevel", "blur_x": 8, "blur_y": 8, "distance": 6, "strength": 1.2, "quality": 2}, + {"type": "gradient_glow", "blur_x": 28, "blur_y": 28, "quality": 2, "distance": 0, "stops": [{"offset": 0, "color": "#ffffff00"}, {"offset": 0.55, "color": "#ffd36b"}, {"offset": 1, "color": "#ff4d3d"}]}, + ]}), + ); + } Some("select") => { // The top layer's artwork selected, for its Properties. self.run("layer.select", json!({"index": 0})); diff --git a/src/main.rs b/src/main.rs index 91aa1fa1..52289618 100644 --- a/src/main.rs +++ b/src/main.rs @@ -121,7 +121,7 @@ fn main() -> eframe::Result { }, "--help" | "-h" => { println!( - "anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|hints|hintsend|prefs|licenses|zoom|recovery|plugins]\n\ + "anicraft [file.anicraft] [--screenshot out.png] [--renderer wgpu|gl] [--theme graphite|high-contrast] [--scale ] [--open palette|shortcuts|lastscene|select|about|files|confirm|transform|points|pen|frames|span|bucket|tlzoom|tlwide|motion|motionspan|hints|hintsend|filters|prefs|licenses|zoom|recovery|plugins]\n\ --renderer force the GPU backend (also ANICRAFT_RENDERER); default wgpu, falling back to OpenGL\n\ --open shows a panel at start (handy with --screenshot for visual checks)\n\ ANICRAFT_STAGE_RENDERER=gpu|cpu stage renderer, in builds with the gpu-stage feature (ADR 0019)\n\ diff --git a/src/panels.rs b/src/panels.rs index 5bfe2ea8..5a97a655 100644 --- a/src/panels.rs +++ b/src/panels.rs @@ -567,18 +567,13 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc } }); }; + let pin = anicraft_engine::doc::pinned_stop(f); match f { Filter::Blur { blur_x, blur_y, quality } => blur_rows(ui, blur_x, blur_y, quality, &mut changed), Filter::DropShadow { blur_x, blur_y, strength, quality, angle, distance, color, inner, knockout, hide_object } => { blur_rows(ui, blur_x, blur_y, quality, &mut changed); shadow_rows(ui, fname, strength, color, &mut changed); - row(ui, "Offset", |ui| { - let a = ui.add(egui::DragValue::new(angle).prefix("Angle ").suffix("°").speed(1.0).range(0.0..=360.0).max_decimals(0)).named("Shadow angle"); - let b = ui.add(egui::DragValue::new(distance).prefix("Distance ").suffix(" px").speed(0.25).range(-1000.0..=1000.0).max_decimals(1)).named("Shadow distance"); - if a.changed() || b.changed() { - changed = Some("Shadow offset"); - } - }); + offset_row(ui, fname, angle, distance, "Shadow offset", &mut changed); row_prose(ui, "Options", |ui| { for (v, label) in [(inner, "Inner"), (knockout, "Knockout"), (hide_object, "Hide object")] { if crate::theme::checkbox(ui, v, label).changed() { @@ -598,6 +593,28 @@ fn filter_rows(app: &mut App, ui: &mut egui::Ui, current: &[anicraft_engine::doc } }); } + Filter::Bevel { blur_x, blur_y, strength, quality, angle, distance, shadow_color, highlight_color, side, knockout } => { + blur_rows(ui, blur_x, blur_y, quality, &mut changed); + strength_row(ui, fname, strength, &mut changed); + row_prose(ui, "Colours", |ui| { + for (c, label, undo) in [(shadow_color, "Shadow", "Bevel shadow colour"), (highlight_color, "Highlight", "Bevel highlight colour")] { + ui.label(label); + if alpha_swatch(ui, c, &format!("{fname} {} colour", label.to_lowercase())) { + changed = Some(undo); + } + } + }); + offset_row(ui, fname, angle, distance, "Bevel offset", &mut changed); + side_rows(ui, fname, side, knockout, &mut changed); + } + Filter::GradientGlow { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } | Filter::GradientBevel { blur_x, blur_y, strength, quality, angle, distance, stops, side, knockout } => { + // The ramp first: it is what makes the filter. + ramp_editor(ui, fname, stops, pin, &mut changed); + blur_rows(ui, blur_x, blur_y, quality, &mut changed); + strength_row(ui, fname, strength, &mut changed); + offset_row(ui, fname, angle, distance, "Filter offset", &mut changed); + side_rows(ui, fname, side, knockout, &mut changed); + } Filter::AdjustColor { brightness, contrast, saturation, hue } => { for (v, label, range) in [(brightness, "Brightness", 100.0), (contrast, "Contrast", 100.0), (saturation, "Saturation", 100.0), (hue, "Hue", 180.0)] { row(ui, label, |ui| { @@ -637,6 +654,181 @@ fn shadow_rows(ui: &mut egui::Ui, fname: &str, strength: &mut f32, color: &mut R }); } +/// The Strength row of a bevel or gradient filter. +fn strength_row(ui: &mut egui::Ui, fname: &str, strength: &mut f32, changed: &mut Option<&'static str>) { + row(ui, "Strength", |ui| { + let mut pct = *strength * 100.0; + if ui.add(egui::DragValue::new(&mut pct).suffix(" %").speed(1.0).range(0.0..=1000.0).max_decimals(0)).named(&format!("{fname} strength")).changed() { + *strength = pct / 100.0; + *changed = Some("Filter strength"); + } + }); +} + +/// Angle and distance of a shadow, bevel or gradient filter. +fn offset_row(ui: &mut egui::Ui, fname: &str, angle: &mut f32, distance: &mut f32, undo: &'static str, changed: &mut Option<&'static str>) { + row(ui, "Offset", |ui| { + let a = ui + .add(egui::DragValue::new(angle).prefix("Angle ").suffix("°").speed(1.0).range(0.0..=360.0).max_decimals(0)) + .named(&format!("{fname} angle")) + .on_hover_text("The direction the shadow falls (the light comes from the opposite side)"); + let b = ui.add(egui::DragValue::new(distance).prefix("Distance ").suffix(" px").speed(0.25).range(-1000.0..=1000.0).max_decimals(1)).named(&format!("{fname} distance")); + if a.changed() || b.changed() { + *changed = Some(undo); + } + }); +} + +/// The Type (inner, outer, full) and Knockout rows of a bevel or gradient filter. +fn side_rows(ui: &mut egui::Ui, fname: &str, side: &mut anicraft_engine::doc::FilterSide, knockout: &mut bool, changed: &mut Option<&'static str>) { + use anicraft_engine::doc::FilterSide; + row_prose(ui, "Type", |ui| { + for (v, tip) in [(FilterSide::Inner, "Inside the artwork's edge"), (FilterSide::Outer, "Outside the artwork's edge"), (FilterSide::Full, "Inside and outside the edge")] { + if ui.selectable_label(*side == v, v.label()).named(&format!("{fname} type {}", v.label())).on_hover_text(tip).clicked() && *side != v { + *side = v; + *changed = Some("Filter type"); + } + } + }); + row_prose(ui, "Options", |ui| { + if crate::theme::checkbox(ui, knockout, "Knockout").named(&format!("{fname} knockout")).on_hover_text("Show only the effect, not the artwork").changed() { + *changed = Some("Filter options"); + } + }); +} + +/// A colour swatch with opacity (Animate's bevel colours carry alpha). True when changed. +fn alpha_swatch(ui: &mut egui::Ui, c: &mut Rgba, name: &str) -> bool { + let s = c.sanitized(); + let b = |v: f32| (v * 255.0).round() as u8; + let mut px = [b(s.r), b(s.g), b(s.b), b(s.a)]; + let r = ui.color_edit_button_srgba_unmultiplied(&mut px).named(name).on_hover_text(name); + if r.changed() { + *c = Rgba::new(f32::from(px[0]) / 255.0, f32::from(px[1]) / 255.0, f32::from(px[2]) / 255.0, f32::from(px[3]) / 255.0); + } + r.changed() +} + +/// A gradient filter's ramp, as Animate's: a strip of its colours over a checkerboard, a +/// marker under it per stop. Click a marker to pick that stop (its colour, position and Remove +/// below), drag it to move it, click the strip to add a stop there. The pinned stop (Gradient +/// Glow's start, Gradient Bevel's middle) can't move or go, and stays transparent. +fn ramp_editor(ui: &mut egui::Ui, fname: &str, stops: &mut Vec, pin: Option, changed: &mut Option<&'static str>) { + use anicraft_engine::doc::{GradientStop, MAX_RAMP_STOPS, ramp_at}; + let sel_id = ui.id().with("ramp_stop"); + let mut sel: usize = ui.data(|d| d.get_temp(sel_id)).unwrap_or(0); + let is_pinned = |s: &GradientStop| pin.is_some_and(|p| (s.offset - p).abs() < 1e-4); + row_prose(ui, "Gradient", |ui| { + ui.vertical(|ui| { + let w = ui.available_width().clamp(80.0, 200.0); + let (strip, resp) = ui.allocate_exact_size(vec2(w, 16.0), Sense::click()); + a11y::control(ui, &resp, WidgetType::Button, &format!("{fname} gradient: add a colour stop"), None); + let resp = resp.on_hover_text("Click to add a colour stop"); + let p = ui.painter(); + // A checkerboard under the ramp shows its opacity. + let cell = 4.0; + let (cols, rows) = ((strip.width() / cell).ceil() as usize, (strip.height() / cell).ceil() as usize); + p.rect_filled(strip, 0.0, T.header); + for (cx, cy) in (0..cols).flat_map(|x| (0..rows).map(move |y| (x, y))).filter(|(x, y)| (x + y) % 2 == 0) { + let r = Rect::from_min_size(pos2(strip.left() + cx as f32 * cell, strip.top() + cy as f32 * cell), vec2(cell, cell)).intersect(strip); + p.rect_filled(r, 0.0, T.text_faint); + } + let mut mesh = egui::Mesh::default(); + let steps = 48u32; + for i in 0..=steps { + let t = i as f32 / steps as f32; + let c = to_color32(ramp_at(stops, t)); + let x = strip.left() + t * strip.width(); + mesh.colored_vertex(pos2(x, strip.top()), c); + mesh.colored_vertex(pos2(x, strip.bottom()), c); + if i > 0 { + let k = 2 * i; + mesh.add_triangle(k - 2, k - 1, k); + mesh.add_triangle(k - 1, k, k + 1); + } + } + p.add(mesh); + p.rect_stroke(strip, 0.0, Stroke::new(1.0, T.border), StrokeKind::Outside); + // Markers: a small pointer per stop, under the strip. + let (track, _) = ui.allocate_exact_size(vec2(w, 12.0), Sense::hover()); + let mut moved = None; + for (i, st) in stops.iter_mut().enumerate() { + let x = strip.left() + st.offset * strip.width(); + let hit = Rect::from_center_size(pos2(x, track.center().y), vec2(10.0, 12.0)); + let pinned = is_pinned(st); + let r = ui.interact(hit, ui.id().with(("ramp_marker", i)), if pinned { Sense::click() } else { Sense::click_and_drag() }); + let label = format!("{fname} colour stop {} at {:.0}%{}", i + 1, st.offset * 100.0, if pinned { " (fixed)" } else { "" }); + a11y::control(ui, &r, WidgetType::Button, &label, Some(i == sel)); + if r.clicked() || r.drag_started() { + sel = i; + } + if r.dragged() + && !pinned + && let Some(at) = r.interact_pointer_pos() + { + st.offset = ((at.x - strip.left()) / strip.width()).clamp(0.0, 1.0); + sel = i; + moved = Some(*st); + *changed = Some("Move colour stop"); + } + let tip = pos2(x, track.top()); + let body = [tip, pos2(x + 5.0, track.top() + 5.0), pos2(x + 5.0, track.bottom()), pos2(x - 5.0, track.bottom()), pos2(x - 5.0, track.top() + 5.0)]; + let edge = if i == sel { T.accent } else if r.hovered() { T.text } else { T.control_edge }; + ui.painter().add(egui::Shape::convex_polygon(body.to_vec(), to_color32(st.color.with_alpha(1.0)), Stroke::new(if i == sel { 2.0 } else { 1.0 }, edge))); + } + // A dragged stop may pass another: keep the order, and the pick on it. + if let Some(m) = moved { + stops.sort_by(|a, b| a.offset.total_cmp(&b.offset)); + sel = stops.iter().position(|s| *s == m).unwrap_or(sel); + } + if resp.clicked() + && stops.len() < MAX_RAMP_STOPS + && let Some(at) = resp.interact_pointer_pos() + { + let t = ((at.x - strip.left()) / strip.width()).clamp(0.0, 1.0); + let new = GradientStop { offset: t, color: ramp_at(stops, t).with_alpha(1.0) }; + let i = stops.iter().position(|s| s.offset > t).unwrap_or(stops.len()); + stops.insert(i, new); + sel = i; + *changed = Some("Add colour stop"); + } + }); + }); + sel = sel.min(stops.len().saturating_sub(1)); + let mut remove = false; + let count = stops.len(); + if let Some(st) = stops.get_mut(sel) { + let pinned = is_pinned(st); + row(ui, "Stop", |ui| { + if pinned { + // Colour only: this stop stays transparent. + let mut c = rgb(st.color); + if ui.color_edit_button_srgb(&mut c).named(&format!("{fname} stop colour")).on_hover_text("Stop colour (this stop stays transparent)").changed() { + st.color = Rgba::new(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0, 0.0); + *changed = Some("Colour stop"); + } + } else if alpha_swatch(ui, &mut st.color, &format!("{fname} stop colour")) { + *changed = Some("Colour stop"); + } + let mut pct = st.offset * 100.0; + let r = ui.add_enabled(!pinned, egui::DragValue::new(&mut pct).suffix(" %").speed(0.5).range(0.0..=100.0).max_decimals(0)).named(&format!("{fname} stop position")); + if r.changed() { + st.offset = pct / 100.0; + *changed = Some("Move colour stop"); + } + if ui.add_enabled(!pinned && count > 2, egui::Button::new("Remove").small()).named(&format!("Remove {fname} colour stop")).on_hover_text("Remove this colour stop").clicked() { + remove = true; + } + }); + } + if remove && sel < stops.len() { + stops.remove(sel); + sel = sel.saturating_sub(1); + *changed = Some("Remove colour stop"); + } + ui.data_mut(|d| d.insert_temp(sel_id, sel)); +} + /// Font, size, style, colour, alignment and spacing rows for text. Returns the edit made, as /// `text.edit` params (one key per change), with an undo label. pub fn text_style_rows(app: &mut App, ui: &mut egui::Ui, st: &mut anicraft_engine::cmds_text::TextStyle, width: Option<&mut Option>) -> Option<(&'static str, Value)> {