From 9704735b5b5d290cd87eee8e4bfaa93c26db239a Mon Sep 17 00:00:00 2001 From: clover caruso Date: Wed, 2 Dec 2026 11:50:16 -0800 Subject: [PATCH] feat(engine): complete 100% of Fusion 2D shapes (sBSpline, sChangeStyle, sText) and particles (pAvoid..pTangentForce) --- crates/engine/src/eval/mod.rs | 9 + crates/engine/src/eval/shapes.rs | 142 ++- crates/engine/src/eval/shapes/collect.rs | 453 ++++------ .../engine/src/eval/shapes/collect_prims.rs | 684 +++++++++++++++ crates/engine/src/eval/shapes/geometry.rs | 813 ++++++------------ crates/engine/src/eval/shapes/modifiers.rs | 581 +++++++++++++ crates/engine/src/eval/shapes/raster.rs | 384 +++++++-- crates/engine/src/eval/shapes/tests.rs | 185 ++++ crates/engine/src/eval/warps_masks/bspline.rs | 90 +- crates/engine/src/particles.rs | 71 +- crates/engine/src/particles/custom.rs | 494 +++++++++++ crates/engine/src/particles/custom_eval.rs | 467 ++++++++++ crates/engine/src/particles/extra_forces.rs | 595 +++++++++++++ crates/engine/src/particles/extra_tests.rs | 342 ++++++++ crates/engine/src/particles/forces.rs | 53 +- crates/engine/src/particles/plan.rs | 28 +- crates/engine/src/particles/sim.rs | 62 +- crates/engine/src/particles/tests.rs | 25 +- crates/engine/src/text_engine.rs | 149 ++++ 19 files changed, 4665 insertions(+), 962 deletions(-) create mode 100644 crates/engine/src/eval/shapes/collect_prims.rs create mode 100644 crates/engine/src/eval/shapes/modifiers.rs create mode 100644 crates/engine/src/particles/custom.rs create mode 100644 crates/engine/src/particles/custom_eval.rs create mode 100644 crates/engine/src/particles/extra_forces.rs create mode 100644 crates/engine/src/particles/extra_tests.rs diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index 8dea757e8c9da5432be2c90e09b12224c2f79d43..f028d6fb7302fb286a1b0bbc752031e8ef3223a5 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -1069,6 +1069,9 @@ impl Engine { | "sEllipse" | "sStar" | "sPolygon" + | "sBSpline" + | "sChangeStyle" + | "sText" | "sGrid" | "sMerge" | "sTransform" @@ -1107,6 +1110,12 @@ impl Engine { | "pBounce" | "pVortex" | "pFlock" + | "pAvoid" + | "pFollow" + | "pTangentForce" + | "pCustom" + | "pCustomForce" + | "pImageEmitter" | "pSpawn" | "pChangeStyle" | "pGradientForce" => self.dummy.clone(), diff --git a/crates/engine/src/eval/shapes.rs b/crates/engine/src/eval/shapes.rs index 0fa26f0c56fdc716fc636813a2c950e575a01e67..91f1a51b5fbe610e78f7e0bd018cfe12f8d29991 100644 --- a/crates/engine/src/eval/shapes.rs +++ b/crates/engine/src/eval/shapes.rs @@ -1,15 +1,19 @@ //! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sPolygon`, -//! `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sBoolean`, `sOutline`). +//! `sBSpline`, `sText`, `sChangeStyle`, `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, +//! `sExpand`, `sOffset`, `sBoolean`, `sOutline`). mod collect; +mod collect_prims; mod geometry; +mod modifiers; mod raster; #[cfg(test)] mod tests; +use super::warps_masks::bspline::BSplinePoint; use super::*; -use collect::collect_shape_tree; +use collect::collect_shape_tree_by_name; use raster::rasterize_shape_tree_rgba8; /// Safety cap on total collected leaf primitives so nested `sDuplicate`/`sGrid` cannot blow up memory. @@ -75,6 +79,49 @@ impl Affine2D { } } +#[derive(Clone, Copy, Debug)] +enum ShapeCmd { + MoveTo([f32; 2]), + LineTo([f32; 2]), + QuadTo([f32; 2], [f32; 2]), + CurveTo([f32; 2], [f32; 2], [f32; 2]), + Close, +} + +impl ShapeCmd { + fn hash_into(self, h: &mut DefaultHasher) { + match self { + Self::MoveTo(p) => { + 0u8.hash(h); + p[0].to_bits().hash(h); + p[1].to_bits().hash(h); + } + Self::LineTo(p) => { + 1u8.hash(h); + p[0].to_bits().hash(h); + p[1].to_bits().hash(h); + } + Self::QuadTo(a, p) => { + 2u8.hash(h); + a[0].to_bits().hash(h); + a[1].to_bits().hash(h); + p[0].to_bits().hash(h); + p[1].to_bits().hash(h); + } + Self::CurveTo(a, b, p) => { + 3u8.hash(h); + a[0].to_bits().hash(h); + a[1].to_bits().hash(h); + b[0].to_bits().hash(h); + b[1].to_bits().hash(h); + p[0].to_bits().hash(h); + p[1].to_bits().hash(h); + } + Self::Close => 4u8.hash(h), + } + } +} + #[derive(Clone, Debug)] enum ShapePrimKind { NGon { sides: u32, width: f32, height: f32 }, @@ -82,6 +129,8 @@ enum ShapePrimKind { Ellipse { width: f32, height: f32 }, Star { points: u32, depth: f32, width: f32, height: f32, corner_radius: f32 }, Polygon { points: Vec, closed: bool }, + BSpline { points: Vec, closed: bool, tessellation: f32 }, + Text { cmds: Vec }, } #[derive(Clone, Copy, Debug)] @@ -102,6 +151,35 @@ struct OutlineStyle { write_len: f32, } +#[derive(Clone, Copy, Debug, Default)] +struct StyleOverride { + color: Option<[f32; 4]>, + solid: Option, + border_width: Option, + join_style: Option, + cap_style: Option, + line_type: Option, +} + +impl StyleOverride { + /// Combines an inner override with an outer override (outer takes precedence per field). + fn merge_outer(inner: Option, outer: Option) -> Option { + match (inner, outer) { + (None, None) => None, + (Some(a), None) => Some(a), + (None, Some(b)) => Some(b), + (Some(a), Some(b)) => Some(Self { + color: b.color.or(a.color), + solid: b.solid.or(a.solid), + border_width: b.border_width.or(a.border_width), + join_style: b.join_style.or(a.join_style), + cap_style: b.cap_style.or(a.cap_style), + line_type: b.line_type.or(a.line_type), + }), + } + } +} + #[derive(Clone, Copy, Debug)] enum PathModifier { Expand { @@ -176,8 +254,11 @@ enum ShapeTree { miter_limit: f32, write_pos: f32, write_len: f32, + fill_even_odd: bool, + line_type: u8, }, Group(Vec), + CombineGroup(Vec), Boolean { op: ShapeBoolOp, color: [f32; 4], @@ -207,6 +288,8 @@ impl ShapeTree { miter_limit, write_pos, write_len, + fill_even_odd, + line_type, } => { 0u8.hash(h); match kind { @@ -249,6 +332,24 @@ impl ShapeTree { pt.linear.hash(h); } } + ShapePrimKind::BSpline { points, closed, tessellation } => { + 6u8.hash(h); + closed.hash(h); + tessellation.to_bits().hash(h); + points.len().hash(h); + for pt in points { + pt.x.to_bits().hash(h); + pt.y.to_bits().hash(h); + pt.w.to_bits().hash(h); + } + } + ShapePrimKind::Text { cmds } => { + 7u8.hash(h); + cmds.len().hash(h); + for cmd in cmds { + cmd.hash_into(h); + } + } } xform.hash_into(h); for c in color { @@ -261,6 +362,8 @@ impl ShapeTree { miter_limit.to_bits().hash(h); write_pos.to_bits().hash(h); write_len.to_bits().hash(h); + fill_even_odd.hash(h); + line_type.hash(h); } ShapeTree::Group(children) => { 1u8.hash(h); @@ -269,6 +372,13 @@ impl ShapeTree { ch.hash_into(h); } } + ShapeTree::CombineGroup(children) => { + 4u8.hash(h); + children.len().hash(h); + for ch in children { + ch.hash_into(h); + } + } ShapeTree::Boolean { op, color, opacity, keep_style, a, b } => { 2u8.hash(h); (*op as u8).hash(h); @@ -311,21 +421,19 @@ impl Engine { let blend = 1.0_f32; let mut prim_budget = MAX_SHAPE_PRIMITIVES; - let shape_tree = node - .connected_node("Input") - .and_then(|s| comp.find_node(s)) - .and_then(|src_id| { - collect_shape_tree( - comp, - src_id, - time, - &self.expr, - Affine2D::identity(), - None, - 0, - &mut prim_budget, - ) - }); + let shape_tree = node.connected_node("Input").and_then(|src_name| { + collect_shape_tree_by_name( + comp, + src_name, + time, + &self.expr, + Affine2D::identity(), + None, + None, + 0, + &mut prim_budget, + ) + }); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); let mask_hash = mask.as_ref().map_or(0, |m| m.content_hash); diff --git a/crates/engine/src/eval/shapes/collect.rs b/crates/engine/src/eval/shapes/collect.rs index b9d0b2edc77360f62879384630c702ca0ffebb03..4533ac8d1482f72395c395420eae366593ff32cf 100644 --- a/crates/engine/src/eval/shapes/collect.rs +++ b/crates/engine/src/eval/shapes/collect.rs @@ -1,61 +1,53 @@ //! Graph collection for 2D vector shape nodes (`sNGon`, `sRectangle`, `sEllipse`, `sStar`, -//! `sPolygon`, `sTransform`, `sMerge`, `sGrid`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, -//! `sOutline`, `sBoolean`). +//! `sPolygon`, `sBSpline`, `sText`, `sChangeStyle`, `sTransform`, `sMerge`, `sGrid`, +//! `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sOutline`, `sBoolean`). -use model::{Comp, ExprEngine, Node, NodeId, ParamValue}; +use model::{Comp, ExprEngine, Node, NodeId}; -use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapePrimKind, ShapeTree}; +use super::collect_prims::{ + collect_basic_primitive, collect_raw_bspline_by_name, collect_s_change_style, collect_s_text, + eval_first_num, eval_xy_or_point, is_point_binding, +}; +use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapeTree, StyleOverride}; -fn eval_first_num( +#[allow(clippy::too_many_arguments)] +pub(super) fn collect_shape_tree_by_name( comp: &Comp, - node: &Node, - keys: &[&str], + name: &str, time: f64, - default: f64, expr: &ExprEngine, -) -> f64 { - for &k in keys { - if node.inputs.contains_key(k) { - return comp.eval_number(node, k, time, default, expr); - } + parent_xform: Affine2D, + outline_override: Option, + style_override: Option, + depth: usize, + prim_budget: &mut usize, +) -> Option { + if depth > 32 || *prim_budget == 0 { + return None; } - default -} - -fn eval_xy_or_point( - comp: &Comp, - node: &Node, - x_keys: &[&str], - y_keys: &[&str], - point_key: &str, - time: f64, - default: [f32; 2], - expr: &ExprEngine, -) -> [f32; 2] { - let pt = if node.inputs.contains_key(point_key) { - let p = comp.eval_point(node, point_key, time, [default[0] as f64, default[1] as f64], expr); - [p[0] as f32, p[1] as f32] - } else { - default - }; - let x = eval_first_num(comp, node, x_keys, time, pt[0] as f64, expr) as f32; - let y = eval_first_num(comp, node, y_keys, time, pt[1] as f64, expr) as f32; - [x, y] -} - -fn is_point_binding(comp: &Comp, node: &Node, key: &str) -> bool { - let Some(binding) = node.inputs.get(key) else { - return false; - }; - if matches!(binding.value, Some(ParamValue::Point(_))) { - return true; - } - if let Some(src) = &binding.source_op { - if comp.poly_paths.contains_key(src) { - return true; - } + if let Some(id) = comp.find_node(name) { + return collect_shape_tree( + comp, + id, + time, + expr, + parent_xform, + outline_override, + style_override, + depth, + prim_budget, + ); } - false + collect_raw_bspline_by_name( + comp, + name, + time, + expr, + parent_xform, + outline_override, + style_override, + prim_budget, + ) } /// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. @@ -72,45 +64,6 @@ fn parse_bool_op(node: &Node) -> Option { } } -/// Extracts `(points, closed)` for `sPolygon` from an animated `Polyline` spline, -/// a `PolyPath` modifier, or an inline `Polyline` table. -fn extract_polygon_polyline( - comp: &Comp, - node: &Node, - time: f64, - solid: bool, - expr: &ExprEngine, -) -> (Vec, bool) { - let explicit_closed = if node.inputs.contains_key("Closed") { - Some(comp.eval_number(node, "Closed", time, if solid { 1.0 } else { 0.0 }, expr) > 0.5) - } else { - None - }; - - if let Some(src) = node.connected_node("Polyline").or_else(|| node.connected_node("PolyLine")) { - if let Some(pts) = comp.eval_polyline_spline(src, time) { - return (pts, explicit_closed.unwrap_or(true)); - } - if let Some(pp) = comp.poly_paths.get(src) { - return (pp.points.clone(), explicit_closed.unwrap_or(pp.closed || solid)); - } - } - - if let Some(tbl) = node - .raw - .get_table("Inputs") - .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) - .and_then(|p| p.get_table("Value")) - { - let has_closed_key = tbl.get_bool("Closed").is_some(); - let (parsed_closed, pts) = model::PolyPath::parse_polyline_table(tbl); - let closed = explicit_closed.unwrap_or(if has_closed_key { parsed_closed } else { solid }); - return (pts, closed); - } - - (Vec::new(), explicit_closed.unwrap_or(solid)) -} - #[allow(clippy::too_many_arguments)] pub(super) fn collect_shape_tree( comp: &Comp, @@ -119,6 +72,7 @@ pub(super) fn collect_shape_tree( expr: &ExprEngine, parent_xform: Affine2D, outline_override: Option, + style_override: Option, depth: usize, prim_budget: &mut usize, ) -> Option { @@ -130,15 +84,15 @@ pub(super) fn collect_shape_tree( return node .connected_node("Input") .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree( + .and_then(|s| { + collect_shape_tree_by_name( comp, - id, + s, time, expr, parent_xform, outline_override, + style_override, depth + 1, prim_budget, ) @@ -146,122 +100,43 @@ pub(super) fn collect_shape_tree( } match node.kind.as_str() { - "sNGon" | "sRectangle" | "sEllipse" | "sStar" | "sPolygon" => { - *prim_budget = prim_budget.saturating_sub(1); - let [tx, ty] = eval_xy_or_point( + "sNGon" | "sRectangle" | "sEllipse" | "sStar" | "sPolygon" | "sBSpline" => { + collect_basic_primitive( comp, node, - &["Translate.X", "XOffset"], - &["Translate.Y", "YOffset"], - "Translate", time, - [0.0, 0.0], expr, - ); - let [px, py] = eval_xy_or_point( - comp, - node, - &["XPivot", "Pivot.X"], - &["YPivot", "Pivot.Y"], - "Pivot", - time, - [0.0, 0.0], - expr, - ); - let base_scale = comp.eval_number(node, "Scale", time, 1.0, expr); - let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; - let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; - let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; - - let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { - Affine2D::translate(tx + px, ty + py) - .mul(Affine2D::rotate_deg(angle)) - .mul(Affine2D::scale(sx, sy)) - .mul(Affine2D::translate(-px, -py)) - } else { - Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) - }; - let xform = parent_xform.mul(local); - - let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; - let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; - let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; - let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; - let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; - - let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; - let mut border_width = comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32; - let mut join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; - let mut cap_style = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; - let mut miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; - let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; - let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; - - if let Some(ov) = outline_override { - solid = false; - border_width = ov.thickness; - join_style = ov.join; - cap_style = ov.cap; - miter_limit = ov.miter_limit; - write_pos = ov.write_pos; - write_len = ov.write_len; - } - - let kind = match node.kind.as_str() { - "sNGon" => { - let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; - let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; - let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; - ShapePrimKind::NGon { sides, width, height } - } - "sRectangle" => { - let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; - let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; - let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; - ShapePrimKind::Rectangle { width, height, corner_radius } - } - "sStar" => { - let points = eval_first_num(comp, node, &["Points", "NumberOfPoints"], time, 6.0, expr) - .round() - .clamp(3.0, 256.0) as u32; - let depth = comp.eval_number(node, "Depth", time, 0.5, expr).clamp(0.0, 2.0) as f32; - let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; - let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; - let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; - ShapePrimKind::Star { points, depth, width, height, corner_radius } - } - "sPolygon" => { - let (points, closed) = extract_polygon_polyline(comp, node, time, solid, expr); - if points.len() < 2 { - return None; - } - ShapePrimKind::Polygon { points, closed } - } - _ => { - let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; - let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; - ShapePrimKind::Ellipse { width, height } - } - }; - - Some(ShapeTree::Primitive { - kind, - xform, - color: [r * opacity, g * opacity, b * opacity, a * opacity], - solid, - border_width, - join_style, - cap_style, - miter_limit, - write_pos, - write_len, - }) + parent_xform, + outline_override, + style_override, + prim_budget, + ) } + "sText" => collect_s_text( + comp, + node, + time, + expr, + parent_xform, + outline_override, + style_override, + prim_budget, + ), + "sChangeStyle" => collect_s_change_style( + comp, + node, + time, + expr, + parent_xform, + outline_override, + style_override, + depth, + prim_budget, + ), "sTransform" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let [ox, oy] = eval_xy_or_point( comp, node, @@ -292,13 +167,22 @@ pub(super) fn collect_shape_tree( .mul(Affine2D::scale(sx, sy)) .mul(Affine2D::translate(-px, -py)); let combined = parent_xform.mul(local); - collect_shape_tree(comp, src_id, time, expr, combined, outline_override, depth + 1, prim_budget) + collect_shape_tree_by_name( + comp, + src_name, + time, + expr, + combined, + outline_override, + style_override, + depth + 1, + prim_budget, + ) } "sDuplicate" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let copies = comp.eval_number(node, "Copies", time, 2.0, expr).round().clamp(0.0, 256.0) as usize; if copies == 0 { return None; @@ -349,13 +233,14 @@ pub(super) fn collect_shape_tree( } let copy_time = time + (i as f64) * time_offset; let copy_xf = parent_xform.mul(cum_xf); - if let Some(tree) = collect_shape_tree( + if let Some(tree) = collect_shape_tree_by_name( comp, - src_id, + src_name, copy_time, expr, copy_xf, outline_override, + style_override, depth + 1, prim_budget, ) { @@ -370,10 +255,9 @@ pub(super) fn collect_shape_tree( } } "sJitter" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let has_x = node.inputs.contains_key("XAmount") || node.inputs.contains_key("PositionX") @@ -408,13 +292,14 @@ pub(super) fn collect_shape_tree( let per_shape = matches!(node.static_str("Mode").or_else(|| node.static_str("JitterMode")), Some("Shape" | "PerShape")) || comp.eval_number(node, "PerShape", time, 0.0, expr) > 0.5; - let child = collect_shape_tree( + let child = collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, Affine2D::identity(), outline_override, + style_override, depth + 1, prim_budget, )?; @@ -447,34 +332,35 @@ pub(super) fn collect_shape_tree( }) } "sExpand" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let amount = eval_first_num(comp, node, &["Amount", "Distance", "Expand", "Offset"], time, 0.0, expr) as f32; let join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; if amount.abs() <= 1e-6 { - return collect_shape_tree( + return collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, parent_xform, outline_override, + style_override, depth + 1, prim_budget, ); } - let child = collect_shape_tree( + let child = collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, Affine2D::identity(), outline_override, + style_override, depth + 1, prim_budget, )?; @@ -489,10 +375,9 @@ pub(super) fn collect_shape_tree( }) } "sOffset" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let mut offset_x = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; let mut offset_y = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; @@ -513,25 +398,27 @@ pub(super) fn collect_shape_tree( // Fast path: pure 2D translation with no contour normal offset or path position shift. if contour_offset.abs() <= 1e-6 && position.abs() <= 1e-6 { let combined = parent_xform.mul(Affine2D::translate(offset_x, offset_y)); - return collect_shape_tree( + return collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, combined, outline_override, + style_override, depth + 1, prim_budget, ); } - let child = collect_shape_tree( + let child = collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, Affine2D::identity(), outline_override, + style_override, depth + 1, prim_budget, )?; @@ -561,14 +448,15 @@ pub(super) fn collect_shape_tree( ports.sort_by_key(|&(idx, _)| idx); let mut children = Vec::new(); for (_, port) in ports { - if let Some(src_id) = node.connected_node(port).and_then(|s| comp.find_node(s)) { - if let Some(tree) = collect_shape_tree( + if let Some(src_name) = node.connected_node(port) { + if let Some(tree) = collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, parent_xform, outline_override, + style_override, depth + 1, prim_budget, ) { @@ -583,10 +471,9 @@ pub(super) fn collect_shape_tree( } } "sGrid" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let cells_x = comp.eval_number(node, "CellsX", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; let cells_y = comp.eval_number(node, "CellsY", time, 3.0, expr).round().clamp(1.0, 256.0) as usize; let x_off = comp.eval_number(node, "XOffset", time, 0.2, expr) as f32; @@ -600,13 +487,14 @@ pub(super) fn collect_shape_tree( } let tx = (ix as f32 - (cells_x as f32 - 1.0) * 0.5) * x_off; let cell_xf = parent_xform.mul(Affine2D::translate(tx, ty)); - if let Some(tree) = collect_shape_tree( + if let Some(tree) = collect_shape_tree_by_name( comp, - src_id, + src_name, time, expr, cell_xf, outline_override, + style_override, depth + 1, prim_budget, ) { @@ -617,25 +505,34 @@ pub(super) fn collect_shape_tree( if children.is_empty() { None } else { - Some(ShapeTree::Group(children)) + Some(ShapeTree::CombineGroup(children)) } } "sOutline" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; + .or_else(|| node.connected_node("Input1"))?; let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr) as f32; if thickness <= 0.0 { return None; } let join = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; - let cap = comp.eval_number(node, "CapStyle", time, 0.0, expr).round().clamp(0.0, 2.0) as u8; + let cap = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; let miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; let write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; let write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; let style = OutlineStyle { thickness, join, cap, miter_limit, write_pos, write_len }; - collect_shape_tree(comp, src_id, time, expr, parent_xform, Some(style), depth + 1, prim_budget) + collect_shape_tree_by_name( + comp, + src_name, + time, + expr, + parent_xform, + Some(style), + style_override, + depth + 1, + prim_budget, + ) } "sBoolean" => { let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; @@ -643,39 +540,44 @@ pub(super) fn collect_shape_tree( let b_col = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; let a_col = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; - let keep_style = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; - let color = [r * opacity, g * opacity, b_col * opacity, a_col * opacity]; + let mut keep_style = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; + let mut color = [r * opacity, g * opacity, b_col * opacity, a_col * opacity]; + if let Some(sv) = style_override { + if let Some(c) = sv.color { + color = c; + keep_style = false; + } + } + let child_sv = if keep_style { style_override } else { None }; let a = node .connected_node("Input1") .or_else(|| node.connected_node("Input")) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree( + .and_then(|s| { + collect_shape_tree_by_name( comp, - id, + s, time, expr, parent_xform, outline_override, + child_sv, depth + 1, prim_budget, ) })?; - let b_opt = node - .connected_node("Input2") - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree( - comp, - id, - time, - expr, - parent_xform, - outline_override, - depth + 1, - prim_budget, - ) - }); + let b_opt = node.connected_node("Input2").and_then(|s| { + collect_shape_tree_by_name( + comp, + s, + time, + expr, + parent_xform, + outline_override, + child_sv, + depth + 1, + prim_budget, + ) + }); // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. let (op, b) = match (parse_bool_op(node), b_opt) { (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), @@ -692,15 +594,34 @@ pub(super) fn collect_shape_tree( }) } "PipeRouter" | "Fuse.Wireless" => { - let src_id = node + let src_name = node .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - collect_shape_tree(comp, src_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) + .or_else(|| node.connected_node("Input1"))?; + collect_shape_tree_by_name( + comp, + src_name, + time, + expr, + parent_xform, + outline_override, + style_override, + depth + 1, + prim_budget, + ) } "MacroOperator" | "GroupOperator" => { let out_id = node.macro_output?; - collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) + collect_shape_tree( + comp, + out_id, + time, + expr, + parent_xform, + outline_override, + style_override, + depth + 1, + prim_budget, + ) } _ => None, } diff --git a/crates/engine/src/eval/shapes/collect_prims.rs b/crates/engine/src/eval/shapes/collect_prims.rs new file mode 100644 index 0000000000000000000000000000000000000000..75ce2b4e466230bcc5b154ebac55ec4797c3ff00 --- /dev/null +++ b/crates/engine/src/eval/shapes/collect_prims.rs @@ -0,0 +1,684 @@ +//! Collection helpers for leaf 2D shape primitives (`sNGon`, `sRectangle`, `sEllipse`, +//! `sStar`, `sPolygon`, `sBSpline`, `sText`) and `sChangeStyle`. + +use model::{Comp, ExprEngine, InputBinding, LuaKey, Node, NodeId, ParamValue}; + +use super::super::warps_masks::bspline::{eval_bspline_shape, find_tool_table_in_tools}; +use super::collect::collect_shape_tree_by_name; +use super::{ + Affine2D, OutlineStyle, ShapeCmd, ShapePrimKind, ShapeTree, StyleOverride, +}; + +pub(super) fn eval_first_num( + comp: &Comp, + node: &Node, + keys: &[&str], + time: f64, + default: f64, + expr: &ExprEngine, +) -> f64 { + for &k in keys { + if node.inputs.contains_key(k) { + return comp.eval_number(node, k, time, default, expr); + } + } + default +} + +pub(super) fn eval_xy_or_point( + comp: &Comp, + node: &Node, + x_keys: &[&str], + y_keys: &[&str], + point_key: &str, + time: f64, + default: [f32; 2], + expr: &ExprEngine, +) -> [f32; 2] { + eval_xy_or_point_keys(comp, node, x_keys, y_keys, &[point_key], time, default, expr) +} + +fn eval_xy_or_point_keys( + comp: &Comp, + node: &Node, + x_keys: &[&str], + y_keys: &[&str], + point_keys: &[&str], + time: f64, + default: [f32; 2], + expr: &ExprEngine, +) -> [f32; 2] { + let mut pt = default; + for &pk in point_keys { + if node.inputs.contains_key(pk) { + let p = comp.eval_point(node, pk, time, [default[0] as f64, default[1] as f64], expr); + pt = [p[0] as f32, p[1] as f32]; + break; + } + } + let x = eval_first_num(comp, node, x_keys, time, pt[0] as f64, expr) as f32; + let y = eval_first_num(comp, node, y_keys, time, pt[1] as f64, expr) as f32; + [x, y] +} + +pub(super) fn is_point_binding(comp: &Comp, node: &Node, key: &str) -> bool { + let Some(binding) = node.inputs.get(key) else { + return false; + }; + if matches!(binding.value, Some(ParamValue::Point(_))) { + return true; + } + if let Some(src) = &binding.source_op { + if comp.poly_paths.contains_key(src) { + return true; + } + } + false +} + +fn eval_text_anchor_h(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { + if node.inputs.contains_key("HorizontalLeftCenterRight") { + return comp.eval_number(node, "HorizontalLeftCenterRight", time, 0.0, expr) as f32; + } + if let Some(s) = node.static_str("HAnchor") { + return match s { + "Left" => -1.0, + "Right" => 1.0, + _ => 0.0, + }; + } + if node.inputs.contains_key("HAnchor") { + return comp.eval_number(node, "HAnchor", time, 0.0, expr) as f32; + } + if comp.eval_number(node, "HorizontalJustificationLeft", time, 0.0, expr) > 0.5 { + return -1.0; + } + if comp.eval_number(node, "HorizontalJustificationRight", time, 0.0, expr) > 0.5 { + return 1.0; + } + if comp.eval_number(node, "HorizontalJustificationCenter", time, 0.0, expr) > 0.5 { + return 0.0; + } + let jnew = comp.eval_number(node, "HorizontalJustificationNew", time, -1.0, expr).round() as i32; + match jnew { + 0 => -1.0, + 2 => 1.0, + _ => 0.0, + } +} + +fn eval_text_anchor_v(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> f32 { + if node.inputs.contains_key("VerticalTopCenterBottom") { + return comp.eval_number(node, "VerticalTopCenterBottom", time, 0.0, expr) as f32; + } + if let Some(s) = node.static_str("VAnchor") { + return match s { + "Top" => -1.0, + "Bottom" => 1.0, + _ => 0.0, + }; + } + if node.inputs.contains_key("VAnchor") { + return comp.eval_number(node, "VAnchor", time, 0.0, expr) as f32; + } + if comp.eval_number(node, "VerticalJustificationTop", time, 0.0, expr) > 0.5 { + return -1.0; + } + if comp.eval_number(node, "VerticalJustificationBottom", time, 0.0, expr) > 0.5 { + return 1.0; + } + if comp.eval_number(node, "VerticalJustificationCenter", time, 0.0, expr) > 0.5 { + return 0.0; + } + let jnew = comp.eval_number(node, "VerticalJustificationNew", time, -1.0, expr).round() as i32; + match jnew { + 0 => -1.0, + 2 => 1.0, + _ => 0.0, + } +} + +fn parse_line_type(node: &Node, comp: &Comp, time: f64, expr: &ExprEngine) -> u8 { + for key in ["LineType", "LineStyle"] { + if let Some(s) = node.static_str(key) { + return match s { + "Dash" => 1, + "Dot" => 2, + "DashDot" | "Dash Dot" => 3, + "DashDotDot" | "Dash Dot Dot" => 4, + _ => 0, + }; + } + if node.inputs.contains_key(key) { + return comp.eval_number(node, key, time, 0.0, expr).round().clamp(0.0, 4.0) as u8; + } + } + 0 +} + +fn extract_polygon_polyline( + comp: &Comp, + node: &Node, + time: f64, + solid: bool, + expr: &ExprEngine, +) -> (Vec, bool) { + let explicit_closed = if node.inputs.contains_key("Closed") { + Some(comp.eval_number(node, "Closed", time, if solid { 1.0 } else { 0.0 }, expr) > 0.5) + } else { + None + }; + + if let Some(src) = node.connected_node("Polyline").or_else(|| node.connected_node("PolyLine")) { + if let Some(pts) = comp.eval_polyline_spline(src, time) { + return (pts, explicit_closed.unwrap_or(true)); + } + if let Some(pp) = comp.poly_paths.get(src) { + return (pp.points.clone(), explicit_closed.unwrap_or(pp.closed || solid)); + } + } + + if let Some(tbl) = node + .raw + .get_table("Inputs") + .and_then(|i| i.get_table("Polyline").or_else(|| i.get_table("PolyLine"))) + .and_then(|p| p.get_table("Value")) + { + let has_closed_key = tbl.get_bool("Closed").is_some(); + let (parsed_closed, pts) = model::PolyPath::parse_polyline_table(tbl); + let closed = explicit_closed.unwrap_or(if has_closed_key { parsed_closed } else { solid }); + return (pts, closed); + } + + (Vec::new(), explicit_closed.unwrap_or(solid)) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn collect_basic_primitive( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option, + style_override: Option, + prim_budget: &mut usize, +) -> Option { + *prim_budget = prim_budget.saturating_sub(1); + let is_bspline = node.kind == "sBSpline"; + let [tx, ty] = eval_xy_or_point_keys( + comp, + node, + &["Translate.X", "Center.X", "XOffset"], + &["Translate.Y", "Center.Y", "YOffset"], + &["Translate", "Center"], + time, + [0.0, 0.0], + expr, + ); + let [px, py] = eval_xy_or_point( + comp, + node, + &["XPivot", "Pivot.X"], + &["YPivot", "Pivot.Y"], + "Pivot", + time, + [0.0, 0.0], + expr, + ); + let base_scale = eval_first_num(comp, node, &["Scale", "Size"], time, 1.0, expr); + let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; + let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; + let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; + + let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { + Affine2D::translate(tx + px, ty + py) + .mul(Affine2D::rotate_deg(angle)) + .mul(Affine2D::scale(sx, sy)) + .mul(Affine2D::translate(-px, -py)) + } else { + Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) + }; + let xform = parent_xform.mul(local); + + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; + let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; + + let mut solid = comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5; + let default_bw = if is_bspline { 0.0 } else { 0.01 }; + let mut border_width = comp.eval_number(node, "BorderWidth", time, default_bw, expr).abs() as f32; + let mut join_style = comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8; + let mut cap_style = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; + let mut miter_limit = comp.eval_number(node, "MiterLimit", time, 10.0, expr).max(1.0) as f32; + let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; + let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; + let fill_even_odd = if is_bspline || node.inputs.contains_key("FillMethod") { + comp.eval_number(node, "FillMethod", time, 1.0, expr) < 0.5 + } else { + false + }; + let mut line_type = parse_line_type(node, comp, time, expr); + let mut color = [r * opacity, g * opacity, b * opacity, a * opacity]; + + if let Some(sv) = style_override { + if let Some(c) = sv.color { + color = c; + } + if let Some(s) = sv.solid { + solid = s; + } + if let Some(bw) = sv.border_width { + border_width = bw; + } + if let Some(js) = sv.join_style { + join_style = js; + } + if let Some(cs) = sv.cap_style { + cap_style = cs; + } + if let Some(lt) = sv.line_type { + line_type = lt; + } + } + + if let Some(ov) = outline_override { + solid = false; + border_width = ov.thickness; + join_style = ov.join; + cap_style = ov.cap; + miter_limit = ov.miter_limit; + write_pos = ov.write_pos; + write_len = ov.write_len; + } + + let kind = match node.kind.as_str() { + "sNGon" => { + let sides = comp.eval_number(node, "Sides", time, 6.0, expr).round().clamp(3.0, 256.0) as u32; + let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; + let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; + ShapePrimKind::NGon { sides, width, height } + } + "sRectangle" => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; + ShapePrimKind::Rectangle { width, height, corner_radius } + } + "sStar" => { + let points = eval_first_num(comp, node, &["Points", "NumberOfPoints"], time, 6.0, expr) + .round() + .clamp(3.0, 256.0) as u32; + let depth = comp.eval_number(node, "Depth", time, 0.5, expr).clamp(0.0, 2.0) as f32; + let width = eval_first_num(comp, node, &["Width", "Size"], time, 0.5, expr).abs() as f32; + let height = eval_first_num(comp, node, &["Height"], time, width as f64, expr).abs() as f32; + let corner_radius = comp.eval_number(node, "CornerRadius", time, 0.0, expr).max(0.0) as f32; + ShapePrimKind::Star { points, depth, width, height, corner_radius } + } + "sPolygon" => { + let (points, closed) = extract_polygon_polyline(comp, node, time, solid, expr); + if points.len() < 2 { + return None; + } + ShapePrimKind::Polygon { points, closed } + } + "sBSpline" => { + let bs = eval_bspline_shape(comp, node, time); + let closed = if node.inputs.contains_key("Closed") { + comp.eval_number(node, "Closed", time, if bs.closed { 1.0 } else { 0.0 }, expr) > 0.5 + } else { + bs.closed + }; + if (closed && bs.points.len() < 3) || (!closed && bs.points.len() < 2) { + return None; + } + if !solid && border_width <= 1e-6 { + return None; + } + let tessellation = comp.eval_number(node, "Tessellation", time, 2.0, expr) as f32; + ShapePrimKind::BSpline { points: bs.points, closed, tessellation } + } + _ => { + let width = comp.eval_number(node, "Width", time, 0.5, expr).abs() as f32; + let height = comp.eval_number(node, "Height", time, 0.5, expr).abs() as f32; + ShapePrimKind::Ellipse { width, height } + } + }; + + Some(ShapeTree::Primitive { + kind, + xform, + color, + solid, + border_width, + join_style, + cap_style, + miter_limit, + write_pos, + write_len, + fill_even_odd, + line_type, + }) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn collect_s_text( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option, + style_override: Option, + prim_budget: &mut usize, +) -> Option { + *prim_budget = prim_budget.saturating_sub(1); + let enabled1 = comp.eval_number(node, "Enabled1", time, 1.0, expr) > 0.5; + if !enabled1 && outline_override.is_none() { + return None; + } + let text_str = comp.eval_text(node, "StyledText", time, "", expr); + if text_str.is_empty() { + return None; + } + let font_family = node.static_str("Font").unwrap_or("Open Sans"); + let font_style = node.static_str("Style").unwrap_or("Bold"); + let size_norm = comp.eval_number(node, "Size", time, 0.08, expr) as f32; + let tracking = eval_first_num( + comp, + node, + &["CharacterSpacing", "CharacterSpacingClone", "Tracking"], + time, + 1.0, + expr, + ) as f32; + let line_spacing = eval_first_num( + comp, + node, + &["LineSpacing", "LineSpacingClone"], + time, + 1.0, + expr, + ) as f32; + let h_lcr = eval_text_anchor_h(comp, node, time, expr); + let v_tcb = eval_text_anchor_v(comp, node, time, expr); + let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, expr) as f32; + let write_on_start = comp.eval_number(node, "Start", time, 0.0, expr) as f32; + let write_on_end = comp.eval_number(node, "End", time, 1.0, expr) as f32; + let char_size_x = comp.eval_number(node, "CharacterSizeX", time, 1.0, expr).max(0.0) as f32; + let char_size_y = comp.eval_number(node, "CharacterSizeY", time, 1.0, expr).max(0.0) as f32; + + let raw_cmds = crate::text_engine::layout_text_shape_commands(&crate::text_engine::TextShapeParams { + text: &text_str, + font_family, + font_style, + size_norm, + tracking, + line_spacing, + h_lcr, + v_tcb, + shear_x, + write_on_start, + write_on_end, + char_size_x, + char_size_y, + }); + if raw_cmds.is_empty() { + return None; + } + let cmds: Vec = raw_cmds + .into_iter() + .map(|c| match c { + zeno::Command::MoveTo(p) => ShapeCmd::MoveTo([p.x, p.y]), + zeno::Command::LineTo(p) => ShapeCmd::LineTo([p.x, p.y]), + zeno::Command::QuadTo(a, p) => ShapeCmd::QuadTo([a.x, a.y], [p.x, p.y]), + zeno::Command::CurveTo(a, b, p) => ShapeCmd::CurveTo([a.x, a.y], [b.x, b.y], [p.x, p.y]), + zeno::Command::Close => ShapeCmd::Close, + }) + .collect(); + + let [tx, ty] = eval_xy_or_point_keys( + comp, + node, + &["Center.X", "Translate.X", "XOffset"], + &["Center.Y", "Translate.Y", "YOffset"], + &["Center", "Translate"], + time, + [0.0, 0.0], + expr, + ); + let [px, py] = eval_xy_or_point( + comp, + node, + &["XPivot", "Pivot.X"], + &["YPivot", "Pivot.Y"], + "Pivot", + time, + [0.0, 0.0], + expr, + ); + let base_scale = eval_first_num(comp, node, &["LayoutSize", "Scale"], time, 1.0, expr); + let sx = comp.eval_number(node, "XSize", time, base_scale, expr) as f32; + let sy = comp.eval_number(node, "YSize", time, base_scale, expr) as f32; + let angle = eval_first_num(comp, node, &["AngleZ", "ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; + let local = if (sx - 1.0).abs() > 1e-6 || (sy - 1.0).abs() > 1e-6 || px.abs() > 1e-6 || py.abs() > 1e-6 { + Affine2D::translate(tx + px, ty + py) + .mul(Affine2D::rotate_deg(angle)) + .mul(Affine2D::scale(sx, sy)) + .mul(Affine2D::translate(-px, -py)) + } else { + Affine2D::translate(tx, ty).mul(Affine2D::rotate_deg(angle)) + }; + let xform = parent_xform.mul(local); + + let r = eval_first_num(comp, node, &["Red1", "Red", "Red1Clone"], time, 1.0, expr) as f32; + let g = eval_first_num(comp, node, &["Green1", "Green", "Green1Clone"], time, 1.0, expr) as f32; + let b = eval_first_num(comp, node, &["Blue1", "Blue", "Blue1Clone"], time, 1.0, expr) as f32; + let a = eval_first_num(comp, node, &["Alpha1", "Alpha", "Alpha1Clone"], time, 1.0, expr) as f32; + let opacity = eval_first_num(comp, node, &["Opacity1", "Opacity"], time, 1.0, expr) as f32; + let mut color = [r * opacity, g * opacity, b * opacity, a * opacity]; + + let elem_shape = comp.eval_number(node, "ElementShape1", time, 0.0, expr).round() as i32; + let mut solid = if node.inputs.contains_key("Solid") { + comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5 + } else { + elem_shape != 1 + }; + let mut border_width = if node.inputs.contains_key("BorderWidth") { + comp.eval_number(node, "BorderWidth", time, 0.02, expr).abs() as f32 + } else { + (comp.eval_number(node, "Thickness1", time, 0.02, expr).abs() as f32) * size_norm.max(1e-4) + }; + let mut join_style = eval_first_num(comp, node, &["JoinStyle1", "JoinStyle"], time, 1.0, expr).round().clamp(0.0, 3.0) as u8; + let mut cap_style = comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8; + let mut miter_limit = eval_first_num(comp, node, &["MiterLimit1", "MiterLimit"], time, 10.0, expr).max(1.0) as f32; + let mut write_pos = comp.eval_number(node, "WritePosition", time, 0.0, expr) as f32; + let mut write_len = comp.eval_number(node, "WriteLength", time, 1.0, expr).clamp(0.0, 1.0) as f32; + let mut line_type = parse_line_type(node, comp, time, expr); + + if let Some(sv) = style_override { + if let Some(c) = sv.color { + color = c; + } + if let Some(s) = sv.solid { + solid = s; + } + if let Some(bw) = sv.border_width { + border_width = bw; + } + if let Some(js) = sv.join_style { + join_style = js; + } + if let Some(cs) = sv.cap_style { + cap_style = cs; + } + if let Some(lt) = sv.line_type { + line_type = lt; + } + } + if let Some(ov) = outline_override { + solid = false; + border_width = ov.thickness; + join_style = ov.join; + cap_style = ov.cap; + miter_limit = ov.miter_limit; + write_pos = ov.write_pos; + write_len = ov.write_len; + } + + Some(ShapeTree::Primitive { + kind: ShapePrimKind::Text { cmds }, + xform, + color, + solid, + border_width, + join_style, + cap_style, + miter_limit, + write_pos, + write_len, + fill_even_odd: false, + line_type, + }) +} + +#[allow(clippy::too_many_arguments)] +pub(super) fn collect_s_change_style( + comp: &Comp, + node: &Node, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option, + style_override: Option, + depth: usize, + prim_budget: &mut usize, +) -> Option { + let src_name = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1"))?; + let keep_mode = node.static_str("StyleMode").unwrap_or("Replace") == "Keep"; + let override_color = if node.inputs.contains_key("OverrideColor") { + comp.eval_number(node, "OverrideColor", time, 1.0, expr) > 0.5 + } else { + !keep_mode + }; + let color = if override_color { + let r = comp.eval_number(node, "Red", time, 1.0, expr) as f32; + let g = comp.eval_number(node, "Green", time, 1.0, expr) as f32; + let b = comp.eval_number(node, "Blue", time, 1.0, expr) as f32; + let a = comp.eval_number(node, "Alpha", time, 1.0, expr) as f32; + let opacity = comp.eval_number(node, "Opacity", time, 1.0, expr) as f32; + Some([r * opacity, g * opacity, b * opacity, a * opacity]) + } else { + None + }; + let check_opt = |flag: &str, key: &str| -> bool { + node.inputs.contains_key(key) + && (!node.inputs.contains_key(flag) + || comp.eval_number(node, flag, time, 1.0, expr) > 0.5) + }; + let solid = check_opt("OverrideSolid", "Solid") + .then(|| comp.eval_number(node, "Solid", time, 1.0, expr) > 0.5); + let border_width = check_opt("OverrideBorderWidth", "BorderWidth") + .then(|| comp.eval_number(node, "BorderWidth", time, 0.01, expr).abs() as f32); + let join_style = check_opt("OverrideJoinStyle", "JoinStyle") + .then(|| comp.eval_number(node, "JoinStyle", time, 1.0, expr).round().clamp(0.0, 3.0) as u8); + let cap_style = check_opt("OverrideCapStyle", "CapStyle") + .then(|| comp.eval_number(node, "CapStyle", time, 1.0, expr).round().clamp(0.0, 2.0) as u8); + let lt = parse_line_type(node, comp, time, expr); + let line_type = (check_opt("OverrideLineType", "LineType") + || check_opt("OverrideLineType", "LineStyle")) + .then_some(lt); + + let local_sv = StyleOverride { color, solid, border_width, join_style, cap_style, line_type }; + let merged_sv = StyleOverride::merge_outer(Some(local_sv), style_override); + collect_shape_tree_by_name( + comp, + src_name, + time, + expr, + parent_xform, + outline_override, + merged_sv, + depth + 1, + prim_budget, + ) +} + +/// Fallback collection for `sBSpline` when `model::is_modifier_type("sBSpline")` omits it from +/// `comp.nodes`; builds a transient `Node` from `comp.raw_root.Tools` and reuses `collect_basic_primitive`. +#[allow(clippy::too_many_arguments)] +pub(super) fn collect_raw_bspline_by_name( + comp: &Comp, + name: &str, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option, + style_override: Option, + prim_budget: &mut usize, +) -> Option { + let tools = comp.raw_root.as_ref()?.get_table("Tools")?; + let tbl = find_tool_table_in_tools(tools, name)?; + if tbl.tag.as_deref() != Some("sBSpline") { + return None; + } + if tbl.get_bool("PassThrough").unwrap_or(false) { + return None; + } + let mut inputs = std::collections::HashMap::new(); + if let Some(in_tbl) = tbl.get_table("Inputs") { + for (k, v) in &in_tbl.entries { + let LuaKey::Str(in_name) = k else { continue }; + let Some(it) = v.as_table() else { continue }; + let source_op = it.get_str("SourceOp").map(str::to_owned); + let source_output = it.get_str("Source").map(str::to_owned); + let expression = it.get_str("Expression").map(str::to_owned); + let value = it.get("Value").and_then(|val| { + if let Some(n) = val.as_f64() { + Some(ParamValue::Number(n)) + } else if let Some(s) = val.as_str() { + Some(ParamValue::Text(s.to_owned())) + } else if let Some(pt) = val.as_table() { + let mut vals = pt.positional_values(); + if let (Some(x), Some(y)) = (vals.next().and_then(|v| v.as_f64()), vals.next().and_then(|v| v.as_f64())) { + Some(ParamValue::Point([x, y])) + } else { + None + } + } else { + None + } + }); + inputs.insert( + in_name.clone(), + InputBinding { value, source_op, source_output, expression }, + ); + } + } + let tmp = Node { + id: NodeId(usize::MAX), + name: name.to_owned(), + kind: "sBSpline".to_owned(), + inputs, + clips: Vec::new(), + raw: tbl.clone(), + bypassed: false, + internal: false, + macro_output: None, + pos: [0.0, 0.0], + }; + collect_basic_primitive( + comp, + &tmp, + time, + expr, + parent_xform, + outline_override, + style_override, + prim_budget, + ) +} diff --git a/crates/engine/src/eval/shapes/geometry.rs b/crates/engine/src/eval/shapes/geometry.rs index 524529a6b086ff76133f52edc480fb0069818adf..982e411a8cb30b6af84a94ef93a97568a928819a 100644 --- a/crates/engine/src/eval/shapes/geometry.rs +++ b/crates/engine/src/eval/shapes/geometry.rs @@ -1,13 +1,11 @@ -//! 2D vector shape command generation, contour flattening, path modifiers -//! (`sExpand`, `sJitter`, `sOffset`), path trimming, and viewport clipping. +//! 2D vector shape command generation, adaptive curve flattening, path trimming, +//! and viewport clipping. -use super::{Affine2D, PathModifier, ShapePrimKind}; - -#[derive(Clone, Debug)] -pub(super) struct Contour { - pub(super) points: Vec<[f32; 2]>, - pub(super) closed: bool, -} +use super::super::warps_masks::bspline::eval_rational_cubic_bspline_2d; +use super::modifiers::{ + Contour, apply_path_modifier_contours, dash_contours, dedup_contour_points, expand_contour, +}; +use super::{Affine2D, PathModifier, ShapeCmd, ShapePrimKind}; #[inline] fn shape_to_px(wpt: [f32; 2], dims: [u32; 2]) -> zeno::Vector { @@ -204,9 +202,175 @@ fn build_primitive_commands_shape(kind: &ShapePrimKind, xform: Affine2D) -> (Vec } (cmds, *closed) } + ShapePrimKind::BSpline { points, closed, tessellation } => { + let min_steps = (12.0 + tessellation.clamp(0.0, 9.0) * 4.0).round() as usize; + let xf_pts: Vec<([f32; 2], f32)> = points + .iter() + .map(|p| (xform.apply([p.x as f32, p.y as f32]), p.w as f32)) + .collect(); + let poly = eval_rational_cubic_bspline_2d(&xf_pts, *closed, |chord| { + ((chord * 128.0).ceil() as usize).clamp(min_steps, 96) + }); + for (i, &pt) in poly.iter().enumerate() { + let v = zeno::Vector::new(pt[0], pt[1]); + if i == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + if *closed && !cmds.is_empty() { + cmds.push(zeno::Command::Close); + } + (cmds, *closed) + } + ShapePrimKind::Text { cmds: text_cmds } => { + cmds.reserve(text_cmds.len()); + for &c in text_cmds { + cmds.push(match c { + ShapeCmd::MoveTo(p) => zeno::Command::MoveTo(to_v(p)), + ShapeCmd::LineTo(p) => zeno::Command::LineTo(to_v(p)), + ShapeCmd::QuadTo(a, p) => zeno::Command::QuadTo(to_v(a), to_v(p)), + ShapeCmd::CurveTo(a, b, p) => zeno::Command::CurveTo(to_v(a), to_v(b), to_v(p)), + ShapeCmd::Close => zeno::Command::Close, + }); + } + (cmds, true) + } } } +/// Flattens `CurveTo` and `QuadTo` segments adaptively in pixel space to sub-0.02px accuracy +/// so smooth curves (like `sEllipse`, `sText`, rounded corners) avoid coarse polygon facets. +fn flatten_quad_adaptive( + p0: [f32; 2], + c: [f32; 2], + p1: [f32; 2], + tol_sq: f32, + depth: u8, + out: &mut Vec<[f32; 2]>, +) { + let mx = 0.5 * (p0[0] + p1[0]); + let my = 0.5 * (p0[1] + p1[1]); + let dx = c[0] - mx; + let dy = c[1] - my; + if depth >= 9 || (dx * dx + dy * dy) <= 16.0 * tol_sq { + out.push(p1); + return; + } + let q0 = [0.5 * (p0[0] + c[0]), 0.5 * (p0[1] + c[1])]; + let q1 = [0.5 * (c[0] + p1[0]), 0.5 * (c[1] + p1[1])]; + let mid = [0.5 * (q0[0] + q1[0]), 0.5 * (q0[1] + q1[1])]; + flatten_quad_adaptive(p0, q0, mid, tol_sq, depth + 1, out); + flatten_quad_adaptive(mid, q1, p1, tol_sq, depth + 1, out); +} + +fn flatten_cubic_adaptive( + p0: [f32; 2], + c1: [f32; 2], + c2: [f32; 2], + p1: [f32; 2], + tol_sq: f32, + depth: u8, + out: &mut Vec<[f32; 2]>, +) { + let dx = p1[0] - p0[0]; + let dy = p1[1] - p0[1]; + let len_sq = dx * dx + dy * dy; + let d1 = (c1[0] - p1[0]) * dy - (c1[1] - p1[1]) * dx; + let d2 = (c2[0] - p1[0]) * dy - (c2[1] - p1[1]) * dx; + let d_max = d1.abs().max(d2.abs()); + let flat_ok = if len_sq > 1e-8 { + (d_max * d_max) <= (16.0 / 9.0) * tol_sq * len_sq + } else { + (c1[0] - p0[0]).hypot(c1[1] - p0[1]).max((c2[0] - p0[0]).hypot(c2[1] - p0[1])) <= 0.1 + }; + if depth >= 9 || (flat_ok && depth >= 2) { + out.push(p1); + return; + } + let p01 = [0.5 * (p0[0] + c1[0]), 0.5 * (p0[1] + c1[1])]; + let p12 = [0.5 * (c1[0] + c2[0]), 0.5 * (c1[1] + c2[1])]; + let p23 = [0.5 * (c2[0] + p1[0]), 0.5 * (c2[1] + p1[1])]; + let p012 = [0.5 * (p01[0] + p12[0]), 0.5 * (p01[1] + p12[1])]; + let p123 = [0.5 * (p12[0] + p23[0]), 0.5 * (p12[1] + p23[1])]; + let mid = [0.5 * (p012[0] + p123[0]), 0.5 * (p012[1] + p123[1])]; + flatten_cubic_adaptive(p0, p01, p012, mid, tol_sq, depth + 1, out); + flatten_cubic_adaptive(mid, p123, p23, p1, tol_sq, depth + 1, out); +} + +/// Splits `cmds` into per-subpath `Contour`s, adaptively flattening curves in `tol_px` units. +pub(super) fn flatten_commands_to_contours( + cmds: &[zeno::Command], + default_closed: bool, + tol_px: f32, +) -> Vec { + use zeno::Command::{Close, CurveTo, LineTo, MoveTo, QuadTo}; + let tol_sq = tol_px * tol_px; + let mut contours: Vec = Vec::new(); + let mut cur: Vec<[f32; 2]> = Vec::new(); + let mut cur_closed = false; + + let flush = |cur: &mut Vec<[f32; 2]>, closed: bool, out: &mut Vec| { + let pts = dedup_contour_points(std::mem::take(cur), closed); + if pts.len() >= 2 && (!closed || pts.len() >= 3) { + out.push(Contour { points: pts, closed }); + } + }; + + for c in cmds { + match *c { + MoveTo(p) => { + if !cur.is_empty() { + flush(&mut cur, cur_closed || default_closed, &mut contours); + } + cur_closed = false; + cur.push([p.x, p.y]); + } + LineTo(p) => { + cur.push([p.x, p.y]); + } + QuadTo(a, p) => { + let p0 = cur.last().copied().unwrap_or([a.x, a.y]); + flatten_quad_adaptive(p0, [a.x, a.y], [p.x, p.y], tol_sq, 0, &mut cur); + } + CurveTo(a, b, p) => { + let p0 = cur.last().copied().unwrap_or([a.x, a.y]); + flatten_cubic_adaptive(p0, [a.x, a.y], [b.x, b.y], [p.x, p.y], tol_sq, 0, &mut cur); + } + Close => { + cur_closed = true; + flush(&mut cur, true, &mut contours); + } + } + } + if !cur.is_empty() { + flush(&mut cur, cur_closed || default_closed, &mut contours); + } + contours +} + +pub(super) fn contours_to_commands(contours: &[Contour]) -> Vec { + let mut cmds = Vec::new(); + for c in contours { + if c.points.len() < 2 || (c.closed && c.points.len() < 3) { + continue; + } + for (i, &pt) in c.points.iter().enumerate() { + let v = zeno::Vector::new(pt[0], pt[1]); + if i == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + if c.closed { + cmds.push(zeno::Command::Close); + } + } + cmds +} + /// Builds pixel-space `zeno::Command`s for a primitive after applying any inner-to-outer `PathModifier`s. pub(super) fn build_primitive_commands_px( kind: &ShapePrimKind, @@ -221,7 +385,7 @@ pub(super) fn build_primitive_commands_px( } if mods.is_empty() { - let px_cmds = shape_cmds + let px_cmds: Vec = shape_cmds .into_iter() .map(|c| match c { zeno::Command::MoveTo(p) => zeno::Command::MoveTo(shape_to_px([p.x, p.y], dims)), @@ -238,534 +402,93 @@ pub(super) fn build_primitive_commands_px( zeno::Command::Close => zeno::Command::Close, }) .collect(); + let has_curves = px_cmds + .iter() + .any(|c| matches!(c, zeno::Command::QuadTo(..) | zeno::Command::CurveTo(..))); + if has_curves { + let contours = flatten_commands_to_contours(&px_cmds, closed, 0.015); + return (contours_to_commands(&contours), closed); + } return (px_cmds, closed); } - let scale_hint = dims[0].max(dims[1]) as f32; - let pts = flatten_commands_to_poly_scaled(&shape_cmds, scale_hint); - let mut contour = Contour { points: dedup_contour_points(pts, closed), closed }; + let tol_shape = 0.02 / (dims[0].max(dims[1]).max(1) as f32); + let mut contours = flatten_commands_to_contours(&shape_cmds, closed, tol_shape); for (mod_idx, &(op, post_xform)) in mods.iter().enumerate() { - if contour.points.len() < 2 { - return (Vec::new(), contour.closed); + if contours.is_empty() { + return (Vec::new(), closed); } - contour = apply_path_modifier(contour, op, shape_idx, mod_idx as u32); - for p in &mut contour.points { - *p = post_xform.apply(*p); - } - } - - if contour.points.len() < 2 || (contour.closed && contour.points.len() < 3) { - return (Vec::new(), contour.closed); - } - - let mut px_cmds = Vec::with_capacity(contour.points.len() + 1); - for (i, &pt) in contour.points.iter().enumerate() { - let v = shape_to_px(pt, dims); - if i == 0 { - px_cmds.push(zeno::Command::MoveTo(v)); - } else { - px_cmds.push(zeno::Command::LineTo(v)); - } - } - if contour.closed { - px_cmds.push(zeno::Command::Close); - } - (px_cmds, contour.closed) -} - -fn dedup_contour_points(pts: Vec<[f32; 2]>, closed: bool) -> Vec<[f32; 2]> { - let mut out: Vec<[f32; 2]> = Vec::with_capacity(pts.len()); - for p in pts { - if !p[0].is_finite() || !p[1].is_finite() { - continue; - } - if let Some(&prev) = out.last() { - if (p[0] - prev[0]).hypot(p[1] - prev[1]) <= 1e-6 { - continue; - } - } - out.push(p); - } - if closed && out.len() >= 2 { - if let (Some(&first), Some(&last)) = (out.first(), out.last()) { - if (last[0] - first[0]).hypot(last[1] - first[1]) <= 1e-6 { - out.pop(); - } - } - } - out -} - -fn signed_area(pts: &[[f32; 2]]) -> f32 { - let n = pts.len(); - if n < 3 { - return 0.0; - } - let mut sum = 0.0_f64; - for i in 0..n { - let a = pts[i]; - let b = pts[(i + 1) % n]; - sum += (a[0] as f64) * (b[1] as f64) - (b[0] as f64) * (a[1] as f64); - } - (0.5 * sum) as f32 -} - -fn apply_path_modifier(contour: Contour, op: PathModifier, shape_idx: u32, mod_idx: u32) -> Contour { - match op { - PathModifier::Expand { amount, join_style, miter_limit } => { - expand_contour(contour, amount, join_style, miter_limit) - } - PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { - jitter_contour(contour, x_amount, y_amount, seed, smoothness, per_shape, shape_idx, mod_idx) - } - PathModifier::Offset { - offset_x, - offset_y, - contour_offset, - position, - join_style, - miter_limit, - } => { - let mut c = if contour_offset.abs() > 1e-6 { - expand_contour(contour, contour_offset, join_style, miter_limit) - } else { - contour - }; - if position.abs() > 1e-6 { - c = shift_contour_position(c, position); + contours = apply_path_modifier_contours(contours, op, shape_idx, mod_idx as u32); + for c in &mut contours { + for p in &mut c.points { + *p = post_xform.apply(*p); } - if offset_x.abs() > 1e-6 || offset_y.abs() > 1e-6 { - for p in &mut c.points { - p[0] += offset_x; - p[1] += offset_y; - } - } - c - } - } -} - -/// Offsets a contour outward (`amount > 0`) or inward (`amount < 0`) using miter/bevel/round joins. -fn expand_contour(contour: Contour, amount: f32, join_style: u8, miter_limit: f32) -> Contour { - if amount.abs() <= 1e-6 { - return contour; - } - let pts = dedup_contour_points(contour.points, contour.closed); - if !contour.closed { - if pts.len() < 2 { - return Contour { points: Vec::new(), closed: false }; - } - let n = pts.len(); - let mut out = Vec::with_capacity(n); - for i in 0..n { - let n0 = if i > 0 { - let dx = pts[i][0] - pts[i - 1][0]; - let dy = pts[i][1] - pts[i - 1][1]; - let l = dx.hypot(dy).max(1e-6); - [dy / l, -dx / l] - } else { - [0.0, 0.0] - }; - let n1 = if i + 1 < n { - let dx = pts[i + 1][0] - pts[i][0]; - let dy = pts[i + 1][1] - pts[i][1]; - let l = dx.hypot(dy).max(1e-6); - [dy / l, -dx / l] - } else { - [0.0, 0.0] - }; - let avg = if i == 0 { - n1 - } else if i + 1 == n { - n0 - } else { - let bx = n0[0] + n1[0]; - let by = n0[1] + n1[1]; - let denom = (1.0 + n0[0] * n1[0] + n0[1] * n1[1]).max(1e-4); - let scale = (1.0 / denom).min(miter_limit * 0.5); - [bx * scale, by * scale] - }; - out.push([pts[i][0] + avg[0] * amount, pts[i][1] + avg[1] * amount]); } - return Contour { points: out, closed: false }; - } - - let n = pts.len(); - if n < 3 { - return Contour { points: Vec::new(), closed: true }; - } - let orig_area = signed_area(&pts); - if orig_area.abs() <= 1e-10 { - return Contour { points: Vec::new(), closed: true }; - } - // For CCW (orig_area > 0) in Y-up shape space, outward normal of edge (dx, dy) is (dy, -dx)/len. - let orient = if orig_area > 0.0 { 1.0_f32 } else { -1.0_f32 }; - - // Compute per-edge outward unit normals. - let mut normals = Vec::with_capacity(n); - for i in 0..n { - let a = pts[i]; - let b = pts[(i + 1) % n]; - let dx = b[0] - a[0]; - let dy = b[1] - a[1]; - let len = dx.hypot(dy).max(1e-6); - normals.push([orient * dy / len, -orient * dx / len]); } - let mut out = Vec::with_capacity(n * 2); - for i in 0..n { - let n0 = normals[(i + n - 1) % n]; - let n1 = normals[i]; - let p = pts[i]; - - let dot = (n0[0] * n1[0] + n0[1] * n1[1]).clamp(-1.0, 1.0); - let cross = n0[0] * n1[1] - n0[1] * n1[0]; - // When dot ~= 1, edges are collinear. - if dot > 1.0 - 1e-5 { - out.push([p[0] + n0[0] * amount, p[1] + n0[1] * amount]); + let eff_closed = contours.first().is_some_and(|c| c.closed); + let mut px_cmds = Vec::new(); + for c in &contours { + if c.points.len() < 2 || (c.closed && c.points.len() < 3) { continue; } - - // Convex corner for CCW has cross > 0; outer join happens when expanding convex or shrinking reflex. - let is_outer = (cross * orient * amount) > 0.0; - let q0 = [p[0] + n0[0] * amount, p[1] + n0[1] * amount]; - let q1 = [p[0] + n1[0] * amount, p[1] + n1[1] * amount]; - let denom = 1.0 + dot; - - if is_outer { - match join_style { - 0 => { - // Bevel - out.push(q0); - out.push(q1); - } - 1 => { - // Round arc from n0 to n1 - let a0 = (n0[1] * amount).atan2(n0[0] * amount); - let a1 = (n1[1] * amount).atan2(n1[0] * amount); - let mut delta = a1 - a0; - while delta > std::f32::consts::PI { - delta -= std::f32::consts::TAU; - } - while delta < -std::f32::consts::PI { - delta += std::f32::consts::TAU; - } - let steps = ((delta.abs() / 0.25).ceil() as usize).clamp(1, 16); - let rad = amount.abs(); - for s in 0..=steps { - let a = a0 + delta * (s as f32 / steps as f32); - out.push([p[0] + rad * a.cos(), p[1] + rad * a.sin()]); - } - } - _ => { - // Miter (with miter_limit fallback to bevel) - if denom > 1e-4 { - let miter_ratio = (2.0 / denom).sqrt(); - if miter_ratio <= miter_limit { - let inv = amount / denom; - out.push([p[0] + (n0[0] + n1[0]) * inv, p[1] + (n0[1] + n1[1]) * inv]); - } else { - out.push(q0); - out.push(q1); - } - } else { - out.push(q0); - out.push(q1); - } - } - } - } else { - // Inner corner (or convex corner when deflating): exact miter intersection clamped to miter_limit. - if denom > 1e-4 { - let miter_ratio = (2.0 / denom).sqrt(); - let clamped_inv = if miter_ratio <= miter_limit { - amount / denom - } else { - amount * (miter_limit / (2.0 * denom).sqrt().max(1e-4)) - }; - out.push([ - p[0] + (n0[0] + n1[0]) * clamped_inv, - p[1] + (n0[1] + n1[1]) * clamped_inv, - ]); + for (i, &pt) in c.points.iter().enumerate() { + let v = shape_to_px(pt, dims); + if i == 0 { + px_cmds.push(zeno::Command::MoveTo(v)); } else { - out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); + px_cmds.push(zeno::Command::LineTo(v)); } } - } - - // If deflating (`amount < 0`), check for collapse / inverted winding. - if amount < 0.0 { - let mut min_x = f32::INFINITY; - let mut max_x = f32::NEG_INFINITY; - let mut min_y = f32::INFINITY; - let mut max_y = f32::NEG_INFINITY; - for &p in &pts { - min_x = min_x.min(p[0]); - max_x = max_x.max(p[0]); - min_y = min_y.min(p[1]); - max_y = max_y.max(p[1]); + if c.closed { + px_cmds.push(zeno::Command::Close); } - let half_min = 0.5 * (max_x - min_x).min(max_y - min_y); - let new_area = signed_area(&out); - if (-amount) >= half_min - 1e-5 || new_area * orig_area <= 1e-10 { - return Contour { points: Vec::new(), closed: true }; - } - } - - Contour { points: dedup_contour_points(out, true), closed: true } -} - -/// Deterministic signed float in `[-1.0, 1.0]` from `(seed, shape_idx, mod_idx, vertex_idx, axis)`. -#[inline] -fn jitter_hash(seed: i64, shape_idx: u32, mod_idx: u32, vertex_idx: u32, axis: u32) -> f32 { - let mut h = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) - ^ (shape_idx as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) - ^ (mod_idx as u64).wrapping_mul(0x94D0_49BB_1331_11EB) - ^ (vertex_idx as u64).wrapping_mul(0xD1B5_4A32_D192_ED03) - ^ (axis as u64).wrapping_mul(0x517C_C1B7_2722_0A95); - h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); - h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); - h ^= h >> 31; - let u = ((h >> 40) as f32) * (1.0 / ((1u32 << 24) as f32)); - u * 2.0 - 1.0 -} - -/// Subdivides sparse contours so long straight edges (like rectangles) receive organic vertex jitter. -fn subdivide_for_jitter(pts: &[[f32; 2]], closed: bool) -> Vec<[f32; 2]> { - let n = pts.len(); - if n < 2 || n >= 48 { - return pts.to_vec(); - } - let seg_count = if closed { n } else { n - 1 }; - let mut total_len = 0.0_f32; - for i in 0..seg_count { - let a = pts[i]; - let b = pts[(i + 1) % n]; - total_len += (b[0] - a[0]).hypot(b[1] - a[1]); - } - if total_len <= 1e-6 { - return pts.to_vec(); - } - let target_step = (total_len / 48.0).max(1e-4); - let mut out = Vec::with_capacity(64); - for i in 0..seg_count { - let a = pts[i]; - let b = pts[(i + 1) % n]; - let len = (b[0] - a[0]).hypot(b[1] - a[1]); - let subs = ((len / target_step).ceil() as usize).clamp(1, 32); - for s in 0..subs { - let t = s as f32 / subs as f32; - out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); - } - } - if !closed { - out.push(pts[n - 1]); } - out + (px_cmds, eff_closed) } -/// Applies deterministic per-vertex or per-shape jitter with optional `smoothness` filtering. -#[allow(clippy::too_many_arguments)] -fn jitter_contour( - contour: Contour, - x_amount: f32, - y_amount: f32, - seed: i64, - smoothness: f32, - per_shape: bool, - shape_idx: u32, - mod_idx: u32, -) -> Contour { - if per_shape { - let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; - let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; - let points = contour - .points - .into_iter() - .map(|p| [p[0] + dx, p[1] + dy]) - .collect(); - return Contour { points, closed: contour.closed }; - } - - let pts = subdivide_for_jitter(&contour.points, contour.closed); - let n = pts.len(); - if n < 2 { - return Contour { points: pts, closed: contour.closed }; - } - - let mut offsets: Vec<[f32; 2]> = (0..n) - .map(|i| { - [ - jitter_hash(seed, shape_idx, mod_idx, i as u32, 0) * x_amount, - jitter_hash(seed, shape_idx, mod_idx, i as u32, 1) * y_amount, - ] - }) - .collect(); - - if smoothness > 1e-4 { - let sigma = (smoothness * 2.5).min((n as f32) * 0.5); - let radius = ((sigma * 2.5).ceil() as usize).clamp(1, n / 2); - let inv_two_sig_sq = 0.5 / (sigma * sigma).max(1e-4); - let mut smoothed = vec![[0.0_f32; 2]; n]; - for i in 0..n { - let mut sx = 0.0_f32; - let mut sy = 0.0_f32; - let mut wsum = 0.0_f32; - for d in -(radius as isize)..=(radius as isize) { - let w = (-((d * d) as f32) * inv_two_sig_sq).exp(); - let j = if contour.closed { - (i as isize + d).rem_euclid(n as isize) as usize - } else { - (i as isize + d).clamp(0, (n - 1) as isize) as usize - }; - sx += offsets[j][0] * w; - sy += offsets[j][1] * w; - wsum += w; - } - if wsum > 1e-6 { - smoothed[i] = [sx / wsum, sy / wsum]; - } - } - // Renormalize variance partially so smooth jitter stays visibly displaced rather than vanishing to 0. - let boost = (1.0 + sigma.sqrt()).min(3.0); - for s in &mut smoothed { - s[0] = (s[0] * boost).clamp(-x_amount.abs(), x_amount.abs()); - s[1] = (s[1] * boost).clamp(-y_amount.abs(), y_amount.abs()); - } - offsets = smoothed; - } - - let points = pts - .into_iter() - .zip(offsets) - .map(|(p, o)| [p[0] + o[0], p[1] + o[1]]) - .collect(); - Contour { points, closed: contour.closed } +/// Builds a closed-ring fill path (`outer` + reversed `inner`) for thick single-contour outlines, +/// avoiding `zeno::Stroke`'s inner-corner self-overlap artifact. +pub(super) fn closed_outline_fill_commands( + cmds: &[zeno::Command], + stroke_px: f32, + join_style: u8, + miter_limit: f32, +) -> Option> { + let contours = flatten_commands_to_contours(cmds, true, 0.02); + if contours.len() != 1 || !contours[0].closed || contours[0].points.len() < 3 { + return None; + } + let half = stroke_px * 0.5; + let outer = expand_contour(contours[0].clone(), half, join_style, miter_limit, None); + if outer.points.len() < 3 { + return None; + } + let mut inner = expand_contour(contours[0].clone(), -half, join_style, miter_limit, None); + let mut out = contours_to_commands(&[outer]); + if inner.points.len() >= 3 { + inner.points.reverse(); + out.extend(contours_to_commands(&[inner])); + } + Some(out) } -/// Shifts a contour's parametric origin along its arc length by `position` (in `[0, 1]` fractions). -fn shift_contour_position(contour: Contour, position: f32) -> Contour { - let pts = dedup_contour_points(contour.points, contour.closed); - let n = pts.len(); - if n < 2 { - return Contour { points: pts, closed: contour.closed }; - } - - if !contour.closed { - // For an open path, translate along its unit start-to-end chord by `position * arc_len`. - let mut total = 0.0_f32; - for i in 0..n - 1 { - total += (pts[i + 1][0] - pts[i][0]).hypot(pts[i + 1][1] - pts[i][1]); - } - let cdx = pts[n - 1][0] - pts[0][0]; - let cdy = pts[n - 1][1] - pts[0][1]; - let clen = cdx.hypot(cdy); - if clen <= 1e-6 || total <= 1e-6 { - return Contour { points: pts, closed: false }; - } - let shift = position * total; - let tx = (cdx / clen) * shift; - let ty = (cdy / clen) * shift; - return Contour { - points: pts.into_iter().map(|p| [p[0] + tx, p[1] + ty]).collect(), - closed: false, - }; - } - - let frac = position.rem_euclid(1.0); - if frac <= 1e-6 || frac >= 1.0 - 1e-6 { - return Contour { points: pts, closed: true }; - } - - let mut seg_lens = Vec::with_capacity(n); - let mut total = 0.0_f32; - for i in 0..n { - let a = pts[i]; - let b = pts[(i + 1) % n]; - let l = (b[0] - a[0]).hypot(b[1] - a[1]); - seg_lens.push(l); - total += l; - } - if total <= 1e-6 { - return Contour { points: pts, closed: true }; - } - - let target = frac * total; - let mut acc = 0.0_f32; - let mut split_idx = 0usize; - let mut split_t = 0.0_f32; - for (i, &l) in seg_lens.iter().enumerate() { - if acc + l >= target || i + 1 == n { - split_idx = i; - split_t = if l > 1e-6 { ((target - acc) / l).clamp(0.0, 1.0) } else { 0.0 }; - break; - } - acc += l; - } - - let a = pts[split_idx]; - let b = pts[(split_idx + 1) % n]; - let start_pt = [a[0] + (b[0] - a[0]) * split_t, a[1] + (b[1] - a[1]) * split_t]; - let mut out = Vec::with_capacity(n + 1); - out.push(start_pt); - for k in 1..=n { - let idx = (split_idx + k) % n; - let p = pts[idx]; - if (p[0] - out.last().unwrap()[0]).hypot(p[1] - out.last().unwrap()[1]) > 1e-6 { - out.push(p); - } - } - Contour { points: dedup_contour_points(out, true), closed: true } -} - -pub(super) fn flatten_commands_to_poly(cmds: &[zeno::Command]) -> Vec<[f32; 2]> { - flatten_commands_to_poly_scaled(cmds, 1.0) -} - -fn flatten_commands_to_poly_scaled(cmds: &[zeno::Command], scale: f32) -> Vec<[f32; 2]> { - use zeno::Command::{CurveTo, LineTo, MoveTo, QuadTo}; - let mut poly: Vec<[f32; 2]> = Vec::new(); - for c in cmds { - match c { - MoveTo(p) | LineTo(p) => poly.push([p.x, p.y]), - QuadTo(a, p) => { - let p0 = poly.last().copied().unwrap_or([a.x, a.y]); - let len = ((a.x - p0[0]).hypot(a.y - p0[1]) + (p.x - a.x).hypot(p.y - a.y)) * scale; - let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(8, 1024); - for i in 1..=n { - let t = i as f32 / n as f32; - let u = 1.0 - t; - poly.push([ - u * u * p0[0] + 2.0 * u * t * a.x + t * t * p.x, - u * u * p0[1] + 2.0 * u * t * a.y + t * t * p.y, - ]); - } - } - CurveTo(a, b, p) => { - let p0 = poly.last().copied().unwrap_or([a.x, a.y]); - let len = ((a.x - p0[0]).hypot(a.y - p0[1]) - + (b.x - a.x).hypot(b.y - a.y) - + (p.x - b.x).hypot(p.y - b.y)) - * scale; - let n = ((len.sqrt() * 1.5).ceil() as usize).clamp(16, 2048); - for i in 1..=n { - let t = i as f32 / n as f32; - let u = 1.0 - t; - let (c0, c1, c2, c3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t); - poly.push([ - c0 * p0[0] + c1 * a.x + c2 * b.x + c3 * p.x, - c0 * p0[1] + c1 * a.y + c2 * b.y + c3 * p.y, - ]); - } - } - _ => {} - } - } - poly +/// Applies `line_type` dashing (`1..=4`) to pixel-space `cmds`. +pub(super) fn dash_path_commands( + cmds: Vec, + closed: bool, + line_type: u8, + stroke_px: f32, +) -> Vec { + if line_type == 0 { + return cmds; + } + let contours = flatten_commands_to_contours(&cmds, closed, 0.05); + dash_contours(&contours, line_type, stroke_px) } -/// Trims a command loop (closed or open) to arc-length fraction `[write_pos, write_pos + write_len]`. +/// Trims each contour in `cmds` to arc-length fraction `[write_pos, write_pos + write_len]`. pub(super) fn trim_path_commands( cmds: Vec, closed: bool, @@ -778,7 +501,20 @@ pub(super) fn trim_path_commands( if write_len >= 1.0 - 1e-5 && (!closed || write_pos.rem_euclid(1.0) <= 1e-5) { return cmds; } - let poly = flatten_commands_to_poly(&cmds); + let contours = flatten_commands_to_contours(&cmds, closed, 0.02); + let mut out = Vec::new(); + for c in contours { + out.extend(trim_single_contour(&c.points, c.closed, write_pos, write_len)); + } + out +} + +fn trim_single_contour( + poly: &[[f32; 2]], + closed: bool, + write_pos: f32, + write_len: f32, +) -> Vec { let n = poly.len(); if n < 2 { return Vec::new(); @@ -839,7 +575,7 @@ pub(super) fn trim_path_commands( out } -/// Flattens `cmds` and clips a closed polygon to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. +/// Flattens `cmds` and clips closed polygons to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. pub(super) fn clip_to_viewport( cmds: Vec, closed: bool, @@ -859,34 +595,37 @@ pub(super) fn clip_to_viewport( if !huge || !closed { return cmds; } - let mut poly = flatten_commands_to_poly(&cmds); + let contours = flatten_commands_to_contours(&cmds, closed, 0.05); let edges: [(usize, f32, f32); 4] = [ (0, 1.0, -margin), (0, -1.0, w + margin), (1, 1.0, -margin), (1, -1.0, h + margin), ]; - for (axis, sign, bound) in edges { - let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0; - let input = std::mem::take(&mut poly); - for (i, &cur) in input.iter().enumerate() { - let prev = input[(i + input.len() - 1) % input.len()]; - if inside(cur) != inside(prev) { - let t = (bound - prev[axis]) / (cur[axis] - prev[axis]); - poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]); - } - if inside(cur) { - poly.push(cur); + let mut out = Vec::new(); + for contour in contours { + let mut poly = contour.points; + for (axis, sign, bound) in edges { + let inside = |p: [f32; 2]| sign * (p[axis] - bound) >= 0.0; + let input = std::mem::take(&mut poly); + for (i, &cur) in input.iter().enumerate() { + let prev = input[(i + input.len() - 1) % input.len()]; + if inside(cur) != inside(prev) { + let t = (bound - prev[axis]) / (cur[axis] - prev[axis]); + poly.push([prev[0] + t * (cur[0] - prev[0]), prev[1] + t * (cur[1] - prev[1])]); + } + if inside(cur) { + poly.push(cur); + } } } + for (i, p) in poly.iter().enumerate() { + let v = zeno::Vector::new(p[0], p[1]); + out.push(if i == 0 { MoveTo(v) } else { LineTo(v) }); + } + if !poly.is_empty() { + out.push(Close); + } } - let mut out = Vec::with_capacity(poly.len() + 1); - for (i, p) in poly.iter().enumerate() { - let v = zeno::Vector::new(p[0], p[1]); - out.push(if i == 0 { MoveTo(v) } else { LineTo(v) }); - } - if !out.is_empty() { - out.push(Close); - } out } diff --git a/crates/engine/src/eval/shapes/modifiers.rs b/crates/engine/src/eval/shapes/modifiers.rs new file mode 100644 index 0000000000000000000000000000000000000000..1ebc133802903e4ab9fcf36d082eb1cd04b817cd --- /dev/null +++ b/crates/engine/src/eval/shapes/modifiers.rs @@ -0,0 +1,581 @@ +//! Multi-contour path modifiers (`sExpand`, `sJitter`, `sOffset`, `LineType` dashing) +//! and shared contour offset/orientation utilities. + +use super::PathModifier; + +#[derive(Clone, Debug)] +pub(super) struct Contour { + pub(super) points: Vec<[f32; 2]>, + pub(super) closed: bool, +} + +pub(super) fn dedup_contour_points(pts: Vec<[f32; 2]>, closed: bool) -> Vec<[f32; 2]> { + let mut out: Vec<[f32; 2]> = Vec::with_capacity(pts.len()); + for p in pts { + if !p[0].is_finite() || !p[1].is_finite() { + continue; + } + if let Some(&prev) = out.last() { + if (p[0] - prev[0]).hypot(p[1] - prev[1]) <= 1e-6 { + continue; + } + } + out.push(p); + } + if closed && out.len() >= 2 { + if let (Some(&first), Some(&last)) = (out.first(), out.last()) { + if (last[0] - first[0]).hypot(last[1] - first[1]) <= 1e-6 { + out.pop(); + } + } + } + out +} + +pub(super) fn signed_area(pts: &[[f32; 2]]) -> f32 { + let n = pts.len(); + if n < 3 { + return 0.0; + } + let mut sum = 0.0_f64; + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + sum += (a[0] as f64) * (b[1] as f64) - (b[0] as f64) * (a[1] as f64); + } + (0.5 * sum) as f32 +} + +pub(super) fn apply_path_modifier_contours( + contours: Vec, + op: PathModifier, + shape_idx: u32, + mod_idx: u32, +) -> Vec { + match op { + PathModifier::Expand { amount, join_style, miter_limit } => { + expand_contours(contours, amount, join_style, miter_limit) + } + PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { + if per_shape { + let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; + let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; + return contours + .into_iter() + .map(|c| Contour { + points: c.points.into_iter().map(|p| [p[0] + dx, p[1] + dy]).collect(), + closed: c.closed, + }) + .collect(); + } + contours + .into_iter() + .enumerate() + .map(|(ci, c)| { + jitter_contour( + c, + x_amount, + y_amount, + seed, + smoothness, + false, + shape_idx.wrapping_mul(131).wrapping_add(ci as u32), + mod_idx, + ) + }) + .collect() + } + PathModifier::Offset { + offset_x, + offset_y, + contour_offset, + position, + join_style, + miter_limit, + } => { + let mut cs = if contour_offset.abs() > 1e-6 { + expand_contours(contours, contour_offset, join_style, miter_limit) + } else { + contours + }; + if position.abs() > 1e-6 { + cs = cs.into_iter().map(|c| shift_contour_position(c, position)).collect(); + } + if offset_x.abs() > 1e-6 || offset_y.abs() > 1e-6 { + for c in &mut cs { + for p in &mut c.points { + p[0] += offset_x; + p[1] += offset_y; + } + } + } + cs + } + } +} + +fn expand_contours( + contours: Vec, + amount: f32, + join_style: u8, + miter_limit: f32, +) -> Vec { + if amount.abs() <= 1e-6 { + return contours; + } + // Determine dominant orientation from the largest closed contour so outer boundaries + // and opposite-winding holes offset consistently (e.g., `sText` glyphs). + let mut best_abs = 0.0_f32; + let mut dom_sign = 0.0_f32; + for c in &contours { + if c.closed && c.points.len() >= 3 { + let a = signed_area(&c.points); + if a.abs() > best_abs { + best_abs = a.abs(); + dom_sign = if a > 0.0 { 1.0 } else { -1.0 }; + } + } + } + let dom = (best_abs > 1e-10).then_some(dom_sign); + contours + .into_iter() + .filter_map(|c| { + let out = expand_contour(c, amount, join_style, miter_limit, dom); + if out.points.len() >= 2 && (!out.closed || out.points.len() >= 3) { + Some(out) + } else { + None + } + }) + .collect() +} + +/// Offsets a contour outward (`amount > 0`) or inward (`amount < 0`) using miter/bevel/round joins. +pub(super) fn expand_contour( + contour: Contour, + amount: f32, + join_style: u8, + miter_limit: f32, + orient_override: Option, +) -> Contour { + if amount.abs() <= 1e-6 { + return contour; + } + let pts = dedup_contour_points(contour.points, contour.closed); + if !contour.closed { + if pts.len() < 2 { + return Contour { points: Vec::new(), closed: false }; + } + let n = pts.len(); + let mut out = Vec::with_capacity(n); + for i in 0..n { + let n0 = if i > 0 { + let dx = pts[i][0] - pts[i - 1][0]; + let dy = pts[i][1] - pts[i - 1][1]; + let l = dx.hypot(dy).max(1e-6); + [dy / l, -dx / l] + } else { + [0.0, 0.0] + }; + let n1 = if i + 1 < n { + let dx = pts[i + 1][0] - pts[i][0]; + let dy = pts[i + 1][1] - pts[i][1]; + let l = dx.hypot(dy).max(1e-6); + [dy / l, -dx / l] + } else { + [0.0, 0.0] + }; + let avg = if i == 0 { + n1 + } else if i + 1 == n { + n0 + } else { + let bx = n0[0] + n1[0]; + let by = n0[1] + n1[1]; + let denom = (1.0 + n0[0] * n1[0] + n0[1] * n1[1]).max(1e-4); + let scale = (1.0 / denom).min(miter_limit * 0.5); + [bx * scale, by * scale] + }; + out.push([pts[i][0] + avg[0] * amount, pts[i][1] + avg[1] * amount]); + } + return Contour { points: out, closed: false }; + } + + let n = pts.len(); + if n < 3 { + return Contour { points: Vec::new(), closed: true }; + } + let orig_area = signed_area(&pts); + if orig_area.abs() <= 1e-10 { + return Contour { points: Vec::new(), closed: true }; + } + // For CCW (orig_area > 0) in Y-up shape space, outward normal of edge (dx, dy) is (dy, -dx)/len. + let self_orient = if orig_area > 0.0 { 1.0_f32 } else { -1.0_f32 }; + let orient = orient_override.unwrap_or(self_orient); + let eff_amount = amount * (self_orient * orient); + + // Compute per-edge outward unit normals relative to the contour's own winding, + // and let `eff_amount` flip inward for opposite-winding holes. + let mut normals = Vec::with_capacity(n); + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + let dx = b[0] - a[0]; + let dy = b[1] - a[1]; + let len = dx.hypot(dy).max(1e-6); + normals.push([self_orient * dy / len, -self_orient * dx / len]); + } + + let mut out = Vec::with_capacity(n * 2); + for i in 0..n { + let n0 = normals[(i + n - 1) % n]; + let n1 = normals[i]; + let p = pts[i]; + + let dot = (n0[0] * n1[0] + n0[1] * n1[1]).clamp(-1.0, 1.0); + let cross = n0[0] * n1[1] - n0[1] * n1[0]; + if dot > 1.0 - 1e-5 { + out.push([p[0] + n0[0] * eff_amount, p[1] + n0[1] * eff_amount]); + continue; + } + + let is_outer = (cross * self_orient * eff_amount) > 0.0; + let q0 = [p[0] + n0[0] * eff_amount, p[1] + n0[1] * eff_amount]; + let q1 = [p[0] + n1[0] * eff_amount, p[1] + n1[1] * eff_amount]; + let denom = 1.0 + dot; + + if is_outer { + match join_style { + 0 => { + out.push(q0); + out.push(q1); + } + 1 => { + let a0 = (n0[1] * eff_amount).atan2(n0[0] * eff_amount); + let a1 = (n1[1] * eff_amount).atan2(n1[0] * eff_amount); + let mut delta = a1 - a0; + while delta > std::f32::consts::PI { + delta -= std::f32::consts::TAU; + } + while delta < -std::f32::consts::PI { + delta += std::f32::consts::TAU; + } + let steps = ((delta.abs() / 0.25).ceil() as usize).clamp(1, 16); + let rad = eff_amount.abs(); + for s in 0..=steps { + let a = a0 + delta * (s as f32 / steps as f32); + out.push([p[0] + rad * a.cos(), p[1] + rad * a.sin()]); + } + } + _ => { + if denom > 1e-4 { + let miter_ratio = (2.0 / denom).sqrt(); + if miter_ratio <= miter_limit { + let inv = eff_amount / denom; + out.push([p[0] + (n0[0] + n1[0]) * inv, p[1] + (n0[1] + n1[1]) * inv]); + } else { + out.push(q0); + out.push(q1); + } + } else { + out.push(q0); + out.push(q1); + } + } + } + } else if denom > 1e-4 { + let miter_ratio = (2.0 / denom).sqrt(); + let clamped_inv = if miter_ratio <= miter_limit { + eff_amount / denom + } else { + eff_amount * (miter_limit / (2.0 * denom).sqrt().max(1e-4)) + }; + out.push([ + p[0] + (n0[0] + n1[0]) * clamped_inv, + p[1] + (n0[1] + n1[1]) * clamped_inv, + ]); + } else { + out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); + } + } + + if eff_amount < 0.0 { + let mut min_x = f32::INFINITY; + let mut max_x = f32::NEG_INFINITY; + let mut min_y = f32::INFINITY; + let mut max_y = f32::NEG_INFINITY; + for &p in &pts { + min_x = min_x.min(p[0]); + max_x = max_x.max(p[0]); + min_y = min_y.min(p[1]); + max_y = max_y.max(p[1]); + } + let half_min = 0.5 * (max_x - min_x).min(max_y - min_y); + let new_area = signed_area(&out); + if (-eff_amount) >= half_min - 1e-5 || new_area * orig_area <= 1e-10 { + return Contour { points: Vec::new(), closed: true }; + } + } + + Contour { points: dedup_contour_points(out, true), closed: true } +} + +/// Deterministic signed float in `[-1.0, 1.0]` from `(seed, shape_idx, mod_idx, vertex_idx, axis)`. +#[inline] +fn jitter_hash(seed: i64, shape_idx: u32, mod_idx: u32, vertex_idx: u32, axis: u32) -> f32 { + let mut h = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15) + ^ (shape_idx as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9) + ^ (mod_idx as u64).wrapping_mul(0x94D0_49BB_1331_11EB) + ^ (vertex_idx as u64).wrapping_mul(0xD1B5_4A32_D192_ED03) + ^ (axis as u64).wrapping_mul(0x517C_C1B7_2722_0A95); + h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); + h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); + h ^= h >> 31; + let u = ((h >> 40) as f32) * (1.0 / ((1u32 << 24) as f32)); + u * 2.0 - 1.0 +} + +fn subdivide_for_jitter(pts: &[[f32; 2]], closed: bool) -> Vec<[f32; 2]> { + let n = pts.len(); + if n < 2 || n >= 48 { + return pts.to_vec(); + } + let seg_count = if closed { n } else { n - 1 }; + let mut total_len = 0.0_f32; + for i in 0..seg_count { + let a = pts[i]; + let b = pts[(i + 1) % n]; + total_len += (b[0] - a[0]).hypot(b[1] - a[1]); + } + if total_len <= 1e-6 { + return pts.to_vec(); + } + let target_step = (total_len / 48.0).max(1e-4); + let mut out = Vec::with_capacity(64); + for i in 0..seg_count { + let a = pts[i]; + let b = pts[(i + 1) % n]; + let len = (b[0] - a[0]).hypot(b[1] - a[1]); + let subs = ((len / target_step).ceil() as usize).clamp(1, 32); + for s in 0..subs { + let t = s as f32 / subs as f32; + out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]); + } + } + if !closed { + out.push(pts[n - 1]); + } + out +} + +#[allow(clippy::too_many_arguments)] +fn jitter_contour( + contour: Contour, + x_amount: f32, + y_amount: f32, + seed: i64, + smoothness: f32, + per_shape: bool, + shape_idx: u32, + mod_idx: u32, +) -> Contour { + if per_shape { + let dx = jitter_hash(seed, shape_idx, mod_idx, 0, 0) * x_amount; + let dy = jitter_hash(seed, shape_idx, mod_idx, 0, 1) * y_amount; + let points = contour.points.into_iter().map(|p| [p[0] + dx, p[1] + dy]).collect(); + return Contour { points, closed: contour.closed }; + } + + let pts = subdivide_for_jitter(&contour.points, contour.closed); + let n = pts.len(); + if n < 2 { + return Contour { points: pts, closed: contour.closed }; + } + + let mut offsets: Vec<[f32; 2]> = (0..n) + .map(|i| { + [ + jitter_hash(seed, shape_idx, mod_idx, i as u32, 0) * x_amount, + jitter_hash(seed, shape_idx, mod_idx, i as u32, 1) * y_amount, + ] + }) + .collect(); + + if smoothness > 1e-4 { + let sigma = (smoothness * 2.5).min((n as f32) * 0.5); + let radius = ((sigma * 2.5).ceil() as usize).clamp(1, n / 2); + let inv_two_sig_sq = 0.5 / (sigma * sigma).max(1e-4); + let mut smoothed = vec![[0.0_f32; 2]; n]; + for i in 0..n { + let mut sx = 0.0_f32; + let mut sy = 0.0_f32; + let mut wsum = 0.0_f32; + for d in -(radius as isize)..=(radius as isize) { + let w = (-((d * d) as f32) * inv_two_sig_sq).exp(); + let j = if contour.closed { + (i as isize + d).rem_euclid(n as isize) as usize + } else { + (i as isize + d).clamp(0, (n - 1) as isize) as usize + }; + sx += offsets[j][0] * w; + sy += offsets[j][1] * w; + wsum += w; + } + if wsum > 1e-6 { + smoothed[i] = [sx / wsum, sy / wsum]; + } + } + let boost = (1.0 + sigma.sqrt()).min(3.0); + for s in &mut smoothed { + s[0] = (s[0] * boost).clamp(-x_amount.abs(), x_amount.abs()); + s[1] = (s[1] * boost).clamp(-y_amount.abs(), y_amount.abs()); + } + offsets = smoothed; + } + + let points = pts + .into_iter() + .zip(offsets) + .map(|(p, o)| [p[0] + o[0], p[1] + o[1]]) + .collect(); + Contour { points, closed: contour.closed } +} + +fn shift_contour_position(contour: Contour, position: f32) -> Contour { + let pts = dedup_contour_points(contour.points, contour.closed); + let n = pts.len(); + if n < 2 { + return Contour { points: pts, closed: contour.closed }; + } + + if !contour.closed { + let mut total = 0.0_f32; + for i in 0..n - 1 { + total += (pts[i + 1][0] - pts[i][0]).hypot(pts[i + 1][1] - pts[i][1]); + } + let cdx = pts[n - 1][0] - pts[0][0]; + let cdy = pts[n - 1][1] - pts[0][1]; + let clen = cdx.hypot(cdy); + if clen <= 1e-6 || total <= 1e-6 { + return Contour { points: pts, closed: false }; + } + let shift = position * total; + let tx = (cdx / clen) * shift; + let ty = (cdy / clen) * shift; + return Contour { + points: pts.into_iter().map(|p| [p[0] + tx, p[1] + ty]).collect(), + closed: false, + }; + } + + let frac = position.rem_euclid(1.0); + if frac <= 1e-6 || frac >= 1.0 - 1e-6 { + return Contour { points: pts, closed: true }; + } + + let mut seg_lens = Vec::with_capacity(n); + let mut total = 0.0_f32; + for i in 0..n { + let a = pts[i]; + let b = pts[(i + 1) % n]; + let l = (b[0] - a[0]).hypot(b[1] - a[1]); + seg_lens.push(l); + total += l; + } + if total <= 1e-6 { + return Contour { points: pts, closed: true }; + } + + let target = frac * total; + let mut acc = 0.0_f32; + let mut split_idx = 0usize; + let mut split_t = 0.0_f32; + for (i, &l) in seg_lens.iter().enumerate() { + if acc + l >= target || i + 1 == n { + split_idx = i; + split_t = if l > 1e-6 { ((target - acc) / l).clamp(0.0, 1.0) } else { 0.0 }; + break; + } + acc += l; + } + + let a = pts[split_idx]; + let b = pts[(split_idx + 1) % n]; + let start_pt = [a[0] + (b[0] - a[0]) * split_t, a[1] + (b[1] - a[1]) * split_t]; + let mut out = Vec::with_capacity(n + 1); + out.push(start_pt); + for k in 1..=n { + let idx = (split_idx + k) % n; + let p = pts[idx]; + if (p[0] - out.last().unwrap()[0]).hypot(p[1] - out.last().unwrap()[1]) > 1e-6 { + out.push(p); + } + } + Contour { points: dedup_contour_points(out, true), closed: true } +} + +/// Splits pixel-space `contours` into dash/gap open `zeno::Command` segments for `line_type > 0`. +pub(super) fn dash_contours( + contours: &[Contour], + line_type: u8, + stroke_px: f32, +) -> Vec { + let w = stroke_px.max(1.0); + let pattern: &[f32] = match line_type { + 1 => &[3.0 * w, 2.0 * w], // Dash + 2 => &[0.5 * w, 1.5 * w], // Dot + 3 => &[3.0 * w, 1.5 * w, 0.5 * w, 1.5 * w], // DashDot + 4 => &[3.0 * w, 1.5 * w, 0.5 * w, 1.5 * w, 0.5 * w, 1.5 * w], // DashDotDot + _ => return Vec::new(), + }; + let mut out = Vec::new(); + for c in contours { + let n = c.points.len(); + if n < 2 { + continue; + } + let seg_count = if c.closed { n } else { n - 1 }; + let mut pat_idx = 0usize; + let mut pat_rem = pattern[0]; + let mut draw_on = true; + let mut pen_active = false; + for s in 0..seg_count { + let a = c.points[s]; + let b = c.points[(s + 1) % n]; + let dx = b[0] - a[0]; + let dy = b[1] - a[1]; + let len = dx.hypot(dy); + if len <= 1e-6 { + continue; + } + let mut pos = 0.0_f32; + while pos < len - 1e-5 { + let step = pat_rem.min(len - pos); + let t0 = pos / len; + let t1 = (pos + step) / len; + let p0 = [a[0] + dx * t0, a[1] + dy * t0]; + let p1 = [a[0] + dx * t1, a[1] + dy * t1]; + if draw_on { + if !pen_active { + out.push(zeno::Command::MoveTo(zeno::Vector::new(p0[0], p0[1]))); + pen_active = true; + } + out.push(zeno::Command::LineTo(zeno::Vector::new(p1[0], p1[1]))); + } else { + pen_active = false; + } + pos += step; + pat_rem -= step; + if pat_rem <= 1e-5 { + pat_idx = (pat_idx + 1) % pattern.len(); + pat_rem = pattern[pat_idx]; + draw_on = pat_idx % 2 == 0; + if !draw_on { + pen_active = false; + } + } + } + } + } + out +} diff --git a/crates/engine/src/eval/shapes/raster.rs b/crates/engine/src/eval/shapes/raster.rs index 5d2083fbc6e51c5aca9a6f045033806027cb571f..d652da0db5995129e3b76db2a0e7ef1331041368 100644 --- a/crates/engine/src/eval/shapes/raster.rs +++ b/crates/engine/src/eval/shapes/raster.rs @@ -1,6 +1,9 @@ //! CPU rasterizer for 2D vector `ShapeTree` hierarchies using `zeno`. -use super::geometry::{build_primitive_commands_px, clip_to_viewport, trim_path_commands}; +use super::geometry::{ + build_primitive_commands_px, clip_to_viewport, closed_outline_fill_commands, + dash_path_commands, trim_path_commands, +}; use super::{Affine2D, PathModifier, ShapeBoolOp, ShapeTree}; fn composite_over(dst: &mut [f32], src: &[f32]) { @@ -17,6 +20,239 @@ fn composite_over(dst: &mut [f32], src: &[f32]) { } } +struct PreparedPrim { + cmds: Vec, + closed: bool, + stroke_px: f32, + use_even_odd_ring: bool, +} + +#[allow(clippy::too_many_arguments)] +fn prepare_primitive_cmds( + tree: &ShapeTree, + dims: [u32; 2], + mods: &[(PathModifier, Affine2D)], + shape_idx: u32, +) -> Option { + let ShapeTree::Primitive { + kind, + xform, + solid, + border_width, + join_style, + cap_style: _, + miter_limit, + write_pos, + write_len, + fill_even_odd: _, + line_type, + .. + } = tree + else { + return None; + }; + let [w, h] = dims; + let (cmds, closed) = build_primitive_commands_px(kind, *xform, mods, shape_idx, dims); + let finite = |v: &zeno::Vector| v.x.is_finite() && v.y.is_finite(); + let degenerate = cmds.iter().any(|c| match c { + zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => !finite(p), + zeno::Command::QuadTo(a, p) => !(finite(a) && finite(p)), + zeno::Command::CurveTo(a, b, p) => !(finite(a) && finite(b) && finite(p)), + _ => false, + }); + if cmds.is_empty() || degenerate { + return None; + } + let reach = 4.0 * w.max(h) as f32; + let mut total_scale = xform.avg_scale(); + for (_, px) in mods { + total_scale *= px.avg_scale(); + } + let stroke_px = (*border_width * total_scale * (w as f32)).clamp(0.5, reach); + let cmds = clip_to_viewport( + cmds, + closed, + dims, + if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, + ); + let is_trimmed = !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5); + let cmds = if is_trimmed { + trim_path_commands(cmds, closed, *write_pos, *write_len) + } else { + cmds + }; + let eff_closed = closed && (!is_trimmed || *write_len >= 1.0 - 1e-5); + let cmds = if !*solid && *line_type > 0 { + dash_path_commands(cmds, eff_closed, *line_type, stroke_px) + } else { + cmds + }; + if cmds.is_empty() { + return None; + } + + let mut use_even_odd_ring = false; + let cmds = if !*solid && eff_closed && *line_type == 0 && stroke_px > 3.0 { + if let Some(ring_cmds) = closed_outline_fill_commands(&cmds, stroke_px, *join_style, *miter_limit) { + use_even_odd_ring = true; + ring_cmds + } else { + cmds + } + } else { + cmds + }; + + Some(PreparedPrim { + cmds, + closed: eff_closed, + stroke_px, + use_even_odd_ring, + }) +} + +#[derive(Clone, Copy, PartialEq)] +struct PrimStyleKey { + color: [u32; 4], + solid: bool, + border_width: u32, + join_style: u8, + cap_style: u8, + miter_limit: u32, + fill_even_odd: bool, + line_type: u8, +} + +fn prim_style_key(tree: &ShapeTree) -> Option { + let ShapeTree::Primitive { + color, + solid, + border_width, + join_style, + cap_style, + miter_limit, + fill_even_odd, + line_type, + .. + } = tree + else { + return None; + }; + Some(PrimStyleKey { + color: color.map(f32::to_bits), + solid: *solid, + border_width: border_width.to_bits(), + join_style: *join_style, + cap_style: *cap_style, + miter_limit: miter_limit.to_bits(), + fill_even_odd: *fill_even_odd, + line_type: *line_type, + }) +} + +#[allow(clippy::too_many_arguments)] +fn rasterize_cmds_cov( + cmds: &[zeno::Command], + closed: bool, + solid: bool, + stroke_px: f32, + join_style: u8, + cap_style: u8, + miter_limit: f32, + fill_even_odd: bool, + use_even_odd_ring: bool, + dims: [u32; 2], + cov_buf: &mut [u8], + scratch: &mut zeno::Scratch, +) { + let [w, h] = dims; + cov_buf.fill(0); + if cmds.is_empty() { + return; + } + let style = if use_even_odd_ring { + zeno::Style::Fill(zeno::Fill::EvenOdd) + } else if solid && closed { + zeno::Style::Fill(if fill_even_odd { zeno::Fill::EvenOdd } else { zeno::Fill::NonZero }) + } else { + let join = match join_style { + 0 => zeno::Join::Bevel, + 1 => zeno::Join::Round, + _ => zeno::Join::Miter, + }; + let cap = match cap_style { + 1 => zeno::Cap::Round, + 2 => zeno::Cap::Square, + _ => zeno::Cap::Butt, + }; + let mut st = zeno::Stroke::new(stroke_px); + st.join(join).cap(cap).miter_limit(miter_limit); + zeno::Style::Stroke(st) + }; + let _ = zeno::Mask::with_scratch(cmds, scratch) + .style(style) + .size(w, h) + .origin(zeno::Origin::TopLeft) + .render_into(cov_buf, None); +} + +fn blend_cov_into_dst(color: [f32; 4], cov_buf: &[u8], dst: &mut [f32]) { + let ca = color[3].clamp(0.0, 1.0); + if ca <= 1e-6 { + return; + } + // Fusion keeps the colour unpremultiplied: Alpha scales coverage into alpha only, not RGB. + for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { + if cov == 0 { + continue; + } + let c = cov as f32 / 255.0; + let inv = 1.0 - c * ca; + px[0] = color[0] * c + px[0] * inv; + px[1] = color[1] * c + px[1] * inv; + px[2] = color[2] * c + px[2] * inv; + px[3] = c * ca + px[3] * inv; + } +} + +#[allow(clippy::too_many_arguments)] +fn render_cmds_into_dst( + cmds: &[zeno::Command], + closed: bool, + color: [f32; 4], + solid: bool, + stroke_px: f32, + join_style: u8, + cap_style: u8, + miter_limit: f32, + fill_even_odd: bool, + use_even_odd_ring: bool, + dims: [u32; 2], + dst: &mut [f32], + cov_buf: &mut [u8], + scratch: &mut zeno::Scratch, +) { + let ca = color[3].clamp(0.0, 1.0); + if ca <= 1e-6 || cmds.is_empty() { + return; + } + rasterize_cmds_cov( + cmds, + closed, + solid, + stroke_px, + join_style, + cap_style, + miter_limit, + fill_even_odd, + use_even_odd_ring, + dims, + cov_buf, + scratch, + ); + blend_cov_into_dst(color, cov_buf, dst); +} + fn rasterize_shape_tree_f32( tree: &ShapeTree, dims: [u32; 2], @@ -26,100 +262,96 @@ fn rasterize_shape_tree_f32( cov_buf: &mut [u8], scratch: &mut zeno::Scratch, ) { - let [w, h] = dims; match tree { ShapeTree::Primitive { - kind, - xform, color, solid, - border_width, join_style, cap_style, miter_limit, - write_pos, - write_len, + fill_even_odd, + .. } => { let shape_idx = *shape_counter; *shape_counter = shape_counter.wrapping_add(1); - - let (cmds, closed) = build_primitive_commands_px(kind, *xform, mods, shape_idx, dims); - let finite = |v: &zeno::Vector| v.x.is_finite() && v.y.is_finite(); - let degenerate = cmds.iter().any(|c| match c { - zeno::Command::MoveTo(p) | zeno::Command::LineTo(p) => !finite(p), - zeno::Command::QuadTo(a, p) => !(finite(a) && finite(p)), - zeno::Command::CurveTo(a, b, p) => !(finite(a) && finite(b) && finite(p)), - _ => false, - }); - if cmds.is_empty() || degenerate { + let Some(prep) = prepare_primitive_cmds(tree, dims, mods, shape_idx) else { return; - } - cov_buf.fill(0); - let reach = 4.0 * w.max(h) as f32; - let mut total_scale = xform.avg_scale(); - for (_, px) in mods { - total_scale *= px.avg_scale(); - } - let stroke_px = (*border_width * total_scale * (w as f32)).clamp(0.5, reach); - let cmds = clip_to_viewport( - cmds, - closed, + }; + render_cmds_into_dst( + &prep.cmds, + prep.closed, + *color, + *solid, + prep.stroke_px, + *join_style, + *cap_style, + *miter_limit, + *fill_even_odd, + prep.use_even_odd_ring, dims, - if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, + dst, + cov_buf, + scratch, ); - let cmds = if !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5) { - trim_path_commands(cmds, closed, *write_pos, *write_len) - } else { - cmds - }; - if cmds.is_empty() { - return; - } - let style = if *solid && closed { - zeno::Style::Fill(zeno::Fill::NonZero) - } else { - let join = match *join_style { - 0 => zeno::Join::Bevel, - 1 => zeno::Join::Round, - _ => zeno::Join::Miter, - }; - let cap = match *cap_style { - 1 => zeno::Cap::Round, - 2 => zeno::Cap::Square, - _ => zeno::Cap::Butt, - }; - let mut st = zeno::Stroke::new(stroke_px); - st.join(join).cap(cap).miter_limit(*miter_limit); - zeno::Style::Stroke(st) - }; - let _ = zeno::Mask::with_scratch(&cmds, scratch) - .style(style) - .size(w, h) - .origin(zeno::Origin::TopLeft) - .render_into(cov_buf, None); - - let ca = color[3].clamp(0.0, 1.0); - if ca <= 1e-6 { - return; - } - // Fusion keeps the colour unpremultiplied: Alpha scales coverage into alpha only, not RGB. - for (px, &cov) in dst.chunks_exact_mut(4).zip(cov_buf.iter()) { - if cov == 0 { - continue; - } - let c = cov as f32 / 255.0; - let inv = 1.0 - c * ca; - px[0] = color[0] * c + px[0] * inv; - px[1] = color[1] * c + px[1] * inv; - px[2] = color[2] * c + px[2] * inv; - px[3] = c * ca + px[3] * inv; - } } ShapeTree::Group(children) => { for ch in children { rasterize_shape_tree_f32(ch, dims, mods, shape_counter, dst, cov_buf, scratch); } } + ShapeTree::CombineGroup(children) => { + if let Some(first) = children.first() { + if let Some(first_key) = prim_style_key(first) { + if children.iter().all(|c| prim_style_key(c) == Some(first_key)) { + let ShapeTree::Primitive { + color, + solid, + join_style, + cap_style, + miter_limit, + fill_even_odd, + .. + } = first + else { + unreachable!(); + }; + let mut union_cov = vec![0u8; cov_buf.len()]; + let mut any_hit = false; + for ch in children { + let shape_idx = *shape_counter; + *shape_counter = shape_counter.wrapping_add(1); + if let Some(prep) = prepare_primitive_cmds(ch, dims, mods, shape_idx) { + rasterize_cmds_cov( + &prep.cmds, + prep.closed, + *solid, + prep.stroke_px, + *join_style, + *cap_style, + *miter_limit, + *fill_even_odd, + prep.use_even_odd_ring, + dims, + cov_buf, + scratch, + ); + any_hit = true; + for (u, &c) in union_cov.iter_mut().zip(cov_buf.iter()) { + *u = (*u).max(c); + } + } + } + if any_hit { + blend_cov_into_dst(*color, &union_cov, dst); + } + return; + } + } + } + for ch in children { + rasterize_shape_tree_f32(ch, dims, mods, shape_counter, dst, cov_buf, scratch); + } + } ShapeTree::Modify { op, post_xform, child } => { let mut next_mods = Vec::with_capacity(mods.len() + 1); next_mods.push((*op, *post_xform)); diff --git a/crates/engine/src/eval/shapes/tests.rs b/crates/engine/src/eval/shapes/tests.rs index 4f21bc2c8653f926e990b3b23709c328a323c54e..c56622ff2aa9d0393727a7e9d0cf1830949fee47 100644 --- a/crates/engine/src/eval/shapes/tests.rs +++ b/crates/engine/src/eval/shapes/tests.rs @@ -744,3 +744,188 @@ fn test_s_polygon_closed_open_bezier_and_transform() { let apex_hit = (25..45).any(|y| p_op[(y * 100 + 50) * 4] > 200 && p_op[(y * 100 + 50) * 4 + 3] > 200); assert!(apex_hit, "open Bezier sPolygon arch apex must be stroked in red"); } + +#[test] +fn test_s_bspline_closed_and_open() { + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + BS1 = sBSpline { + Inputs = { + Red = Input { Value = 1, }, Green = Input { Value = 0, }, Blue = Input { Value = 0, }, + Polyline = Input { + Value = BSplinePolyline { + Closed = true, + Points = { + { X = -0.2, Y = -0.2, W = 1 }, + { X = 0.2, Y = -0.2, W = 1 }, + { X = 0.2, Y = 0.2, W = 1 }, + { X = -0.2, Y = 0.2, W = 1 }, + }, + }, + }, + }, + }, + R = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "BS1", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + let (tex, stats) = eng.evaluate(&comp, comp.find_node("R").unwrap(), 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let rgba = eng.readback_rgba(&tex).unwrap(); + let mid = (32 * 64 + 32) * 4; + assert_eq!(&rgba[mid..mid + 4], &[255, 0, 0, 255]); + assert_eq!(&rgba[0..4], &[0, 0, 0, 0]); + + // Open stroked sBSpline: center (32, 32) must remain transparent, while curve stroke along y=0 (32) near x=32 is red. + let open_src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + BSOpen = sBSpline { + Inputs = { + Solid = Input { Value = 0, }, + BorderWidth = Input { Value = 0.06, }, + Red = Input { Value = 0, }, Green = Input { Value = 1, }, Blue = Input { Value = 0, }, + Polyline = Input { + Value = BSplinePolyline { + Closed = false, + Points = { + { X = -0.35, Y = -0.2, W = 1 }, + { X = 0.0, Y = 0.2, W = 1 }, + { X = 0.35, Y = -0.2, W = 1 }, + }, + }, + }, + }, + }, + R = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "BSOpen", Source = "Output", }, }, }, + }, + }"#; + let open_comp = Comp::from_fusion_str(open_src).unwrap(); + let (tex_o, _) = eng.evaluate(&open_comp, open_comp.find_node("R").unwrap(), 0.0); + let po = eng.readback_rgba(&tex_o).unwrap(); + let stroke_hits = (0..64) + .flat_map(|y| (0..64).map(move |x| (y * 64 + x) * 4)) + .filter(|&i| po[i + 1] > 150 && po[i] < 20 && po[i + 3] > 150) + .count(); + assert!(stroke_hits > 30, "open stroked sBSpline should render green curve, hits={stroke_hits}"); + assert_eq!(po[(56 * 64 + 32) * 4 + 3], 0, "open sBSpline bottom background stays hollow"); +} + +#[test] +fn test_s_change_style_color_opacity_and_stroke_override() { + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + RectA = sRectangle { + Inputs = { + Width = Input { Value = 0.5, }, + Height = Input { Value = 0.5, }, + Red = Input { Value = 1, }, Green = Input { Value = 0, }, Blue = Input { Value = 0, }, + }, + }, + CSColor = sChangeStyle { + Inputs = { + Input = Input { SourceOp = "RectA", Source = "Output", }, + Red = Input { Value = 0, }, Green = Input { Value = 1, }, Blue = Input { Value = 0.5, }, + Alpha = Input { Value = 0.5, }, Opacity = Input { Value = 0.5, }, + }, + }, + RColor = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CSColor", Source = "Output", }, }, }, + CSOutline = sChangeStyle { + Inputs = { + Input = Input { SourceOp = "RectA", Source = "Output", }, + Red = Input { Value = 0, }, Green = Input { Value = 0, }, Blue = Input { Value = 1, }, + Solid = Input { Value = 0, }, + BorderWidth = Input { Value = 0.05, }, + }, + }, + ROutline = sRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CSOutline", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (t1, s1) = eng.evaluate(&comp, comp.find_node("RColor").unwrap(), 0.0); + assert!(s1.unsupported_nodes.is_empty()); + let p1 = eng.readback_rgba(&t1).unwrap(); + let mid = (32 * 64 + 32) * 4; + // Alpha = 0.5 * 0.5 = 0.25 -> [0, 128, 64, 64] in straight RGBA output (matching Fusion GT). + assert_eq!(p1[mid], 0); + assert!(p1[mid + 1] > 115 && p1[mid + 1] < 140, "expected green ~128, got {:?}", &p1[mid..mid + 4]); + assert!(p1[mid + 2] > 55 && p1[mid + 2] < 75, "expected blue ~64, got {:?}", &p1[mid..mid + 4]); + assert!(p1[mid + 3] > 55 && p1[mid + 3] < 75, "expected alpha ~64, got {}", p1[mid + 3]); + + let (t2, s2) = eng.evaluate(&comp, comp.find_node("ROutline").unwrap(), 0.0); + assert!(s2.unsupported_nodes.is_empty()); + let p2 = eng.readback_rgba(&t2).unwrap(); + assert_eq!(p2[mid + 3], 0, "Solid=0 override must hollow out rectangle interior"); + let border_hits = (0..64) + .flat_map(|y| (0..64).map(move |x| (y * 64 + x) * 4)) + .filter(|&i| p2[i + 2] > 180 && p2[i + 3] > 180) + .count(); + assert!(border_hits > 60, "blue stroke override must render border, hits={border_hits}"); +} + +#[test] +fn test_s_text_contours_and_composition() { + let src = r#"Composition { + CurrentTime = 0, RenderRange = { 0, 0 }, GlobalRange = { 0, 0 }, + Tools = ordered() { + Txt = sText { + Inputs = { + StyledText = Input { Value = "HI", }, + Font = Input { Value = "Open Sans", }, + Style = Input { Value = "Bold", }, + Size = Input { Value = 0.35, }, + Red1 = Input { Value = 1, }, Green1 = Input { Value = 0.5, }, Blue1 = Input { Value = 0, }, + }, + }, + Out = sOutline { + Inputs = { + Input = Input { SourceOp = "Txt", Source = "Output", }, + Thickness = Input { Value = 0.02, }, + }, + }, + Exp = sExpand { + Inputs = { + Input = Input { SourceOp = "Txt", Source = "Output", }, + Expand = Input { Value = 0.015, }, + }, + }, + Cut = sRectangle { + Inputs = { + Width = Input { Value = 0.12, }, Height = Input { Value = 0.12, }, + Red = Input { Value = 0, }, Green = Input { Value = 0, }, Blue = Input { Value = 1, }, + }, + }, + Bool = sBoolean { + Inputs = { + Operation = Input { Value = FuID { "Union" }, }, + Input1 = Input { SourceOp = "Txt", Source = "Output", }, + Input2 = Input { SourceOp = "Cut", Source = "Output", }, + }, + }, + Xform = sTransform { + Inputs = { + Input = Input { SourceOp = "Bool", Source = "Output", }, + XOffset = Input { Value = 0.05, }, + }, + }, + RTxt = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Txt", Source = "Output", }, }, }, + ROut = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Out", Source = "Output", }, }, }, + RExp = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Exp", Source = "Output", }, }, }, + RXform = sRender { Inputs = { Width = Input { Value = 128, }, Height = Input { Value = 128, }, Input = Input { SourceOp = "Xform", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return }; + for name in ["RTxt", "ROut", "RExp", "RXform"] { + let (tex, stats) = eng.evaluate(&comp, comp.find_node(name).unwrap(), 0.0); + assert!(stats.unsupported_nodes.is_empty(), "{name} unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba(&tex).unwrap(); + let lit = px.chunks_exact(4).filter(|c| c[3] > 20).count(); + assert!(lit > 50, "{name} must rasterize visible glyph pixels, lit={lit}"); + } +} diff --git a/crates/engine/src/eval/warps_masks/bspline.rs b/crates/engine/src/eval/warps_masks/bspline.rs index 3d9323b58e2611dcbc6a7ae40e78ce0152e6b23b..b11c235bd3d07f91528ed0c24c3725c63b0cfbed 100644 --- a/crates/engine/src/eval/warps_masks/bspline.rs +++ b/crates/engine/src/eval/warps_masks/bspline.rs @@ -38,7 +38,7 @@ pub(in crate::eval) fn parse_bspline_table(tbl: &LuaTable) -> BSplineShape { BSplineShape { closed, points } } -fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { +pub(in crate::eval) fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a LuaTable> { if let Some(t) = tools.get_table(name) { return Some(t); } @@ -54,7 +54,7 @@ fn find_tool_table_in_tools<'a>(tools: &'a LuaTable, name: &str) -> Option<&'a L None } -fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option> { +pub(in crate::eval) fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option> { let kfs = spline_tbl.get_table("KeyFrames")?; let mut out = Vec::with_capacity(kfs.entries.len()); for (k, v) in &kfs.entries { @@ -76,7 +76,7 @@ fn parse_bspline_keyframes(spline_tbl: &LuaTable) -> Option BSplineShape { +pub(in crate::eval) fn eval_bspline_shape(comp: &Comp, node: &Node, time: f64) -> BSplineShape { for port in ["Polyline", "PolyLine", "Polyline2"] { if let Some(src_name) = node.connected_node(port) { if let Some(root) = comp.raw_root.as_ref() { @@ -178,43 +178,29 @@ fn eval_bspline_shape(comp: &Comp, node: &Node, time: f64) -> BSplineShape { BSplineShape { closed: false, points: Vec::new() } } -/// Evaluates a uniform rational cubic B-spline into pixel-space polygon vertices. -pub(in crate::eval) fn evaluate_bspline_polygon( - shape: &BSplineShape, - size: [u32; 2], - center: [f32; 2], - scale: f32, - angle_deg: f32, +/// Evaluates a uniform rational cubic B-spline over already-transformed 2D control points. +pub(in crate::eval) fn eval_rational_cubic_bspline_2d( + points: &[([f32; 2], f32)], + closed: bool, + steps_for_chord: impl Fn(f32) -> usize, ) -> Vec<[f32; 2]> { - let n = shape.points.len(); - if (shape.closed && n < 3) || (!shape.closed && n < 2) || size[0] == 0 || size[1] == 0 { + let n = points.len(); + if (closed && n < 3) || (!closed && n < 2) { return Vec::new(); } - let [w, h] = size; - let aspect = w as f32 / (h as f32).max(1.0); - let (s, c) = angle_deg.to_radians().sin_cos(); - let to_px = |x: f64, y: f64| -> [f32; 2] { - let sx = x as f32 * scale; - let sy = (y as f32 * scale) / aspect; - let rx = sx * c - sy * s; - let ry = (sx * s + sy * c) * aspect; - [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] - }; - let mut ctrl: Vec<([f32; 2], f32)> = Vec::with_capacity(n + 6); - if shape.closed { - for p in &shape.points { - ctrl.push((to_px(p.x, p.y), p.w.max(0.0) as f32)); + if closed { + for &(pt, w) in points { + ctrl.push((pt, w.max(0.0))); } } else { // Clamped open cubic B-spline: repeat endpoints twice so curve interpolates P0 and P_{n-1}. - let first = (to_px(shape.points[0].x, shape.points[0].y), shape.points[0].w.max(0.0) as f32); - let last_p = shape.points[n - 1]; - let last = (to_px(last_p.x, last_p.y), last_p.w.max(0.0) as f32); + let first = (points[0].0, points[0].1.max(0.0)); + let last = (points[n - 1].0, points[n - 1].1.max(0.0)); ctrl.push(first); ctrl.push(first); - for p in &shape.points { - ctrl.push((to_px(p.x, p.y), p.w.max(0.0) as f32)); + for &(pt, w) in points { + ctrl.push((pt, w.max(0.0))); } ctrl.push(last); ctrl.push(last); @@ -243,17 +229,17 @@ pub(in crate::eval) fn evaluate_bspline_polygon( ]) }; - let seg_count = if shape.closed { n } else { ctrl.len().saturating_sub(3) }; + let seg_count = if closed { n } else { ctrl.len().saturating_sub(3) }; let mut poly = Vec::with_capacity(seg_count * 20); for seg in 0..seg_count { - let (p0, p1, p2, p3) = if shape.closed { + let (p0, p1, p2, p3) = if closed { (ctrl[(seg + n - 1) % n], ctrl[seg], ctrl[(seg + 1) % n], ctrl[(seg + 2) % n]) } else { (ctrl[seg], ctrl[seg + 1], ctrl[seg + 2], ctrl[seg + 3]) }; let chord = (p2.0[0] - p1.0[0]).hypot(p2.0[1] - p1.0[1]); - let steps = ((chord * 0.25).ceil() as usize).clamp(16, 48); - let end = if !shape.closed && seg + 1 == seg_count { steps } else { steps - 1 }; + let steps = steps_for_chord(chord).max(1); + let end = if !closed && seg + 1 == seg_count { steps } else { steps - 1 }; for st in 0..=end { let t = st as f32 / steps as f32; if let Some(pt) = eval_seg(p0, p1, p2, p3, t) { @@ -266,6 +252,38 @@ pub(in crate::eval) fn evaluate_bspline_polygon( poly } +/// Evaluates a uniform rational cubic B-spline into pixel-space polygon vertices. +pub(in crate::eval) fn evaluate_bspline_polygon( + shape: &BSplineShape, + size: [u32; 2], + center: [f32; 2], + scale: f32, + angle_deg: f32, +) -> Vec<[f32; 2]> { + let n = shape.points.len(); + if (shape.closed && n < 3) || (!shape.closed && n < 2) || size[0] == 0 || size[1] == 0 { + return Vec::new(); + } + let [w, h] = size; + let aspect = w as f32 / (h as f32).max(1.0); + let (s, c) = angle_deg.to_radians().sin_cos(); + let to_px = |x: f64, y: f64| -> [f32; 2] { + let sx = x as f32 * scale; + let sy = (y as f32 * scale) / aspect; + let rx = sx * c - sy * s; + let ry = (sx * s + sy * c) * aspect; + [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32] + }; + let pts: Vec<([f32; 2], f32)> = shape + .points + .iter() + .map(|p| (to_px(p.x, p.y), p.w as f32)) + .collect(); + eval_rational_cubic_bspline_2d(&pts, shape.closed, |chord| { + ((chord * 0.25).ceil() as usize).clamp(16, 48) + }) +} + fn trim_poly_arc(poly: &[[f32; 2]], closed: bool, write_pos: f32, write_len: f32) -> Vec<[f32; 2]> { let write_pos = if write_pos.is_finite() { write_pos } else { 0.0 }; let write_len = if write_len.is_finite() { write_len.clamp(0.0, 1.0) } else { 1.0 }; diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index 78c01a28cc1d60815cb2e1c7f52563bebab599b7..c924e75a92bdeb5bac54f16908fde701f6115a95 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -4,11 +4,16 @@ //! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pVortex`, `pFlock`, `pSpawn`, //! `pChangeStyle`, `pGradientForce`, `pMerge`, and `pRender` (2D mode). +mod custom; +mod custom_eval; +mod extra_forces; mod forces; mod plan; mod raster; mod sim; #[cfg(test)] +mod extra_tests; +#[cfg(test)] mod tests; pub use plan::collect_bitmap_sources; @@ -90,16 +95,29 @@ struct CachedSim { snapshots: BTreeMap, } -#[derive(Clone, Default)] +#[derive(Clone)] struct SimState { particles: Vec, /// Fractional emission accumulator per `pEmitter` stable name hash. emit_accum: HashMap, + /// Monotonically increasing particle ID counter for `id` in `pCustom` / `pAvoid`. + next_id: u32, +} + +impl Default for SimState { + fn default() -> Self { + Self { + particles: Vec::new(), + emit_accum: HashMap::new(), + next_id: 1, + } + } } #[derive(Clone, Copy, Debug)] struct Particle { emitter_hash: u64, + id: u32, /// Particle set membership bitmask (bit 0 = Set1 .. bit 31 = Set32). sets: u32, /// Optional per-particle style override applied by `pChangeStyle` / `pSpawn`. @@ -110,11 +128,15 @@ struct Particle { bitmap_owner_hash: u64, pos: [f64; 3], vel: [f64; 3], + rot_xy: [f64; 2], rot_z: f64, + spin_xy: [f64; 2], spin_z: f64, age: f64, lifespan: f64, size: f64, + mass: f64, + user: f64, color: [f32; 4], alive: bool, } @@ -244,7 +266,7 @@ pub fn render_particles_2d( let gradient_fields = build_gradient_fields(comp, &plan.modifiers, sprites); let mut subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); - if !gradient_fields.is_empty() { + if !gradient_fields.is_empty() || !sprites.is_empty() { let mut h = DefaultHasher::new(); subgraph_hash.hash(&mut h); let mut gf_ids: Vec = gradient_fields.keys().copied().collect(); @@ -253,6 +275,18 @@ pub fn render_particles_2d( id.0.hash(&mut h); gradient_fields[&id].content_hash.hash(&mut h); } + let mut spr_ids: Vec = sprites.keys().copied().collect(); + spr_ids.sort_by_key(|id| id.0); + for id in spr_ids { + let sp = &sprites[&id]; + id.0.hash(&mut h); + sp.size.hash(&mut h); + sp.rgba.len().hash(&mut h); + let step = (sp.rgba.len() / 256).max(1); + for b in sp.rgba.iter().step_by(step) { + b.hash(&mut h); + } + } subgraph_hash = h.finish(); } let key = (rnode.name.clone(), subgraph_hash); @@ -270,7 +304,16 @@ pub fn render_particles_2d( } else if target_frame > cached.current_frame { if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) { for f in cached.current_frame.saturating_add(1)..=target_frame { - step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); + step_simulation( + &mut cached.state, + comp, + &plan, + &gradient_fields, + sprites, + f, + sim_origin, + expr, + ); maybe_record_snapshot(cached, f); } cached.current_frame = target_frame; @@ -284,7 +327,16 @@ pub fn render_particles_2d( cached.current_frame = snap_f; if snap_f < target_frame { for f in snap_f.saturating_add(1)..=target_frame { - step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); + step_simulation( + &mut cached.state, + comp, + &plan, + &gradient_fields, + sprites, + f, + sim_origin, + expr, + ); maybe_record_snapshot(cached, f); } } @@ -309,7 +361,16 @@ pub fn render_particles_2d( snapshots: BTreeMap::new(), }; for f in sim_start..=target_frame { - step_simulation(&mut sim.state, comp, &plan, &gradient_fields, f, expr); + step_simulation( + &mut sim.state, + comp, + &plan, + &gradient_fields, + sprites, + f, + sim_start, + expr, + ); maybe_record_snapshot(&mut sim, f); } cache.entries.insert(key.clone(), sim); diff --git a/crates/engine/src/particles/custom.rs b/crates/engine/src/particles/custom.rs new file mode 100644 index 0000000000000000000000000000000000000000..5be37ca6a7208b4da799f4f07dc9652396bd2409 --- /dev/null +++ b/crates/engine/src/particles/custom.rs @@ -0,0 +1,494 @@ +//! Pure-Rust per-particle expression parser & evaluator for `pCustom` and `pCustomForce`. +//! +//! Supports Fusion particle expressions (`px/py/pz`, `vx/vy/vz`, `rx/ry/rz`, `sx/sy/sz`, +//! `r/g/b/a`, `size`, `age`, `lifespan`/`life`, `id`, `mass`, `user`, `time`, `n1..n8`, +//! `p1x/p1y/p1z..p4x/p4y/p4z`, `s1..s4`, `i1..i8`, `getr1/g1/b1/a1`, degree trig + radian +//! `sinr/cosr/...`, `abs/sqrt/pow/exp/log/floor/ceil/round/clamp/min/max/if/iif/mix/step/smoothstep/rand/rands/noise`). + + +#[derive(Clone, Debug, PartialEq)] +enum Tok { + Num(f64), + Ident(String), + Plus, + Minus, + Star, + Slash, + Percent, + Caret, + LParen, + RParen, + Comma, + Lt, + Le, + Gt, + Ge, + Eq, + Ne, + And, + Or, + Bang, +} + +fn tokenize(src: &str) -> Result, ()> { + let b = src.as_bytes(); + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let c = b[i]; + if c.is_ascii_whitespace() { + i += 1; + continue; + } + if c == b'/' && b.get(i + 1) == Some(&b'/') { + i += 2; + while i < b.len() && b[i] != b'\n' { + i += 1; + } + continue; + } + if c == b'/' && b.get(i + 1) == Some(&b'*') { + i += 2; + while i + 1 < b.len() && !(b[i] == b'*' && b[i + 1] == b'/') { + i += 1; + } + i = (i + 2).min(b.len()); + continue; + } + if c.is_ascii_digit() || (c == b'.' && b.get(i + 1).is_some_and(u8::is_ascii_digit)) { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if b.get(i) == Some(&b'.') { + i += 1; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + } + if matches!(b.get(i), Some(b'e' | b'E')) { + let exp_pos = i; + i += 1; + if matches!(b.get(i), Some(b'+' | b'-')) { + i += 1; + } + let dig_start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if i == dig_start { + i = exp_pos; + } + } + let v: f64 = src[start..i].parse().map_err(|_| ())?; + out.push(Tok::Num(v)); + continue; + } + if c.is_ascii_alphabetic() || c == b'_' { + let start = i; + while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') { + i += 1; + } + out.push(Tok::Ident(src[start..i].to_owned())); + continue; + } + let next = b.get(i + 1).copied(); + match (c, next) { + (b'<', Some(b'=')) => { out.push(Tok::Le); i += 2; } + (b'>', Some(b'=')) => { out.push(Tok::Ge); i += 2; } + (b'=', Some(b'=')) => { out.push(Tok::Eq); i += 2; } + (b'!', Some(b'=')) | (b'~', Some(b'=')) | (b'<', Some(b'>')) => { out.push(Tok::Ne); i += 2; } + (b'&', Some(b'&')) => { out.push(Tok::And); i += 2; } + (b'|', Some(b'|')) => { out.push(Tok::Or); i += 2; } + (b'+', _) => { out.push(Tok::Plus); i += 1; } + (b'-', _) => { out.push(Tok::Minus); i += 1; } + (b'*', _) => { out.push(Tok::Star); i += 1; } + (b'/', _) => { out.push(Tok::Slash); i += 1; } + (b'%', _) => { out.push(Tok::Percent); i += 1; } + (b'^', _) => { out.push(Tok::Caret); i += 1; } + (b'(', _) => { out.push(Tok::LParen); i += 1; } + (b')', _) => { out.push(Tok::RParen); i += 1; } + (b',', _) => { out.push(Tok::Comma); i += 1; } + (b'<', _) => { out.push(Tok::Lt); i += 1; } + (b'>', _) => { out.push(Tok::Gt); i += 1; } + (b'=', _) => { out.push(Tok::Eq); i += 1; } + (b'&', _) => { out.push(Tok::And); i += 1; } + (b'|', _) => { out.push(Tok::Or); i += 1; } + (b'!', _) => { out.push(Tok::Bang); i += 1; } + _ => return Err(()), + } + } + Ok(out) +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Var { + Px, Py, Pz, + Vx, Vy, Vz, + Rx, Ry, Rz, + Sx, Sy, Sz, + R, G, B, A, + Size, Age, Lifespan, Id, Mass, User, Time, Pi, E, + Num(u8), + Pt(u8, u8), + Setup(u8), + Inter(u8), +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum BinOp { + Add, Sub, Mul, Div, Mod, Pow, + Lt, Le, Gt, Ge, Eq, Ne, + And, Or, +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Func { + Sin, Cos, Tan, Asin, Acos, Atan, Atan2, + Sinr, Cosr, Tanr, Asinr, Acosr, Atanr, Atan2r, + Sinh, Cosh, Tanh, Deg, Rad, + Abs, Sqrt, Pow, Exp, Log, Log10, Log2, + Floor, Ceil, Round, Trunc, Fract, Sign, + Min, Max, Clamp, Mod, If, Dist, Hypot, Mix, Step, Smoothstep, + Rand, Rands, Noise1, Noise2, Noise3, + SampleImg(u8, u8), // (channel 0..4, edge_mode 0..2) +} + +#[derive(Clone, Debug)] +pub(super) enum Ast { + Const(f64), + Var(Var), + Neg(Box), + Not(Box), + Bin(BinOp, Box, Box), + Call(Func, Vec), +} + +struct Parser<'a> { + toks: &'a [Tok], + pos: usize, + depth: usize, +} + +impl<'a> Parser<'a> { + fn peek(&self) -> Option<&Tok> { + self.toks.get(self.pos) + } + + fn eat(&mut self, t: &Tok) -> bool { + if self.peek() == Some(t) { + self.pos += 1; + true + } else { + false + } + } + + fn parse(&mut self) -> Result { + if self.toks.is_empty() { + return Ok(Ast::Const(0.0)); + } + let e = self.parse_or()?; + if self.pos != self.toks.len() { + return Err(()); + } + Ok(e) + } + + fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Result) -> Result { + if self.depth >= 64 { + return Err(()); + } + self.depth += 1; + let r = f(self); + self.depth -= 1; + r + } + + fn parse_or(&mut self) -> Result { + let mut lhs = self.parse_and()?; + while self.eat(&Tok::Or) { + let rhs = self.parse_and()?; + lhs = Ast::Bin(BinOp::Or, Box::new(lhs), Box::new(rhs)); + } + Ok(lhs) + } + + fn parse_and(&mut self) -> Result { + let mut lhs = self.parse_cmp()?; + while self.eat(&Tok::And) { + let rhs = self.parse_cmp()?; + lhs = Ast::Bin(BinOp::And, Box::new(lhs), Box::new(rhs)); + } + Ok(lhs) + } + + fn parse_cmp(&mut self) -> Result { + let mut lhs = self.parse_add()?; + loop { + let op = match self.peek() { + Some(Tok::Lt) => BinOp::Lt, + Some(Tok::Le) => BinOp::Le, + Some(Tok::Gt) => BinOp::Gt, + Some(Tok::Ge) => BinOp::Ge, + Some(Tok::Eq) => BinOp::Eq, + Some(Tok::Ne) => BinOp::Ne, + _ => break, + }; + self.pos += 1; + let rhs = self.parse_add()?; + lhs = Ast::Bin(op, Box::new(lhs), Box::new(rhs)); + } + Ok(lhs) + } + + fn parse_add(&mut self) -> Result { + let mut lhs = self.parse_mul()?; + loop { + if self.eat(&Tok::Plus) { + let rhs = self.parse_mul()?; + lhs = Ast::Bin(BinOp::Add, Box::new(lhs), Box::new(rhs)); + } else if self.eat(&Tok::Minus) { + let rhs = self.parse_mul()?; + lhs = Ast::Bin(BinOp::Sub, Box::new(lhs), Box::new(rhs)); + } else { + break; + } + } + Ok(lhs) + } + + fn parse_mul(&mut self) -> Result { + let mut lhs = self.parse_pow()?; + loop { + if self.eat(&Tok::Star) { + let rhs = self.parse_pow()?; + lhs = Ast::Bin(BinOp::Mul, Box::new(lhs), Box::new(rhs)); + } else if self.eat(&Tok::Slash) { + let rhs = self.parse_pow()?; + lhs = Ast::Bin(BinOp::Div, Box::new(lhs), Box::new(rhs)); + } else if self.eat(&Tok::Percent) { + let rhs = self.parse_pow()?; + lhs = Ast::Bin(BinOp::Mod, Box::new(lhs), Box::new(rhs)); + } else { + break; + } + } + Ok(lhs) + } + + fn parse_pow(&mut self) -> Result { + let base = self.parse_unary()?; + if self.eat(&Tok::Caret) { + let exp = self.with_depth(Self::parse_pow)?; + Ok(Ast::Bin(BinOp::Pow, Box::new(base), Box::new(exp))) + } else { + Ok(base) + } + } + + fn parse_unary(&mut self) -> Result { + if self.eat(&Tok::Minus) { + let inner = self.with_depth(Self::parse_unary)?; + Ok(Ast::Neg(Box::new(inner))) + } else if self.eat(&Tok::Plus) { + self.with_depth(Self::parse_unary) + } else if self.eat(&Tok::Bang) { + let inner = self.with_depth(Self::parse_unary)?; + Ok(Ast::Not(Box::new(inner))) + } else { + self.parse_primary() + } + } + + fn parse_primary(&mut self) -> Result { + match self.peek().cloned() { + Some(Tok::LParen) => { + self.pos += 1; + let inner = self.with_depth(Self::parse_or)?; + if !self.eat(&Tok::RParen) { + return Err(()); + } + Ok(inner) + } + Some(Tok::Num(v)) => { + self.pos += 1; + Ok(Ast::Const(v)) + } + Some(Tok::Ident(name)) => { + self.pos += 1; + if self.eat(&Tok::LParen) { + let mut args = Vec::new(); + if self.peek() != Some(&Tok::RParen) { + loop { + args.push(self.with_depth(Self::parse_or)?); + if !self.eat(&Tok::Comma) { + break; + } + } + } + if !self.eat(&Tok::RParen) { + return Err(()); + } + Ok(Ast::Call(resolve_func(&name, args.len())?, args)) + } else { + Ok(Ast::Var(resolve_var(&name)?)) + } + } + _ => Err(()), + } + } +} + +fn resolve_var(name: &str) -> Result { + match name { + "px" => Ok(Var::Px), + "py" => Ok(Var::Py), + "pz" => Ok(Var::Pz), + "vx" => Ok(Var::Vx), + "vy" => Ok(Var::Vy), + "vz" => Ok(Var::Vz), + "rx" => Ok(Var::Rx), + "ry" => Ok(Var::Ry), + "rz" => Ok(Var::Rz), + "sx" => Ok(Var::Sx), + "sy" => Ok(Var::Sy), + "sz" => Ok(Var::Sz), + "r" => Ok(Var::R), + "g" => Ok(Var::G), + "b" => Ok(Var::B), + "a" => Ok(Var::A), + "size" => Ok(Var::Size), + "age" => Ok(Var::Age), + "lifespan" | "life" => Ok(Var::Lifespan), + "id" => Ok(Var::Id), + "mass" => Ok(Var::Mass), + "user" => Ok(Var::User), + "time" => Ok(Var::Time), + "pi" => Ok(Var::Pi), + "e" => Ok(Var::E), + "n1" => Ok(Var::Num(0)), + "n2" => Ok(Var::Num(1)), + "n3" => Ok(Var::Num(2)), + "n4" => Ok(Var::Num(3)), + "n5" => Ok(Var::Num(4)), + "n6" => Ok(Var::Num(5)), + "n7" => Ok(Var::Num(6)), + "n8" => Ok(Var::Num(7)), + "p1x" => Ok(Var::Pt(0, 0)), + "p1y" => Ok(Var::Pt(0, 1)), + "p1z" => Ok(Var::Pt(0, 2)), + "p2x" => Ok(Var::Pt(1, 0)), + "p2y" => Ok(Var::Pt(1, 1)), + "p2z" => Ok(Var::Pt(1, 2)), + "p3x" => Ok(Var::Pt(2, 0)), + "p3y" => Ok(Var::Pt(2, 1)), + "p3z" => Ok(Var::Pt(2, 2)), + "p4x" => Ok(Var::Pt(3, 0)), + "p4y" => Ok(Var::Pt(3, 1)), + "p4z" => Ok(Var::Pt(3, 2)), + "s1" => Ok(Var::Setup(0)), + "s2" => Ok(Var::Setup(1)), + "s3" => Ok(Var::Setup(2)), + "s4" => Ok(Var::Setup(3)), + "i1" => Ok(Var::Inter(0)), + "i2" => Ok(Var::Inter(1)), + "i3" => Ok(Var::Inter(2)), + "i4" => Ok(Var::Inter(3)), + "i5" => Ok(Var::Inter(4)), + "i6" => Ok(Var::Inter(5)), + "i7" => Ok(Var::Inter(6)), + "i8" => Ok(Var::Inter(7)), + _ => Err(()), + } +} + +fn resolve_func(name: &str, argc: usize) -> Result { + if let Some(rest) = name.strip_prefix("get") { + let bytes = rest.as_bytes(); + if (2..=3).contains(&bytes.len()) && argc == 2 { + let ch = match bytes[0] { + b'r' => Some(0), + b'g' => Some(1), + b'b' => Some(2), + b'a' => Some(3), + b'c' => Some(4), + _ => None, + }; + let edge = match bytes.get(2) { + None | Some(b'b') => Some(0), + Some(b'w') => Some(1), + Some(b'd') => Some(2), + _ => None, + }; + if let (Some(ch), Some(edge)) = (ch, edge) { + if bytes[1] == b'1' || bytes[1] == b'2' { + return Ok(Func::SampleImg(ch, edge)); + } + } + } + } + let f = match (name, argc) { + ("sin", 1) => Func::Sin, + ("cos", 1) => Func::Cos, + ("tan", 1) => Func::Tan, + ("asin", 1) => Func::Asin, + ("acos", 1) => Func::Acos, + ("atan", 1) => Func::Atan, + ("atan2", 2) => Func::Atan2, + ("sinr", 1) => Func::Sinr, + ("cosr", 1) => Func::Cosr, + ("tanr", 1) => Func::Tanr, + ("asinr", 1) => Func::Asinr, + ("acosr", 1) => Func::Acosr, + ("atanr", 1) => Func::Atanr, + ("atan2r", 2) => Func::Atan2r, + ("sinh", 1) => Func::Sinh, + ("cosh", 1) => Func::Cosh, + ("tanh", 1) => Func::Tanh, + ("deg", 1) => Func::Deg, + ("rad", 1) => Func::Rad, + ("abs", 1) => Func::Abs, + ("sqrt", 1) => Func::Sqrt, + ("pow", 2) => Func::Pow, + ("exp", 1) => Func::Exp, + ("log" | "ln", 1) => Func::Log, + ("log10", 1) => Func::Log10, + ("log2", 1) => Func::Log2, + ("floor" | "int", 1) => Func::Floor, + ("ceil", 1) => Func::Ceil, + ("round", 1) => Func::Round, + ("trunc", 1) => Func::Trunc, + ("fract", 1) => Func::Fract, + ("sign", 1) => Func::Sign, + ("min", n) if n >= 2 => Func::Min, + ("max", n) if n >= 2 => Func::Max, + ("clamp", 3) => Func::Clamp, + ("mod", 2) => Func::Mod, + ("if" | "iif", 3) => Func::If, + ("dist", 4) => Func::Dist, + ("hypot", 2) => Func::Hypot, + ("mix" | "lerp", 3) => Func::Mix, + ("step", 2) => Func::Step, + ("smoothstep", 3) => Func::Smoothstep, + ("rand", 2) => Func::Rand, + ("rands", 3) => Func::Rands, + ("noise", 1) => Func::Noise1, + ("noise2", 2) => Func::Noise2, + ("noise3", 3) => Func::Noise3, + _ => return Err(()), + }; + Ok(f) +} + +pub(super) fn compile_expr(src: &str) -> Option { + let trimmed = src.trim(); + if trimmed.is_empty() { + return None; + } + let toks = tokenize(trimmed).ok()?; + let mut p = Parser { toks: &toks, pos: 0, depth: 0 }; + p.parse().ok() +} + +pub(super) use super::custom_eval::{apply_custom, apply_custom_force}; diff --git a/crates/engine/src/particles/custom_eval.rs b/crates/engine/src/particles/custom_eval.rs new file mode 100644 index 0000000000000000000000000000000000000000..628340cfae1f5a0615ee46d8c23672d66b05055d --- /dev/null +++ b/crates/engine/src/particles/custom_eval.rs @@ -0,0 +1,467 @@ +//! Evaluator & per-particle executors for `pCustom` and `pCustomForce`. + +use std::collections::HashSet; + +use model::{Comp, ExprEngine, Node}; + +use super::custom::{Ast, BinOp, Func, Var, compile_expr}; +use super::forces::ModifierFilter; +use super::sim::value_noise_3d; +use super::{Particle, SplitMix64, SpriteImage, VELOCITY_SCALE}; + +struct EvalCtx<'a> { + p: &'a Particle, + time: f64, + seed: i64, + n: [f64; 8], + pt: [[f64; 3]; 4], + s: [f64; 4], + i: [f64; 8], + img: Option<&'a SpriteImage>, +} + +fn sample_sprite(img: Option<&SpriteImage>, x: f64, y: f64, ch: u8, edge: u8) -> f64 { + let Some(sp) = img else { + return 0.0; + }; + let w = sp.size[0] as isize; + let h = sp.size[1] as isize; + if w <= 0 || h <= 0 || sp.rgba.len() < (w as usize) * (h as usize) * 4 { + return 0.0; + } + // Fusion normalized image coords: (0,0) bottom-left, (1,1) top-right. + let mut u = x; + let mut v = 1.0 - y; + match edge { + 1 => { + u = u.rem_euclid(1.0); + v = v.rem_euclid(1.0); + } + 2 => { + u = u.clamp(0.0, 1.0); + v = v.clamp(0.0, 1.0); + } + _ => { + if !(0.0..=1.0).contains(&u) || !(0.0..=1.0).contains(&v) { + return 0.0; + } + } + } + let ix = ((u * w as f64).floor() as isize).clamp(0, w - 1) as usize; + let iy = ((v * h as f64).floor() as isize).clamp(0, h - 1) as usize; + let off = (iy * w as usize + ix) * 4; + let px = &sp.rgba[off..off + 4]; + match ch { + 0 => px[0] as f64 / 255.0, + 1 => px[1] as f64 / 255.0, + 2 => px[2] as f64 / 255.0, + 3 => px[3] as f64 / 255.0, + _ => (0.2126 * px[0] as f64 + 0.7152 * px[1] as f64 + 0.0722 * px[2] as f64) / 255.0, + } +} + +fn eval_ast(ast: &Ast, ctx: &EvalCtx<'_>) -> f64 { + let v = match ast { + Ast::Const(c) => *c, + Ast::Var(var) => match *var { + Var::Px => ctx.p.pos[0], + Var::Py => ctx.p.pos[1], + Var::Pz => ctx.p.pos[2], + Var::Vx => ctx.p.vel[0], + Var::Vy => ctx.p.vel[1], + Var::Vz => ctx.p.vel[2], + Var::Rx => ctx.p.rot_xy[0], + Var::Ry => ctx.p.rot_xy[1], + Var::Rz => ctx.p.rot_z, + Var::Sx => ctx.p.spin_xy[0], + Var::Sy => ctx.p.spin_xy[1], + Var::Sz => ctx.p.spin_z, + Var::R => ctx.p.color[0] as f64, + Var::G => ctx.p.color[1] as f64, + Var::B => ctx.p.color[2] as f64, + Var::A => ctx.p.color[3] as f64, + Var::Size => ctx.p.size, + Var::Age => ctx.p.age / ctx.p.lifespan.max(1.0), + Var::Lifespan => ctx.p.lifespan, + Var::Id => ctx.p.id as f64, + Var::Mass => ctx.p.mass, + Var::User => ctx.p.user, + Var::Time => ctx.time, + Var::Pi => std::f64::consts::PI, + Var::E => std::f64::consts::E, + Var::Num(idx) => ctx.n[idx as usize], + Var::Pt(idx, axis) => ctx.pt[idx as usize][axis as usize], + Var::Setup(idx) => ctx.s[idx as usize], + Var::Inter(idx) => ctx.i[idx as usize], + }, + Ast::Neg(x) => -eval_ast(x, ctx), + Ast::Not(x) => if eval_ast(x, ctx) == 0.0 { 1.0 } else { 0.0 }, + Ast::Bin(op, a, b) => { + let x = eval_ast(a, ctx); + let y = eval_ast(b, ctx); + match op { + BinOp::Add => x + y, + BinOp::Sub => x - y, + BinOp::Mul => x * y, + BinOp::Div => if y.abs() < 1e-12 { 0.0 } else { x / y }, + BinOp::Mod => if y.abs() < 1e-12 { 0.0 } else { x % y }, + BinOp::Pow => x.powf(y), + BinOp::Lt => if x < y { 1.0 } else { 0.0 }, + BinOp::Le => if x <= y { 1.0 } else { 0.0 }, + BinOp::Gt => if x > y { 1.0 } else { 0.0 }, + BinOp::Ge => if x >= y { 1.0 } else { 0.0 }, + BinOp::Eq => if (x - y).abs() < 1e-12 { 1.0 } else { 0.0 }, + BinOp::Ne => if (x - y).abs() >= 1e-12 { 1.0 } else { 0.0 }, + BinOp::And => if x != 0.0 && y != 0.0 { 1.0 } else { 0.0 }, + BinOp::Or => if x != 0.0 || y != 0.0 { 1.0 } else { 0.0 }, + } + } + Ast::Call(func, args) => match *func { + Func::Sin => eval_ast(&args[0], ctx).to_radians().sin(), + Func::Cos => eval_ast(&args[0], ctx).to_radians().cos(), + Func::Tan => eval_ast(&args[0], ctx).to_radians().tan(), + Func::Asin => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).asin().to_degrees(), + Func::Acos => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).acos().to_degrees(), + Func::Atan => eval_ast(&args[0], ctx).atan().to_degrees(), + Func::Atan2 => eval_ast(&args[0], ctx).atan2(eval_ast(&args[1], ctx)).to_degrees(), + Func::Sinr => eval_ast(&args[0], ctx).sin(), + Func::Cosr => eval_ast(&args[0], ctx).cos(), + Func::Tanr => eval_ast(&args[0], ctx).tan(), + Func::Asinr => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).asin(), + Func::Acosr => eval_ast(&args[0], ctx).clamp(-1.0, 1.0).acos(), + Func::Atanr => eval_ast(&args[0], ctx).atan(), + Func::Atan2r => eval_ast(&args[0], ctx).atan2(eval_ast(&args[1], ctx)), + Func::Sinh => eval_ast(&args[0], ctx).sinh(), + Func::Cosh => eval_ast(&args[0], ctx).cosh(), + Func::Tanh => eval_ast(&args[0], ctx).tanh(), + Func::Deg => eval_ast(&args[0], ctx).to_degrees(), + Func::Rad => eval_ast(&args[0], ctx).to_radians(), + Func::Abs => eval_ast(&args[0], ctx).abs(), + Func::Sqrt => eval_ast(&args[0], ctx).max(0.0).sqrt(), + Func::Pow => eval_ast(&args[0], ctx).powf(eval_ast(&args[1], ctx)), + Func::Exp => eval_ast(&args[0], ctx).exp(), + Func::Log => eval_ast(&args[0], ctx).max(1e-12).ln(), + Func::Log10 => eval_ast(&args[0], ctx).max(1e-12).log10(), + Func::Log2 => eval_ast(&args[0], ctx).max(1e-12).log2(), + Func::Floor => eval_ast(&args[0], ctx).floor(), + Func::Ceil => eval_ast(&args[0], ctx).ceil(), + Func::Round => eval_ast(&args[0], ctx).round(), + Func::Trunc => eval_ast(&args[0], ctx).trunc(), + Func::Fract => eval_ast(&args[0], ctx).fract(), + Func::Sign => { + let x = eval_ast(&args[0], ctx); + if x > 0.0 { 1.0 } else if x < 0.0 { -1.0 } else { 0.0 } + } + Func::Min => args.iter().map(|a| eval_ast(a, ctx)).fold(f64::INFINITY, f64::min), + Func::Max => args.iter().map(|a| eval_ast(a, ctx)).fold(f64::NEG_INFINITY, f64::max), + Func::Clamp => { + let x = eval_ast(&args[0], ctx); + let lo = eval_ast(&args[1], ctx); + let hi = eval_ast(&args[2], ctx); + if lo <= hi { x.clamp(lo, hi) } else { x.clamp(hi, lo) } + } + Func::Mod => { + let x = eval_ast(&args[0], ctx); + let y = eval_ast(&args[1], ctx); + if y.abs() < 1e-12 { 0.0 } else { x % y } + } + Func::If => { + if eval_ast(&args[0], ctx) != 0.0 { + eval_ast(&args[1], ctx) + } else { + eval_ast(&args[2], ctx) + } + } + Func::Dist => { + let x1 = eval_ast(&args[0], ctx); + let y1 = eval_ast(&args[1], ctx); + let x2 = eval_ast(&args[2], ctx); + let y2 = eval_ast(&args[3], ctx); + (x2 - x1).hypot(y2 - y1) + } + Func::Hypot => eval_ast(&args[0], ctx).hypot(eval_ast(&args[1], ctx)), + Func::Mix => { + let a = eval_ast(&args[0], ctx); + let b = eval_ast(&args[1], ctx); + let u = eval_ast(&args[2], ctx); + a + (b - a) * u + } + Func::Step => { + if eval_ast(&args[1], ctx) < eval_ast(&args[0], ctx) { 0.0 } else { 1.0 } + } + Func::Smoothstep => { + let e0 = eval_ast(&args[0], ctx); + let e1 = eval_ast(&args[1], ctx); + let x = eval_ast(&args[2], ctx); + let u = if (e1 - e0).abs() < 1e-12 { 0.0 } else { ((x - e0) / (e1 - e0)).clamp(0.0, 1.0) }; + u * u * (3.0 - 2.0 * u) + } + Func::Rand => { + let lo = eval_ast(&args[0], ctx); + let hi = eval_ast(&args[1], ctx); + let mut rng = SplitMix64::from_parts(ctx.seed ^ i64::from(ctx.p.id), ctx.time.round() as i64, "pCustomRand"); + rng.range(lo, hi) + } + Func::Rands => { + let lo = eval_ast(&args[0], ctx); + let hi = eval_ast(&args[1], ctx); + let s = eval_ast(&args[2], ctx).to_bits() as i64; + let mut rng = SplitMix64::from_parts(ctx.seed ^ s ^ i64::from(ctx.p.id), 0, "pCustomRands"); + rng.range(lo, hi) + } + Func::Noise1 => value_noise_3d(eval_ast(&args[0], ctx), 0.0, 0.0, ctx.seed as u64), + Func::Noise2 => value_noise_3d(eval_ast(&args[0], ctx), eval_ast(&args[1], ctx), 0.0, ctx.seed as u64), + Func::Noise3 => value_noise_3d( + eval_ast(&args[0], ctx), + eval_ast(&args[1], ctx), + eval_ast(&args[2], ctx), + ctx.seed as u64, + ), + Func::SampleImg(ch, edge) => { + let x = eval_ast(&args[0], ctx); + let y = eval_ast(&args[1], ctx); + sample_sprite(ctx.img, x, y, ch, edge) + } + }, + }; + if v.is_finite() { v } else { 0.0 } +} + +fn read_common_inputs(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> ([f64; 8], [[f64; 3]; 4], [Option; 4], [Option; 8]) { + let n = std::array::from_fn(|idx| { + let key = format!("NumberIn{}", idx + 1); + comp.eval_number(node, &key, t, 0.0, expr) + }); + let pt = std::array::from_fn(|idx| { + let i = idx + 1; + let pin_key = format!("PointIn{i}"); + let def_pt = if node.inputs.contains_key(&pin_key) { + comp.eval_point(node, &pin_key, t, [0.0, 0.0], expr) + } else { + [0.0, 0.0] + }; + [ + comp.eval_number(node, &format!("Position{i}.X"), t, def_pt[0], expr), + comp.eval_number(node, &format!("Position{i}.Y"), t, def_pt[1], expr), + comp.eval_number(node, &format!("Position{i}.Z"), t, 0.0, expr), + ] + }); + let setups = std::array::from_fn(|idx| { + let key = format!("Setup{}", idx + 1); + compile_expr(&comp.eval_text(node, &key, t, "", expr)) + }); + let inters = std::array::from_fn(|idx| { + let key = format!("Intermediate{}", idx + 1); + let alias = format!("Inter{}", idx + 1); + let txt = if node.inputs.contains_key(&key) { + comp.eval_text(node, &key, t, "", expr) + } else if node.inputs.contains_key(&alias) { + comp.eval_text(node, &alias, t, "", expr) + } else { + String::new() + }; + compile_expr(&txt) + }); + (n, pt, setups, inters) +} + +fn compile_channel_expr( + comp: &Comp, + node: &Node, + keys: &[&str], + identity_var: &str, + t: f64, + expr: &ExprEngine, +) -> Option { + for &k in keys { + if node.inputs.contains_key(k) { + let txt = comp.eval_text(node, k, t, identity_var, expr); + let trimmed = txt.trim(); + if trimmed.is_empty() || trimmed == identity_var { + return None; + } + return compile_expr(trimmed); + } + } + None +} + +/// Applies `pCustom` per-particle expression overrides to matching live particles. +pub(super) fn apply_custom( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + img: Option<&SpriteImage>, + t: f64, + expr: &ExprEngine, +) { + let px_ast = compile_channel_expr(comp, node, &["PositionXExpression"], "px", t, expr); + let py_ast = compile_channel_expr(comp, node, &["PositionYExpression"], "py", t, expr); + let pz_ast = compile_channel_expr(comp, node, &["PositionZExpression"], "pz", t, expr); + let vx_ast = compile_channel_expr(comp, node, &["VelocityXExpression"], "vx", t, expr); + let vy_ast = compile_channel_expr(comp, node, &["VelocityYExpression"], "vy", t, expr); + let vz_ast = compile_channel_expr(comp, node, &["VelocityZExpression"], "vz", t, expr); + let rx_ast = compile_channel_expr(comp, node, &["RotationXExpression"], "rx", t, expr); + let ry_ast = compile_channel_expr(comp, node, &["RotationYExpression"], "ry", t, expr); + let rz_ast = compile_channel_expr(comp, node, &["RotationZExpression"], "rz", t, expr); + let sx_ast = compile_channel_expr(comp, node, &["SpinXExpression"], "sx", t, expr); + let sy_ast = compile_channel_expr(comp, node, &["SpinYExpression"], "sy", t, expr); + let sz_ast = compile_channel_expr(comp, node, &["SpinZExpression"], "sz", t, expr); + let r_ast = compile_channel_expr(comp, node, &["RedExpression"], "r", t, expr); + let g_ast = compile_channel_expr(comp, node, &["GreenExpression"], "g", t, expr); + let b_ast = compile_channel_expr(comp, node, &["BlueExpression"], "b", t, expr); + let a_ast = compile_channel_expr(comp, node, &["AlphaExpression"], "a", t, expr); + let size_ast = compile_channel_expr(comp, node, &["SizeExpression"], "size", t, expr); + let life_ast = compile_channel_expr(comp, node, &["LifeSpanExpression", "LifespanExpression"], "lifespan", t, expr); + let mass_ast = compile_channel_expr(comp, node, &["MassExpression"], "mass", t, expr); + let user_ast = compile_channel_expr(comp, node, &["UserExpression"], "user", t, expr); + let kill_ast = compile_channel_expr(comp, node, &["KillExpressionKillIf10", "KillExpression"], "0", t, expr); + + if [ + &px_ast, &py_ast, &pz_ast, &vx_ast, &vy_ast, &vz_ast, &rx_ast, &ry_ast, &rz_ast, + &sx_ast, &sy_ast, &sz_ast, &r_ast, &g_ast, &b_ast, &a_ast, &size_ast, &life_ast, + &mass_ast, &user_ast, &kill_ast, + ] + .iter() + .all(|o| o.is_none()) + { + return; + } + + let (n, pt, setups, inters) = read_common_inputs(comp, node, t, expr); + let filter = ModifierFilter::from_node(comp, node, t, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + let mut ctx = EvalCtx { + p, + time: t, + seed, + n, + pt, + s: [0.0; 4], + i: [0.0; 8], + img, + }; + for idx in 0..4 { + if let Some(ref ast) = setups[idx] { + ctx.s[idx] = eval_ast(ast, &ctx); + } + } + for idx in 0..8 { + if let Some(ref ast) = inters[idx] { + ctx.i[idx] = eval_ast(ast, &ctx); + } + } + let new_px = px_ast.as_ref().map_or(p.pos[0], |e| eval_ast(e, &ctx)); + let new_py = py_ast.as_ref().map_or(p.pos[1], |e| eval_ast(e, &ctx)); + let new_pz = pz_ast.as_ref().map_or(p.pos[2], |e| eval_ast(e, &ctx)); + let new_vx = vx_ast.as_ref().map_or(p.vel[0], |e| eval_ast(e, &ctx)); + let new_vy = vy_ast.as_ref().map_or(p.vel[1], |e| eval_ast(e, &ctx)); + let new_vz = vz_ast.as_ref().map_or(p.vel[2], |e| eval_ast(e, &ctx)); + let new_rx = rx_ast.as_ref().map_or(p.rot_xy[0], |e| eval_ast(e, &ctx)); + let new_ry = ry_ast.as_ref().map_or(p.rot_xy[1], |e| eval_ast(e, &ctx)); + let new_rz = rz_ast.as_ref().map_or(p.rot_z, |e| eval_ast(e, &ctx)); + let new_sx = sx_ast.as_ref().map_or(p.spin_xy[0], |e| eval_ast(e, &ctx)); + let new_sy = sy_ast.as_ref().map_or(p.spin_xy[1], |e| eval_ast(e, &ctx)); + let new_sz = sz_ast.as_ref().map_or(p.spin_z, |e| eval_ast(e, &ctx)); + let new_r = r_ast.as_ref().map_or(p.color[0], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); + let new_g = g_ast.as_ref().map_or(p.color[1], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); + let new_b = b_ast.as_ref().map_or(p.color[2], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); + let new_a = a_ast.as_ref().map_or(p.color[3], |e| eval_ast(e, &ctx).clamp(0.0, 1.0) as f32); + let new_size = size_ast.as_ref().map_or(p.size, |e| eval_ast(e, &ctx).max(0.0)); + let new_life = life_ast.as_ref().map_or(p.lifespan, |e| eval_ast(e, &ctx).max(1.0)); + let new_mass = mass_ast.as_ref().map_or(p.mass, |e| eval_ast(e, &ctx)); + let new_user = user_ast.as_ref().map_or(p.user, |e| eval_ast(e, &ctx)); + let kill = kill_ast.as_ref().is_some_and(|e| eval_ast(e, &ctx) > 0.5); + + p.pos = [new_px, new_py, new_pz]; + p.vel = [new_vx, new_vy, new_vz]; + p.rot_xy = [new_rx, new_ry]; + p.rot_z = new_rz; + p.spin_xy = [new_sx, new_sy]; + p.spin_z = new_sz; + p.color = [new_r, new_g, new_b, new_a]; + p.size = new_size; + p.lifespan = new_life; + p.mass = new_mass; + p.user = new_user; + if kill { + p.alive = false; + } + } +} + +/// Applies `pCustomForce` per-particle acceleration/torque expressions each substep. +pub(super) fn apply_custom_force( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + img: Option<&SpriteImage>, + t: f64, + expr: &ExprEngine, +) { + let fx_ast = compile_channel_expr(comp, node, &["ForceXExpression"], "0", t, expr); + let fy_ast = compile_channel_expr(comp, node, &["ForceYExpression"], "0", t, expr); + let fz_ast = compile_channel_expr(comp, node, &["ForceZExpression"], "0", t, expr); + let tx_ast = compile_channel_expr(comp, node, &["TorqueXExpression"], "0", t, expr); + let ty_ast = compile_channel_expr(comp, node, &["TorqueYExpression"], "0", t, expr); + let tz_ast = compile_channel_expr(comp, node, &["TorqueZExpression"], "0", t, expr); + if [&fx_ast, &fy_ast, &fz_ast, &tx_ast, &ty_ast, &tz_ast] + .iter() + .all(|o| o.is_none()) + { + return; + } + + let (n, pt, setups, inters) = read_common_inputs(comp, node, t, expr); + let filter = ModifierFilter::from_node(comp, node, t, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + let force_scale = VELOCITY_SCALE * VELOCITY_SCALE; + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + let mut ctx = EvalCtx { + p, + time: t, + seed, + n, + pt, + s: [0.0; 4], + i: [0.0; 8], + img, + }; + for idx in 0..4 { + if let Some(ref ast) = setups[idx] { + ctx.s[idx] = eval_ast(ast, &ctx); + } + } + for idx in 0..8 { + if let Some(ref ast) = inters[idx] { + ctx.i[idx] = eval_ast(ast, &ctx); + } + } + let inv_m = if p.mass.abs() > 1e-6 { 1.0 / p.mass } else { 1.0 }; + let dfx = fx_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); + let dfy = fy_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); + let dfz = fz_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * force_scale * inv_m); + let dtx = tx_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); + let dty = ty_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); + let dtz = tz_ast.as_ref().map_or(0.0, |ast| eval_ast(ast, &ctx) * inv_m); + p.vel[0] += dfx; + p.vel[1] += dfy; + p.vel[2] += dfz; + p.spin_xy[0] += dtx; + p.spin_xy[1] += dty; + p.spin_z += dtz; + } +} diff --git a/crates/engine/src/particles/extra_forces.rs b/crates/engine/src/particles/extra_forces.rs new file mode 100644 index 0000000000000000000000000000000000000000..91e87dd473d6b550d2093c23cee84b29a18b2085 --- /dev/null +++ b/crates/engine/src/particles/extra_forces.rs @@ -0,0 +1,595 @@ +//! Additional Fusion particle operators: +//! - `pAvoid`: repulsive obstacle-avoidance steering force around a region surface +//! - `pFollow`: spring-damper target follow and boids leader-follower steering +//! - `pTangentForce`: orbital tangential cross-product force (`S x (p - center)`) +//! - `pImageEmitter`: emits particles sampled from an input image's RGBA pixels + +use std::collections::{HashMap, HashSet}; + +use model::{Comp, ExprEngine, Node, NodeId}; + +use super::forces::{ModifierFilter, eval_first_num, read_sets_mask}; +use super::sim::RegionSpec; +use super::{ + MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, SpriteImage, VELOCITY_SCALE, +}; + +/// `pAvoid`: repels particles smoothly away from the obstacle `Region` within `Distance`. +pub(super) fn apply_avoid( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let strength = comp.eval_number(node, "Strength", t, 0.1, expr); + let dist_limit = comp.eval_number(node, "Distance", t, 0.1, expr).max(0.0); + if strength.abs() < 1e-12 || dist_limit <= 1e-9 { + return; + } + + let filter = ModifierFilter::from_node_ignore_region(comp, node, t, expr); + // Fusion's pAvoid defaults Region to LineRgn ((0,0,0)..(0,0,0)). + let obstacle = RegionSpec::from_node_with_default(comp, node, t, expr, "LineRgn"); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + let force_mag = strength * VELOCITY_SCALE * VELOCITY_SCALE; + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + let Some((dist, dir)) = avoid_surface_vector(&obstacle, p.pos, p.id) else { + continue; + }; + if dist >= dist_limit { + continue; + } + let falloff = if dist <= 0.0 { + 1.0 + } else { + 1.0 - dist / dist_limit + }; + let push = force_mag * falloff; + p.vel[0] += dir[0] * push; + p.vel[1] += dir[1] * push; + p.vel[2] += dir[2] * push; + } +} + +fn avoid_surface_vector(region: &RegionSpec, p: [f64; 3], id: u32) -> Option<(f64, [f64; 3])> { + let normalize_or_fallback = |dx: f64, dy: f64, dz: f64| -> (f64, [f64; 3]) { + let len = (dx * dx + dy * dy + dz * dz).sqrt(); + if len > 1e-9 { + (len, [dx / len, dy / len, dz / len]) + } else { + let ang = (id as f64) * 2.399963229728653; + (0.0, [ang.cos(), ang.sin(), 0.0]) + } + }; + + match *region { + RegionSpec::Point { center } => { + Some(normalize_or_fallback(p[0] - center[0], p[1] - center[1], p[2] - center[2])) + } + RegionSpec::Sphere { center, radius } => { + let (d, dir) = + normalize_or_fallback(p[0] - center[0], p[1] - center[1], p[2] - center[2]); + Some(((d - radius).max(0.0), dir)) + } + RegionSpec::Line { start, end } => { + let abx = end[0] - start[0]; + let aby = end[1] - start[1]; + let abz = end[2] - start[2]; + let ab2 = abx * abx + aby * aby + abz * abz; + let s = if ab2 > 1e-12 { + (((p[0] - start[0]) * abx + (p[1] - start[1]) * aby + (p[2] - start[2]) * abz) + / ab2) + .clamp(0.0, 1.0) + } else { + 0.0 + }; + let qx = start[0] + abx * s; + let qy = start[1] + aby * s; + let qz = start[2] + abz * s; + Some(normalize_or_fallback(p[0] - qx, p[1] - qy, p[2] - qz)) + } + RegionSpec::Rect { + center, + width, + height, + } => { + let hw = width * 0.5; + let hh = height * 0.5; + let rx = p[0] - center[0]; + let ry = p[1] - center[1]; + let dx = (rx.abs() - hw).max(0.0) * rx.signum(); + let dy = (ry.abs() - hh).max(0.0) * ry.signum(); + let dz = p[2] - center[2]; + if dx.abs() > 1e-9 || dy.abs() > 1e-9 || dz.abs() > 1e-9 { + Some(normalize_or_fallback(dx, dy, dz)) + } else { + let px = hw - rx.abs(); + let py = hh - ry.abs(); + if px <= py { + Some((0.0, [if rx >= 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0])) + } else { + Some((0.0, [0.0, if ry >= 0.0 { 1.0 } else { -1.0 }, 0.0])) + } + } + } + RegionSpec::Cube { + center, + width, + height, + depth, + } => { + let hw = width * 0.5; + let hh = height * 0.5; + let hd = depth * 0.5; + let rx = p[0] - center[0]; + let ry = p[1] - center[1]; + let rz = p[2] - center[2]; + let dx = (rx.abs() - hw).max(0.0) * rx.signum(); + let dy = (ry.abs() - hh).max(0.0) * ry.signum(); + let dz = (rz.abs() - hd).max(0.0) * rz.signum(); + if dx.abs() > 1e-9 || dy.abs() > 1e-9 || dz.abs() > 1e-9 { + Some(normalize_or_fallback(dx, dy, dz)) + } else { + let px = hw - rx.abs(); + let py = hh - ry.abs(); + let pz = hd - rz.abs(); + if px <= py && px <= pz { + Some((0.0, [if rx >= 0.0 { 1.0 } else { -1.0 }, 0.0, 0.0])) + } else if py <= pz { + Some((0.0, [0.0, if ry >= 0.0 { 1.0 } else { -1.0 }, 0.0])) + } else { + Some((0.0, [0.0, 0.0, if rz >= 0.0 { 1.0 } else { -1.0 }])) + } + } + } + RegionSpec::All => None, + } +} + +/// `pFollow`: supports Fusion's spring-damper target follow (`Position` + `Spring` + `Damping`) +/// and leader/neighbor follower steering (`FollowSet` / `AffectSet` / `Strength` / `Distance`). +pub(super) fn apply_follow( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let has_neighbor_inputs = node.inputs.contains_key("FollowSet") + || node.inputs.contains_key("AffectSet") + || (node.inputs.contains_key("Strength") && !node.inputs.contains_key("Spring")); + + if has_neighbor_inputs { + apply_follow_neighbors(particles, comp, node, scope, t, expr); + } else { + apply_follow_spring(particles, comp, node, scope, t, expr); + } +} + +fn apply_follow_spring( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let spring = comp.eval_number(node, "Spring", t, 1.0, expr); + let damping = comp.eval_number(node, "Damping", t, 0.1, expr).max(0.0); + if spring.abs() < 1e-12 && damping.abs() < 1e-12 { + return; + } + + let pos_pt = if node.inputs.contains_key("Position") { + comp.eval_point(node, "Position", t, [0.0, 0.0], expr) + } else { + [0.0, 0.0] + }; + let tx = eval_first_num(comp, node, &["Position.X", "Center.X"], t, pos_pt[0], expr); + let ty = eval_first_num(comp, node, &["Position.Y", "Center.Y"], t, pos_pt[1], expr); + let tz = eval_first_num(comp, node, &["Position.Z", "Center.Z"], t, 0.0, expr); + + let filter = ModifierFilter::from_node(comp, node, t, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + let k = spring * VELOCITY_SCALE * VELOCITY_SCALE; + let damp_factor = (1.0 - (damping * 0.1).clamp(0.0, 0.99)).clamp(0.01, 1.0); + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + p.vel[0] = p.vel[0] * damp_factor + (tx - p.pos[0]) * k; + p.vel[1] = p.vel[1] * damp_factor + (ty - p.pos[1]) * k; + p.vel[2] = p.vel[2] * damp_factor + (tz - p.pos[2]) * k; + } +} + +fn parse_set_arg(comp: &Comp, node: &Node, key: &str, t: f64, expr: &ExprEngine) -> Option { + if let Some(s) = node.static_str(key) { + if let Some(rest) = s.strip_prefix("Set") { + if let Ok(idx) = rest.parse::() { + if (1..=32).contains(&idx) { + return Some(1u32 << (idx - 1)); + } + } + } + } + if node.inputs.contains_key(key) { + let idx = comp.eval_number(node, key, t, 1.0, expr).round() as i32; + if (1..=32).contains(&idx) { + return Some(1u32 << (idx - 1)); + } + } + None +} + +fn apply_follow_neighbors( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let strength = comp.eval_number(node, "Strength", t, 0.5, expr); + if strength.abs() < 1e-12 || particles.is_empty() { + return; + } + let distance = comp.eval_number(node, "Distance", t, 0.25, expr).max(0.0); + let follow_mask = parse_set_arg(comp, node, "FollowSet", t, expr); + let affect_mask = parse_set_arg(comp, node, "AffectSet", t, expr); + + let filter = ModifierFilter::from_node(comp, node, t, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + + let leaders: Vec<([f64; 3], [f64; 3])> = particles + .iter() + .filter(|p| { + p.alive + && scope.contains(&p.emitter_hash) + && follow_mask.is_none_or(|m| (p.sets & m) != 0) + }) + .map(|p| (p.pos, p.vel)) + .collect(); + if leaders.is_empty() { + return; + } + + let dist_sq = if distance > 1e-9 { + distance * distance + } else { + f64::INFINITY + }; + let accel = strength * VELOCITY_SCALE * VELOCITY_SCALE; + + let mut deltas = vec![[0.0_f64; 3]; particles.len()]; + for (idx, p) in particles.iter().enumerate() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + if let Some(m) = affect_mask { + if (p.sets & m) == 0 { + continue; + } + } + let mut sum_pos = [0.0_f64; 3]; + let mut sum_vel = [0.0_f64; 3]; + let mut count = 0usize; + for &(lp, lv) in &leaders { + let dx = lp[0] - p.pos[0]; + let dy = lp[1] - p.pos[1]; + let dz = lp[2] - p.pos[2]; + let d2 = dx * dx + dy * dy + dz * dz; + if d2 <= 1e-12 || d2 > dist_sq { + continue; + } + sum_pos[0] += dx; + sum_pos[1] += dy; + sum_pos[2] += dz; + sum_vel[0] += lv[0] - p.vel[0]; + sum_vel[1] += lv[1] - p.vel[1]; + sum_vel[2] += lv[2] - p.vel[2]; + count += 1; + } + if count > 0 { + let inv = 1.0 / count as f64; + deltas[idx] = [ + sum_pos[0] * inv * accel + sum_vel[0] * inv * (accel * 2.0).min(0.25), + sum_pos[1] * inv * accel + sum_vel[1] * inv * (accel * 2.0).min(0.25), + sum_pos[2] * inv * accel + sum_vel[2] * inv * (accel * 2.0).min(0.25), + ]; + } + } + + for (p, dv) in particles.iter_mut().zip(deltas) { + p.vel[0] += dv[0]; + p.vel[1] += dv[1]; + p.vel[2] += dv[2]; + } +} + +/// `pTangentForce`: orbital tangential force around `Translate` / `Center` via `S x (p - center)`. +pub(super) fn apply_tangent_force( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let center_pt = if node.inputs.contains_key("Center") { + comp.eval_point(node, "Center", t, [0.0, 0.0], expr) + } else { + [0.0, 0.0] + }; + let cx = eval_first_num(comp, node, &["Translate.X", "Center.X"], t, center_pt[0], expr); + let cy = eval_first_num(comp, node, &["Translate.Y", "Center.Y"], t, center_pt[1], expr); + let cz = eval_first_num(comp, node, &["Translate.Z", "Center.Z"], t, 0.0, expr); + + let (sx, sy, sz) = if node.inputs.contains_key("XStrength") + || node.inputs.contains_key("YStrength") + || node.inputs.contains_key("ZStrength") + { + ( + comp.eval_number(node, "XStrength", t, 0.0, expr), + comp.eval_number(node, "YStrength", t, 0.0, expr), + comp.eval_number(node, "ZStrength", t, 0.1, expr), + ) + } else if node.inputs.contains_key("Strength") || node.inputs.contains_key("Axis") { + let s = comp.eval_number(node, "Strength", t, 0.1, expr); + let axis_idx = match node.static_str("Axis") { + Some("X" | "x") => 0, + Some("Y" | "y") => 1, + Some("Z" | "z") => 2, + _ => comp.eval_number(node, "Axis", t, 2.0, expr).round() as i32, + }; + match axis_idx { + 0 => (s, 0.0, 0.0), + 1 => (0.0, s, 0.0), + _ => (0.0, 0.0, s), + } + } else { + (0.0, 0.0, 0.1) + }; + + if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 { + return; + } + + let filter = ModifierFilter::from_node(comp, node, t, expr); + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name); + let scale = POINT_FORCE_SCALE.max(VELOCITY_SCALE * VELOCITY_SCALE * 0.2); + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + let rx = p.pos[0] - cx; + let ry = p.pos[1] - cy; + let rz = p.pos[2] - cz; + // Cross product S x r gives orbital tangent acceleration around center. + let fx = (sy * rz - sz * ry) * scale; + let fy = (sz * rx - sx * rz) * scale; + let fz = (sx * ry - sy * rx) * scale; + p.vel[0] += fx; + p.vel[1] += fy; + p.vel[2] += fz; + } +} + +/// `pImageEmitter`: emits particles distributed across the sampled RGBA pixels of its `Input` image. +#[allow(clippy::too_many_arguments)] +pub(super) fn emit_image_particles( + state: &mut SimState, + comp: &Comp, + node: &Node, + emitter_id: NodeId, + emitter_hash: u64, + sprites: &HashMap, + frame: i64, + sim_start: i64, + t: f64, + expr: &ExprEngine, +) { + let every_frame = comp.eval_number(node, "CreateParticlesEveryFrame", t, 0.0, expr) > 0.5; + if !every_frame && frame != sim_start { + return; + } + let Some(sprite) = sprites.get(&emitter_id) else { + return; + }; + let sw = sprite.size[0] as usize; + let sh = sprite.size[1] as usize; + if sw == 0 || sh == 0 || sprite.rgba.len() < sw.saturating_mul(sh).saturating_mul(4) { + return; + } + + let x_density = comp.eval_number(node, "XDensity", t, 1.0, expr).clamp(0.0, 8.0); + let y_density = comp.eval_number(node, "YDensity", t, 1.0, expr).clamp(0.0, 8.0); + if x_density <= 1e-6 || y_density <= 1e-6 { + return; + } + let alpha_thresh = comp.eval_number(node, "AlphaThreshold", t, 0.0, expr).clamp(0.0, 1.0); + let use_style_color = matches!(node.static_str("ColorMode"), Some("UseStyle" | "Style")) + || (node.inputs.contains_key("ColorMode") + && comp.eval_number(node, "ColorMode", t, 0.0, expr).round() as i32 == 1); + + let remaining = MAX_PARTICLES.saturating_sub(state.particles.len()); + if remaining == 0 { + return; + } + + let mut nx = ((sw as f64) * x_density).round().max(1.0) as usize; + let mut ny = ((sh as f64) * y_density).round().max(1.0) as usize; + if nx.saturating_mul(ny) > remaining { + let scale = (remaining as f64 / (nx * ny) as f64).sqrt(); + nx = ((nx as f64) * scale).floor().max(1.0) as usize; + ny = (remaining / nx).max(1); + } + + let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64; + let mut rng = SplitMix64::from_parts(seed, frame, &node.name); + + let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0); + let lifespan_var = comp + .eval_number(node, "LifespanVariance", t, 0.0, expr) + .max(0.0); + let pos_var = comp + .eval_number(node, "PositionVariance", t, 0.0, expr) + .max(0.0); + let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr); + let vel_var = comp + .eval_number(node, "VelocityVariance", t, 0.0, expr) + .max(0.0); + let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr); + let angle_var = comp + .eval_number(node, "AngleVariance", t, 0.0, expr) + .max(0.0); + let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr); + let angle_z_var = comp + .eval_number(node, "AngleZVariance", t, 0.0, expr) + .max(0.0); + + let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr); + let rot_z_var = comp + .eval_number(node, "RotationZVariance", t, 0.0, expr) + .max(0.0); + let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr); + let spin_z_var = comp + .eval_number(node, "SpinZVariance", t, 0.0, expr) + .max(0.0); + + let style_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr) as f32; + let style_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr) as f32; + let style_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr) as f32; + let style_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr) as f32; + let size_base = comp + .eval_number(node, "ParticleStyle.Size", t, 0.1, expr) + .max(0.0); + let size_var = comp + .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) + .max(0.0); + + let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr); + let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr); + let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr); + let sx = comp.eval_number(node, "Transform3DOp.Scale.X", t, 1.0, expr); + let sy = if comp.eval_number(node, "Transform3DOp.ScaleLock", t, 1.0, expr) > 0.5 + && !node.inputs.contains_key("Transform3DOp.Scale.Y") + { + sx + } else { + comp.eval_number(node, "Transform3DOp.Scale.Y", t, 1.0, expr) + }; + let rz_deg = comp.eval_number(node, "Transform3DOp.Rotate.Z", t, 0.0, expr); + let (sin_rz, cos_rz) = rz_deg.to_radians().sin_cos(); + + let region = if node.static_str("Region").is_some() { + RegionSpec::from_node(comp, node, t, expr) + } else { + RegionSpec::All + }; + let emitter_sets = read_sets_mask(comp, node, t, expr).unwrap_or(1u32); + let aspect = sw as f64 / (sh as f64).max(1.0); + + for iy in 0..ny { + let v = (iy as f64 + 0.5) / ny as f64; + let py = ((v * sh as f64).floor() as usize).min(sh - 1); + for ix in 0..nx { + if state.particles.len() >= MAX_PARTICLES { + return; + } + let u = (ix as f64 + 0.5) / nx as f64; + let px = ((u * sw as f64).floor() as usize).min(sw - 1); + let off = (py * sw + px) * 4; + let pa = sprite.rgba[off + 3] as f64 / 255.0; + if pa <= alpha_thresh.max(1e-6) { + continue; + } + + let lx = (u - 0.5) * sx; + let ly = ((0.5 - v) / aspect) * sy; + let mut pos = [ + tx + lx * cos_rz - ly * sin_rz, + ty + lx * sin_rz + ly * cos_rz, + tz, + ]; + if !region.contains(pos) { + continue; + } + if pos_var > 0.0 { + pos[0] += rng.signed() * pos_var; + pos[1] += rng.signed() * pos_var; + pos[2] += rng.signed() * pos_var; + } + + let color = if use_style_color { + [ + style_r.clamp(0.0, 1.0), + style_g.clamp(0.0, 1.0), + style_b.clamp(0.0, 1.0), + style_a.clamp(0.0, 1.0), + ] + } else { + // Sprite readback is premultiplied RGBA8; unpremultiply RGB so particle rasterizer + // can apply its own FadeIn/FadeOut and ColorOverLife cleanly. + let inv_a = 1.0 / pa as f32; + let pr = ((sprite.rgba[off] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); + let pg = ((sprite.rgba[off + 1] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); + let pb = ((sprite.rgba[off + 2] as f32 / 255.0) * inv_a).clamp(0.0, 1.0); + [ + (pr * style_r).clamp(0.0, 1.0), + (pg * style_g).clamp(0.0, 1.0), + (pb * style_b).clamp(0.0, 1.0), + (pa as f32 * style_a).clamp(0.0, 1.0), + ] + }; + + let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE; + let ang = (angle_base + rng.signed() * angle_var).to_radians(); + let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians(); + let cos_z = ang_z.cos(); + let vel = [ + speed * ang.cos() * cos_z, + speed * ang.sin() * cos_z, + speed * ang_z.sin(), + ]; + + let pid = state.next_id; + state.next_id = state.next_id.wrapping_add(1).max(1); + + state.particles.push(Particle { + emitter_hash, + id: pid, + sets: emitter_sets, + style_override: None, + ngon_sides_override: 0, + bitmap_owner_hash: 0, + pos, + vel, + rot_xy: [0.0, 0.0], + rot_z: rot_z_base + rng.signed() * rot_z_var, + spin_xy: [0.0, 0.0], + spin_z: spin_z_base + rng.signed() * spin_z_var, + age: 0.0, + lifespan: (lifespan_base + rng.signed() * lifespan_var).max(1.0), + size: (size_base + rng.signed() * size_var).max(0.0), + mass: 1.0, + user: 0.0, + color, + alive: true, + }); + } + } +} diff --git a/crates/engine/src/particles/extra_tests.rs b/crates/engine/src/particles/extra_tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..d2d9dd221a74df3aba2d49b64e253327b934e239 --- /dev/null +++ b/crates/engine/src/particles/extra_tests.rs @@ -0,0 +1,342 @@ +//! Unit & end-to-end GPU tests for `pAvoid`, `pCustom`, `pCustomForce`, `pFollow`, +//! `pImageEmitter`, and `pTangentForce`. + +use super::plan::build_particle_plan; +use super::sim::step_simulation; +use super::*; + +#[test] +fn test_p_avoid_repels_from_obstacle_region() { + let comp_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + EN = BezierSpline { + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [1] = { 0, Flags = { Linear = true } }, + }, + }, + ENear = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.05, }, + }, + }, + EFar = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.40, }, + }, + }, + M = pMerge { + Inputs = { + Input1 = Input { SourceOp = "ENear", Source = "Output", }, + Input2 = Input { SourceOp = "EFar", Source = "Output", }, + }, + }, + Av = pAvoid { + Inputs = { + Input = Input { SourceOp = "M", Source = "Output", }, + Region = Input { Value = FuID { "SphereRgn" }, }, + ["SphereRgn.Translate.X"] = Input { Value = 0.0, }, + ["SphereRgn.Size"] = Input { Value = 0.02, }, + Distance = Input { Value = 0.15, }, + Strength = Input { Value = 2.0, }, + }, + }, + R = pRender { Inputs = { Input = Input { SourceOp = "Av", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let render_id = comp.node_by_name["R"]; + let plan = build_particle_plan(&comp, render_id); + let expr = ExprEngine::new(); + let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); + let mut state = SimState::default(); + for f in 0..=4 { + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); + } + assert_eq!(state.particles.len(), 2); + let near = &state.particles[0]; + let far = &state.particles[1]; + assert!(near.vel[0] > 0.01 && near.pos[0] > 0.07, "near particle should be repelled +X: {:?}", near); + assert!(far.vel[0].abs() < 1e-9 && (far.pos[0] - 0.40).abs() < 1e-9, "far particle outside Distance must remain unaffected: {:?}", far); +} + +#[test] +fn test_p_tangent_force_orbital_velocity() { + let comp_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + EN = BezierSpline { + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [1] = { 0, Flags = { Linear = true } }, + }, + }, + E = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.25, }, + ["Point.Translate.Y"] = Input { Value = 0.0, }, + }, + }, + TF = pTangentForce { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + ["Translate.X"] = Input { Value = 0.0, }, + ["Translate.Y"] = Input { Value = 0.0, }, + ZStrength = Input { Value = 1.0, }, + }, + }, + R = pRender { Inputs = { Input = Input { SourceOp = "TF", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let render_id = comp.node_by_name["R"]; + let plan = build_particle_plan(&comp, render_id); + let expr = ExprEngine::new(); + let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); + let mut state = SimState::default(); + for f in 0..=1 { + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); + } + let p1 = state.particles[0]; + assert!(p1.vel[1] > 1e-4, "ZStrength > 0 at (+X,0) should produce +Y orbital velocity, got {:?}", p1.vel); + assert!(p1.vel[0].abs() < 1e-9, "radial X force should be 0 on first tangent impulse, got {}", p1.vel[0]); + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, 2, 0, &expr); + let p2 = state.particles[0]; + assert!(p2.vel[0] < 0.0, "second step after moving +Y should deflect velocity inward toward -X, got {:?}", p2.vel); +} + +#[test] +fn test_p_follow_spring_target_and_leader_sets() { + // 1. Native Fusion spring-damper follow toward Position. + let spring_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + EN = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, + E = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = -0.3, }, + }, + }, + Fol = pFollow { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + ["Position.X"] = Input { Value = 0.3, }, + ["Position.Y"] = Input { Value = 0.2, }, + Spring = Input { Value = 2.0, }, + Damping = Input { Value = 0.2, }, + }, + }, + R = pRender { Inputs = { Input = Input { SourceOp = "Fol", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(spring_src).unwrap(); + let plan = build_particle_plan(&comp, comp.node_by_name["R"]); + let expr = ExprEngine::new(); + let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); + let mut state = SimState::default(); + for f in 0..=4 { + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); + } + let p = state.particles[0]; + assert!(p.vel[0] > 0.01 && p.vel[1] > 0.005, "spring target must pull particle toward (0.3, 0.2), got {:?}", p.vel); + + // 2. Boids leader-follower mode using FollowSet / AffectSet / Strength / Distance. + let boids_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + EN = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, + Leader = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Set1 = Input { Value = 1, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.2, }, + Velocity = Input { Value = 0.0, }, + }, + }, + Follower = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Set2 = Input { Value = 1, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = -0.1, }, + Velocity = Input { Value = 0.0, }, + }, + }, + M = pMerge { + Inputs = { + Input1 = Input { SourceOp = "Leader", Source = "Output", }, + Input2 = Input { SourceOp = "Follower", Source = "Output", }, + }, + }, + Fol = pFollow { + Inputs = { + Input = Input { SourceOp = "M", Source = "Output", }, + FollowSet = Input { Value = FuID { "Set1" }, }, + AffectSet = Input { Value = FuID { "Set2" }, }, + Strength = Input { Value = 3.0, }, + Distance = Input { Value = 0.5, }, + }, + }, + R = pRender { Inputs = { Input = Input { SourceOp = "Fol", Source = "Output", }, }, }, + }, + }"#; + let bcomp = Comp::from_fusion_str(boids_src).unwrap(); + let bplan = build_particle_plan(&bcomp, bcomp.node_by_name["R"]); + let mut bstate = SimState::default(); + for f in 0..=4 { + step_simulation(&mut bstate, &bcomp, &bplan, &empty_fields, &no_sprites, f, 0, &expr); + } + let leader = bstate.particles.iter().find(|x| (x.sets & 1) != 0).unwrap(); + let follower = bstate.particles.iter().find(|x| (x.sets & 2) != 0).unwrap(); + assert!(leader.vel[0].abs() < 1e-9, "leader in Set1 not in AffectSet must stay still"); + assert!(follower.vel[0] > 0.01 && follower.pos[0] > -0.1, "follower in Set2 must steer toward leader in Set1"); +} + +#[test] +fn test_p_custom_and_p_custom_force_expressions_and_gpu() { + let comp_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + EN = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } }, [1] = { 0, Flags = { Linear = true } } } }, + E = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 0.4, }, + }, + }, + Cust = pCustom { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + NumberIn1 = Input { Value = 0.25, }, + ["Position1.X"] = Input { Value = -0.1, }, + ["Position1.Y"] = Input { Value = 0.05, }, + Setup1 = Input { Value = "sin(90)", }, + Intermediate1 = Input { Value = "s1 * n1", }, + PositionXExpression = Input { Value = "if(id > 1, i1, p1x)", }, + PositionYExpression = Input { Value = "p1y", }, + RedExpression = Input { Value = "clamp(n1 * 4, 0, 1)", }, + GreenExpression = Input { Value = "0", }, + BlueExpression = Input { Value = "0", }, + KillExpressionKillIf10 = Input { Value = "if(id == 1 && age >= 0.04, 1, 0)", }, + }, + }, + CF = pCustomForce { + Inputs = { + Input = Input { SourceOp = "Cust", Source = "Output", }, + ForceYExpression = Input { Value = "2.0", }, + TorqueZExpression = Input { Value = "1.5", }, + }, + }, + R = pRender { Inputs = { Width = Input { Value = 64, }, Height = Input { Value = 64, }, Input = Input { SourceOp = "CF", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let render_id = comp.node_by_name["R"]; + let plan = build_particle_plan(&comp, render_id); + let expr = ExprEngine::new(); + let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); + let mut state = SimState::default(); + for f in 0..=4 { + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); + } + // Particle id=1 was killed at age>=2; particle id=2 survived at x=0.25 with +Y acceleration from pCustomForce. + assert_eq!(state.particles.len(), 1, "id=1 must be killed leaving id=2, got {:?}", state.particles); + let p = state.particles[0]; + assert_eq!(p.id, 2); + assert!((p.pos[0] - 0.25).abs() < 1e-6); + assert!(p.vel[1] > 0.02, "ForceYExpression='2.0' must accelerate +Y: {}", p.vel[1]); + assert!(p.rot_z > 1.0, "TorqueZExpression='1.5' must integrate spin_z into rot_z: {}", p.rot_z); + assert!(p.color[0] > 0.99 && p.color[1] < 0.01); + + let Ok(mut eng) = crate::Engine::new_headless() else { return }; + let (tex, stats) = eng.evaluate(&comp, render_id, 4.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba(&tex).unwrap(); + let nonzero = px.chunks_exact(4).filter(|c| c[3] > 0).count(); + assert!(nonzero > 5); +} + +#[test] +fn test_p_image_emitter_samples_rgba_and_alpha_threshold_and_gpu() { + // 32x32 image whose left half is opaque red and right half is fully transparent, + // driving pImageEmitter -> pRender on GPU. + let comp_src = r#"Composition { + GlobalRange = { 0, 5 }, + RenderRange = { 0, 5 }, + Tools = ordered() { + MaskLeft = RectangleMask { + Inputs = { + MaskWidth = Input { Value = 32, }, MaskHeight = Input { Value = 32, }, + Center = Input { Value = { 0.25, 0.5 }, }, + Width = Input { Value = 0.5, }, Height = Input { Value = 1.0, }, + }, + }, + RedHalf = Background { + Inputs = { + Width = Input { Value = 32, }, Height = Input { Value = 32, }, + TopLeftRed = Input { Value = 1, }, TopLeftGreen = Input { Value = 0, }, TopLeftBlue = Input { Value = 0, }, TopLeftAlpha = Input { Value = 1, }, + EffectMask = Input { SourceOp = "MaskLeft", Source = "Mask", }, + }, + }, + IE = pImageEmitter { + Inputs = { + Input = Input { SourceOp = "RedHalf", Source = "Output", }, + XDensity = Input { Value = 0.5, }, + YDensity = Input { Value = 0.5, }, + AlphaThreshold = Input { Value = 0.5, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 0.25, }, + }, + }, + R = pRender { + Inputs = { + Width = Input { Value = 64, }, Height = Input { Value = 64, }, + Input = Input { SourceOp = "IE", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let render_id = comp.node_by_name["R"]; + let Ok(mut eng) = crate::Engine::new_headless() else { return }; + let (tex, stats) = eng.evaluate(&comp, render_id, 2.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba(&tex).unwrap(); + let px_ref = px.as_slice(); + + let left_red: u64 = (0..64) + .flat_map(|y| (0..28).map(move |x| px_ref[(y * 64 + x) * 4] as u64)) + .sum(); + let right_alpha: u64 = (0..64) + .flat_map(|y| (42..64).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) + .sum(); + assert!(left_red > 1000, "pImageEmitter must emit bright red particles over left half (left_red={left_red})"); + assert_eq!(right_alpha, 0, "right transparent half above AlphaThreshold must emit no particles (right_alpha={right_alpha})"); +} diff --git a/crates/engine/src/particles/forces.rs b/crates/engine/src/particles/forces.rs index c35c76fd40a8e29f945b646e03742f8349cd8fae..8592eeb21fa7af14df691910a3b7a8bc96c9f314 100644 --- a/crates/engine/src/particles/forces.rs +++ b/crates/engine/src/particles/forces.rs @@ -195,7 +195,7 @@ pub(super) fn parse_particle_style(s: &str) -> Option { } } -fn eval_first_num( +pub(super) fn eval_first_num( comp: &Comp, node: &Node, keys: &[&str], @@ -237,7 +237,7 @@ pub(super) fn read_sets_mask(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine any_key.then_some(mask) } -struct ModifierFilter { +pub(super) struct ModifierFilter { region: RegionSpec, invert_region: bool, probability: f64, @@ -248,8 +248,21 @@ struct ModifierFilter { } impl ModifierFilter { - fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { - let region = if node.static_str("Region").is_some() { + pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { + Self::build(comp, node, t, expr, false) + } + + pub(super) fn from_node_ignore_region( + comp: &Comp, + node: &Node, + t: f64, + expr: &ExprEngine, + ) -> Self { + Self::build(comp, node, t, expr, true) + } + + fn build(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine, ignore_region: bool) -> Self { + let region = if !ignore_region && node.static_str("Region").is_some() { RegionSpec::from_node(comp, node, t, expr) } else { RegionSpec::All @@ -276,7 +289,7 @@ impl ModifierFilter { } #[inline] - fn matches(&self, p: &Particle, scope: &HashSet, rng: &mut SplitMix64) -> bool { + pub(super) fn matches(&self, p: &Particle, scope: &HashSet, rng: &mut SplitMix64) -> bool { if !p.alive || !scope.contains(&p.emitter_hash) { return false; } @@ -305,19 +318,38 @@ impl ModifierFilter { #[allow(clippy::too_many_arguments)] pub(super) fn apply_extended_modifier( particles: &mut Vec, + next_id: &mut u32, comp: &Comp, node: &Node, mod_id: NodeId, scope: &HashSet, emitter_nodes: &HashMap, gradient_fields: &HashMap, + sprites: &HashMap, t: f64, expr: &ExprEngine, ) { match node.kind.as_str() { "pVortex" => apply_vortex(particles, comp, node, scope, t, expr), "pFlock" => apply_flock(particles, comp, node, scope, t, expr), - "pSpawn" => apply_spawn(particles, comp, node, scope, emitter_nodes, t, expr), + "pAvoid" => super::extra_forces::apply_avoid(particles, comp, node, scope, t, expr), + "pFollow" => super::extra_forces::apply_follow(particles, comp, node, scope, t, expr), + "pTangentForce" => { + super::extra_forces::apply_tangent_force(particles, comp, node, scope, t, expr) + } + "pCustom" => { + super::custom::apply_custom(particles, comp, node, scope, sprites.get(&mod_id), t, expr) + } + "pCustomForce" => super::custom::apply_custom_force( + particles, + comp, + node, + scope, + sprites.get(&mod_id), + t, + expr, + ), + "pSpawn" => apply_spawn(particles, next_id, comp, node, scope, emitter_nodes, t, expr), "pChangeStyle" => apply_change_style(particles, comp, node, scope, t, expr), "pGradientForce" => { if let Some(field) = gradient_fields.get(&mod_id) { @@ -521,8 +553,10 @@ fn apply_flock( } /// `pSpawn`: spawns child particles from living parent particles, respecting `MAX_PARTICLES`. +#[allow(clippy::too_many_arguments)] fn apply_spawn( particles: &mut Vec, + next_id: &mut u32, comp: &Comp, node: &Node, scope: &HashSet, @@ -655,8 +689,11 @@ fn apply_spawn( if has_b { col_b } else { parent.color[2] }, if has_a { col_a } else { parent.color[3] }, ]; + let pid = *next_id; + *next_id = (*next_id).wrapping_add(1).max(1); spawned.push(Particle { emitter_hash: spawn_hash, + id: pid, sets: child_sets.unwrap_or(parent.sets), style_override: child_style, ngon_sides_override: if ngon_sides >= 3 { @@ -667,11 +704,15 @@ fn apply_spawn( bitmap_owner_hash: child_bitmap_owner, pos, vel, + rot_xy: [0.0, 0.0], rot_z: rot_z_base + rng.signed() * rot_z_var, + spin_xy: [0.0, 0.0], spin_z: spin_z_base + rng.signed() * spin_z_var, age: 0.0, lifespan, size, + mass: parent.mass, + user: parent.user, color, alive: true, }); diff --git a/crates/engine/src/particles/plan.rs b/crates/engine/src/particles/plan.rs index f0f9d499a0591d32256ca65a89a96497c97845fd..15a827f986a44d8f5f0753c85650e61d1f97eceb 100644 --- a/crates/engine/src/particles/plan.rs +++ b/crates/engine/src/particles/plan.rs @@ -95,6 +95,21 @@ fn collect_bitmap_sources_dfs( out.push((node_id, src_id)); } } + } else if node.kind == "pImageEmitter" { + if let Some(src_name) = node.connected_node("Input") { + if let Some(&src_id) = comp.node_by_name.get(src_name) { + out.push((node_id, src_id)); + } + } + } else if matches!(node.kind.as_str(), "pCustom" | "pCustomForce") { + for port in ["Image1", "Image", "Bitmap", "BitmapInput"] { + if let Some(src_name) = node.connected_node(port) { + if let Some(&src_id) = comp.node_by_name.get(src_name) { + out.push((node_id, src_id)); + break; + } + } + } } else if node.kind == "pGradientForce" { for port in ["Image", "Bitmap", "BitmapInput", "GradientImage"] { if let Some(src_name) = node.connected_node(port) { @@ -106,8 +121,10 @@ fn collect_bitmap_sources_dfs( } } - for up_id in particle_stream_inputs(comp, node) { - collect_bitmap_sources_dfs(comp, up_id, visited, out); + if node.kind != "pImageEmitter" { + for up_id in particle_stream_inputs(comp, node) { + collect_bitmap_sources_dfs(comp, up_id, visited, out); + } } } @@ -181,7 +198,7 @@ fn build_plan_dfs( scope.extend(up_set); } - if node.kind == "pEmitter" { + if matches!(node.kind.as_str(), "pEmitter" | "pImageEmitter") { if !node.bypassed { let emitter_hash = stable_name_hash(&node.name); emitters.push((node_id, emitter_hash)); @@ -207,6 +224,11 @@ fn build_plan_dfs( | "pBounce" | "pVortex" | "pFlock" + | "pAvoid" + | "pFollow" + | "pTangentForce" + | "pCustom" + | "pCustomForce" | "pChangeStyle" | "pGradientForce" ) diff --git a/crates/engine/src/particles/sim.rs b/crates/engine/src/particles/sim.rs index 6d65dfd1d0f836e3d1e63add3d636ceeb828678b..27ae349b622a9d6f5d6d1fcc275753d6d3fb2c96 100644 --- a/crates/engine/src/particles/sim.rs +++ b/crates/engine/src/particles/sim.rs @@ -5,17 +5,20 @@ use model::{Comp, ExprEngine, Node, NodeId}; use super::forces::{GradientField, apply_extended_modifier, read_sets_mask}; use super::plan::ParticlePlan; use super::{ - MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE, - VELOCITY_SCALE, + MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, SpriteImage, + TURBULENCE_SCALE, VELOCITY_SCALE, }; /// Advances the particle simulation by a single integer frame `frame`. +#[allow(clippy::too_many_arguments)] pub(super) fn step_simulation( state: &mut SimState, comp: &Comp, plan: &ParticlePlan, gradient_fields: &HashMap, + sprites: &HashMap, frame: i64, + sim_start: i64, expr: &ExprEngine, ) { let t = frame as f64; @@ -27,15 +30,26 @@ pub(super) fn step_simulation( continue; }; match node.kind.as_str() { - "pVortex" | "pFlock" | "pSpawn" | "pChangeStyle" | "pGradientForce" => { + "pVortex" + | "pFlock" + | "pAvoid" + | "pFollow" + | "pTangentForce" + | "pCustom" + | "pCustomForce" + | "pSpawn" + | "pChangeStyle" + | "pGradientForce" => { apply_extended_modifier( &mut state.particles, + &mut state.next_id, comp, node, *mod_id, scope, &plan.emitter_nodes, gradient_fields, + sprites, t, expr, ); @@ -51,6 +65,8 @@ pub(super) fn step_simulation( p.pos[0] += p.vel[0]; p.pos[1] += p.vel[1]; p.pos[2] += p.vel[2]; + p.rot_xy[0] += p.spin_xy[0]; + p.rot_xy[1] += p.spin_xy[1]; p.rot_z += p.spin_z; p.age += 1.0; if p.age >= p.lifespan { @@ -69,7 +85,22 @@ pub(super) fn step_simulation( let Some(node) = comp.nodes.get(emitter_id.0) else { continue; }; - emit_particles(state, comp, node, emitter_hash, frame, t, expr); + if node.kind == "pImageEmitter" { + super::extra_forces::emit_image_particles( + state, + comp, + node, + emitter_id, + emitter_hash, + sprites, + frame, + sim_start, + t, + expr, + ); + } else { + emit_particles(state, comp, node, emitter_hash, frame, t, expr); + } } // A newborn is damped by friction and then integrated once on its birth frame; other forces @@ -86,6 +117,8 @@ pub(super) fn step_simulation( for axis in 0..3 { p.pos[axis] += p.vel[axis]; } + p.rot_xy[0] += p.spin_xy[0]; + p.rot_xy[1] += p.spin_xy[1]; p.rot_z += p.spin_z; } } @@ -235,19 +268,26 @@ fn emit_particles( ] }; + let pid = state.next_id; + state.next_id = state.next_id.wrapping_add(1).max(1); state.particles.push(Particle { emitter_hash, + id: pid, sets: emitter_sets, style_override: None, ngon_sides_override: 0, bitmap_owner_hash: 0, pos, vel, + rot_xy: [0.0, 0.0], rot_z, + spin_xy: [0.0, 0.0], spin_z, age: 0.0, lifespan, size, + mass: 1.0, + user: 0.0, color, alive: true, }); @@ -283,7 +323,17 @@ pub(super) enum RegionSpec { impl RegionSpec { pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { - let region_name = node.static_str("Region").unwrap_or("SphereRgn"); + Self::from_node_with_default(comp, node, t, expr, "SphereRgn") + } + + pub(super) fn from_node_with_default( + comp: &Comp, + node: &Node, + t: f64, + expr: &ExprEngine, + default_region: &str, + ) -> Self { + let region_name = node.static_str("Region").unwrap_or(default_region); match region_name { "RectRgn" => Self::Rect { center: [ @@ -904,7 +954,7 @@ fn apply_modifier( } /// Smooth deterministic 3D value noise in `[-1.0, 1.0]`. -fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { +pub(super) fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 { let xi = x.floor() as i64; let yi = y.floor() as i64; let zi = z.floor() as i64; diff --git a/crates/engine/src/particles/tests.rs b/crates/engine/src/particles/tests.rs index 92f10002c3f5e9137f6ca2b6c64191b6d971b05e..0a1cd69c6545c27e664a101929e2ac1f6c02bb4e 100644 --- a/crates/engine/src/particles/tests.rs +++ b/crates/engine/src/particles/tests.rs @@ -264,8 +264,9 @@ Composition { // Step until the first emitted particle (born at f=0 at y=0.2, vy≈-0.0866, vx=0.05) // crosses the floor at y=0.0 around frame 3. let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); for f in 0..=4 { - step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); } let first = state.particles.first().expect("particle emitted"); let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); @@ -677,12 +678,13 @@ fn test_p_vortex_swirl_and_spiral_angle() { let expr = ExprEngine::new(); let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); // Angle = 0: pure CCW tangential swirl -> particle at (+0.2, 0) gains +Y velocity. let comp_tan = Comp::from_fusion_str(&make_comp(0.0)).unwrap(); let plan_tan = build_particle_plan(&comp_tan, comp_tan.node_by_name["R"]); let mut state_tan = SimState::default(); for f in 0..=4 { - step_simulation(&mut state_tan, &comp_tan, &plan_tan, &empty_fields, f, &expr); + step_simulation(&mut state_tan, &comp_tan, &plan_tan, &empty_fields, &no_sprites, f, 0, &expr); } let p_tan = state_tan.particles[0]; assert!(p_tan.vel[1] > 0.01, "tangential vortex must swirl +Y at (+X,0), got {:?}", p_tan.vel); @@ -692,7 +694,7 @@ fn test_p_vortex_swirl_and_spiral_angle() { let plan_in = build_particle_plan(&comp_in, comp_in.node_by_name["R"]); let mut state_in = SimState::default(); for f in 0..=5 { - step_simulation(&mut state_in, &comp_in, &plan_in, &empty_fields, f, &expr); + step_simulation(&mut state_in, &comp_in, &plan_in, &empty_fields, &no_sprites, f, 0, &expr); } let r_in = state_in.particles[0].pos[0].hypot(state_in.particles[0].pos[1]); assert!(r_in < 0.19, "positive Angle vortex should spiral inward, got r={r_in}"); @@ -702,7 +704,7 @@ fn test_p_vortex_swirl_and_spiral_angle() { let plan_out = build_particle_plan(&comp_out, comp_out.node_by_name["R"]); let mut state_out = SimState::default(); for f in 0..=5 { - step_simulation(&mut state_out, &comp_out, &plan_out, &empty_fields, f, &expr); + step_simulation(&mut state_out, &comp_out, &plan_out, &empty_fields, &no_sprites, f, 0, &expr); } let r_out = state_out.particles[0].pos[0].hypot(state_out.particles[0].pos[1]); assert!(r_out > 0.21, "negative Angle vortex should spiral outward, got r={r_out}"); @@ -773,11 +775,12 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { let expr = ExprEngine::new(); let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); // Cohesion + Alignment: particles at x=-0.08 and x=+0.08 pull together and share +Y velocity. let plan_coh = build_particle_plan(&comp, comp.node_by_name["RCoh"]); let mut state_coh = SimState::default(); for f in 0..=4 { - step_simulation(&mut state_coh, &comp, &plan_coh, &empty_fields, f, &expr); + step_simulation(&mut state_coh, &comp, &plan_coh, &empty_fields, &no_sprites, f, 0, &expr); } let dx_coh = (state_coh.particles[1].pos[0] - state_coh.particles[0].pos[0]).abs(); assert!(dx_coh < 0.155, "cohesion should pull particles closer than 0.16, got {dx_coh}"); @@ -787,7 +790,7 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { let plan_sep = build_particle_plan(&comp, comp.node_by_name["RSep"]); let mut state_sep = SimState::default(); for f in 0..=4 { - step_simulation(&mut state_sep, &comp, &plan_sep, &empty_fields, f, &expr); + step_simulation(&mut state_sep, &comp, &plan_sep, &empty_fields, &no_sprites, f, 0, &expr); } let dx_sep = (state_sep.particles[1].pos[0] - state_sep.particles[0].pos[0]).abs(); assert!(dx_sep > 0.165, "separation should push particles farther than 0.16, got {dx_sep}"); @@ -817,7 +820,7 @@ fn test_p_flock_cohesion_separation_alignment_and_perf() { let mut heavy_state = SimState::default(); let t0 = Instant::now(); for f in 0..=2 { - step_simulation(&mut heavy_state, &heavy_comp, &heavy_plan, &empty_fields, f, &expr); + step_simulation(&mut heavy_state, &heavy_comp, &heavy_plan, &empty_fields, &no_sprites, f, 0, &expr); } assert!(heavy_state.particles.len() >= 2000); assert!( @@ -881,8 +884,9 @@ fn test_p_spawn_children_velocity_transfer_and_cap() { // Frame 0: 2 parents emitted. Frame 1: each parent spawns 3 children => 2 + 6 = 8. // Frame 2: only the 2 original parents spawn (NOT the 6 children!) => 2 + 6 + 6 = 14. + let no_sprites = HashMap::new(); for f in 0..=2 { - step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); } assert_eq!(state.particles.len(), 14, "expected 2 parents + 12 non-recursive children"); @@ -972,9 +976,10 @@ fn test_p_change_style_color_size_style_and_region() { let plan = build_particle_plan(&comp, render_id); let expr = ExprEngine::new(); let empty_fields = HashMap::new(); + let no_sprites = HashMap::new(); let mut state = SimState::default(); for f in 0..=2 { - step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); + step_simulation(&mut state, &comp, &plan, &empty_fields, &no_sprites, f, 0, &expr); } let p_in = state.particles.iter().find(|p| p.pos[0] < 0.0).unwrap(); let p_out = state.particles.iter().find(|p| p.pos[0] > 0.0).unwrap(); @@ -1077,7 +1082,7 @@ fn test_p_gradient_force_luma_gradient_and_gpu_eval() { let expr = ExprEngine::new(); let mut state = SimState::default(); for f in 0..=4 { - step_simulation(&mut state, &comp, &plan, &fields, f, &expr); + step_simulation(&mut state, &comp, &plan, &fields, &sprites, f, 0, &expr); } let p = state.particles[0]; assert!(p.vel[0] > 0.02, "left-to-right bright ramp must push particle +X, got {:?}", p.vel); diff --git a/crates/engine/src/text_engine.rs b/crates/engine/src/text_engine.rs index be43559a667df78b58deae7d6daca9e53cf3bc7a..e34d1ff0b0ae19a3b2395749892bdf149092d2bd 100644 --- a/crates/engine/src/text_engine.rs +++ b/crates/engine/src/text_engine.rs @@ -987,6 +987,155 @@ fn layout_glyphs(dims: [u32; 2], params: &RichTextPlusParams<'_>) -> Option<(Vec Some((out, total_chars)) } +/// Parameters for extracting vector `zeno::Command` contours for `sText` in Y-up shape space. +pub struct TextShapeParams<'a> { + pub text: &'a str, + pub font_family: &'a str, + pub font_style: &'a str, + pub size_norm: f32, + pub tracking: f32, + pub line_spacing: f32, + pub h_lcr: f32, + pub v_tcb: f32, + pub shear_x: f32, + pub write_on_start: f32, + pub write_on_end: f32, + pub char_size_x: f32, + pub char_size_y: f32, +} + +struct ShapePathBuilder { + commands: Vec, + scale_x: f32, + scale_y: f32, + origin: [f32; 2], + lean: f32, +} + +impl ShapePathBuilder { + fn point(&self, x: f32, y: f32) -> Vector { + let px = x * self.scale_x; + let py = y * self.scale_y; + Vector::new(self.origin[0] + px + py * self.lean, self.origin[1] + py) + } +} + +impl OutlineBuilder for ShapePathBuilder { + fn move_to(&mut self, x: f32, y: f32) { + let p = self.point(x, y); + self.commands.push(Command::MoveTo(p)); + } + fn line_to(&mut self, x: f32, y: f32) { + let p = self.point(x, y); + self.commands.push(Command::LineTo(p)); + } + fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) { + let (c, p) = (self.point(x1, y1), self.point(x, y)); + self.commands.push(Command::QuadTo(c, p)); + } + fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) { + let (c1, c2, p) = (self.point(x1, y1), self.point(x2, y2), self.point(x, y)); + self.commands.push(Command::CurveTo(c1, c2, p)); + } + fn close(&mut self) { + self.commands.push(Command::Close); + } +} + +/// Extracts Y-up shape-space vector `zeno::Command` contours for `sText` using `rustybuzz` + `ttf-parser`. +pub fn layout_text_shape_commands(params: &TextShapeParams<'_>) -> Vec { + let total_chars = params.text.chars().count(); + if total_chars == 0 || !params.size_norm.is_finite() || params.size_norm <= 1e-4 { + return Vec::new(); + } + let c_start = (params.write_on_start.clamp(0.0, 1.0) * total_chars as f32).floor() as usize; + let c_end = (params.write_on_end.clamp(0.0, 1.0) * total_chars as f32).ceil() as usize; + if c_start >= c_end || c_start >= total_chars { + return Vec::new(); + } + let Some(font) = Font::find(params.font_family, params.font_style) else { + return Vec::new(); + }; + let face = font.face(); + let upem = face.units_per_em() as f32; + if upem <= 0.0 { + return Vec::new(); + } + + // Use a large reference scale (1000.0) for `shape_line` so integer glyph advance/kerning + // stays exact, then rescale back to normalized shape units (width = 1.0). + let ref_w = 1000.0_f32; + let (font_px, asc, desc) = size_metrics(&face, params.size_norm, ref_w); + let top_anchor = (font_px - desc).max(0.0) / ref_w; + let asc = asc / ref_w; + let desc = desc / ref_w; + let font_em = font_px / ref_w; + let extra_track = (params.tracking - 1.0) * params.size_norm; + + struct ShapeLine { + glyphs: Vec<(GlyphId, f32, f32)>, + width: f32, + } + let mut lines: Vec = Vec::new(); + let mut char_cursor = 0usize; + for raw_line in params.text.split('\n') { + let raw_char_len = raw_line.chars().count(); + let line_str = raw_line.strip_suffix('\r').unwrap_or(raw_line); + let mut glyphs = Vec::new(); + let width = if line_str.is_empty() { + 0.0 + } else { + let shaped = shape_line(&face, line_str, font_px, extra_track * ref_w); + for g in &shaped.glyphs { + let idx = char_cursor + g.char_index; + if idx < c_start || idx >= c_end { + continue; + } + glyphs.push((g.id, g.x / ref_w * params.char_size_x, g.y / ref_w * params.char_size_y)); + } + shaped.width / ref_w * params.char_size_x + }; + lines.push(ShapeLine { glyphs, width }); + char_cursor += raw_char_len + 1; + } + + let h_frac = params.h_lcr.clamp(-1.0, 1.0) * 0.5 + 0.5; + let v_frac = params.v_tcb.clamp(-1.0, 1.0) * 0.5 + 0.5; + let ls = params.line_spacing.max(0.05); + let line_step = (desc + asc) * ls; + let mut baselines = Vec::with_capacity(lines.len()); + let mut y_acc = 0.0_f32; + for i in 0..lines.len() { + baselines.push(y_acc); + if i + 1 < lines.len() { + y_acc += line_step; + } + } + let block_h = y_acc + top_anchor; + let baseline_0 = v_frac * block_h - top_anchor; + + let mut commands = Vec::new(); + let scale_x = (font_em / upem) * params.char_size_x; + let scale_y = (font_em / upem) * params.char_size_y; + let lean = font.lean - params.shear_x; + for (li, line) in lines.into_iter().enumerate() { + let start_x = -line.width * h_frac; + let base_y = baseline_0 - baselines[li]; + for (gid, gx, gy) in line.glyphs { + let mut builder = ShapePathBuilder { + commands: Vec::new(), + scale_x, + scale_y, + origin: [start_x + gx, base_y + gy], + lean, + }; + face.outline_glyph(gid, &mut builder); + commands.extend(builder.commands); + } + } + commands +} + const GLYPH_BASELINE_ANCHOR: f32 = 256.0; const GLYPH_BASELINE_ANCHOR_I32: i32 = 256; const MAX_GLYPH_CACHE_ENTRIES: usize = 4096; -- 2.54.1