diff --git a/crates/engine/src/eval/mod.rs b/crates/engine/src/eval/mod.rs index a1800d029d06a38eb2ab9f65986c7caded4ee9ca..b79c45cacf93afbc239ddf94f8843f23093b3d88 100644 --- a/crates/engine/src/eval/mod.rs +++ b/crates/engine/src/eval/mod.rs @@ -986,9 +986,14 @@ impl Engine { | "sRectangle" | "sEllipse" | "sStar" + | "sPolygon" | "sGrid" | "sMerge" | "sTransform" + | "sDuplicate" + | "sJitter" + | "sExpand" + | "sOffset" | "sBoolean" | "sOutline" => self.dummy.clone(), "EllipseMask" => self.eval_mask_shape(comp, node, time, frame_i, comp_dims, 0, enc, visiting, stats), @@ -1015,7 +1020,12 @@ impl Engine { | "pFriction" | "pKill" | "pMerge" - | "pBounce" => self.dummy.clone(), + | "pBounce" + | "pVortex" + | "pFlock" + | "pSpawn" + | "pChangeStyle" + | "pGradientForce" => self.dummy.clone(), "Custom" if node.connected_node("Image1").and_then(|s| comp.find_node(s)).is_none() => self.dummy.clone(), "Custom" => self.eval_custom(comp, node, time, frame_i, comp_dims, enc, visiting, stats), "SurfaceTracker" => self.eval_surface_tracker(comp, node, time, frame_i, enc, visiting, stats), diff --git a/crates/engine/src/eval/shapes.rs b/crates/engine/src/eval/shapes.rs index 67ded4d44942349014788f1d031d046b374a1d78..0fa26f0c56fdc716fc636813a2c950e575a01e67 100644 --- a/crates/engine/src/eval/shapes.rs +++ b/crates/engine/src/eval/shapes.rs @@ -1,8 +1,20 @@ -//! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sGrid`, -//! `sMerge`, `sTransform`, `sBoolean`, `sOutline`). +//! 2D Vector Shape Pipeline (`sRender`, `sNGon`, `sRectangle`, `sEllipse`, `sStar`, `sPolygon`, +//! `sGrid`, `sMerge`, `sTransform`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, `sBoolean`, `sOutline`). + +mod collect; +mod geometry; +mod raster; +#[cfg(test)] +mod tests; use super::*; +use collect::collect_shape_tree; +use raster::rasterize_shape_tree_rgba8; + +/// Safety cap on total collected leaf primitives so nested `sDuplicate`/`sGrid` cannot blow up memory. +const MAX_SHAPE_PRIMITIVES: usize = 4096; + #[derive(Clone, Copy, Debug)] struct Affine2D { // [a, b, c, d, tx, ty] => x' = a*x + b*y + tx, y' = c*x + d*y + ty @@ -63,12 +75,13 @@ impl Affine2D { } } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Debug)] enum ShapePrimKind { NGon { sides: u32, width: f32, height: f32 }, Rectangle { width: f32, height: f32, corner_radius: f32 }, Ellipse { width: f32, height: f32 }, Star { points: u32, depth: f32, width: f32, height: f32, corner_radius: f32 }, + Polygon { points: Vec, closed: bool }, } #[derive(Clone, Copy, Debug)] @@ -89,6 +102,67 @@ struct OutlineStyle { write_len: f32, } +#[derive(Clone, Copy, Debug)] +enum PathModifier { + Expand { + amount: f32, + join_style: u8, + miter_limit: f32, + }, + Jitter { + x_amount: f32, + y_amount: f32, + seed: i64, + smoothness: f32, + per_shape: bool, + }, + Offset { + offset_x: f32, + offset_y: f32, + contour_offset: f32, + position: f32, + join_style: u8, + miter_limit: f32, + }, +} + +impl PathModifier { + fn hash_into(self, h: &mut DefaultHasher) { + match self { + PathModifier::Expand { amount, join_style, miter_limit } => { + 0u8.hash(h); + amount.to_bits().hash(h); + join_style.hash(h); + miter_limit.to_bits().hash(h); + } + PathModifier::Jitter { x_amount, y_amount, seed, smoothness, per_shape } => { + 1u8.hash(h); + x_amount.to_bits().hash(h); + y_amount.to_bits().hash(h); + seed.hash(h); + smoothness.to_bits().hash(h); + per_shape.hash(h); + } + PathModifier::Offset { + offset_x, + offset_y, + contour_offset, + position, + join_style, + miter_limit, + } => { + 2u8.hash(h); + offset_x.to_bits().hash(h); + offset_y.to_bits().hash(h); + contour_offset.to_bits().hash(h); + position.to_bits().hash(h); + join_style.hash(h); + miter_limit.to_bits().hash(h); + } + } + } +} + #[derive(Clone, Debug)] enum ShapeTree { Primitive { @@ -112,6 +186,11 @@ enum ShapeTree { a: Box, b: Box, }, + Modify { + op: PathModifier, + post_xform: Affine2D, + child: Box, + }, } impl ShapeTree { @@ -130,7 +209,7 @@ impl ShapeTree { write_len, } => { 0u8.hash(h); - match *kind { + match kind { ShapePrimKind::NGon { sides, width, height } => { 1u8.hash(h); sides.hash(h); @@ -156,6 +235,20 @@ impl ShapeTree { height.to_bits().hash(h); corner_radius.to_bits().hash(h); } + ShapePrimKind::Polygon { points, closed } => { + 5u8.hash(h); + closed.hash(h); + points.len().hash(h); + for pt in points { + pt.x.to_bits().hash(h); + pt.y.to_bits().hash(h); + pt.lx.to_bits().hash(h); + pt.ly.to_bits().hash(h); + pt.rx.to_bits().hash(h); + pt.ry.to_bits().hash(h); + pt.linear.hash(h); + } + } } xform.hash_into(h); for c in color { @@ -187,757 +280,14 @@ impl ShapeTree { a.hash_into(h); b.hash_into(h); } - } - } -} - -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 -} - -/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. -fn parse_bool_op(node: &Node) -> Option { - if !node.inputs.contains_key("Operation") { - return Some(ShapeBoolOp::Intersect); - } - match node.static_str("Operation")? { - "Union" => Some(ShapeBoolOp::Union), - "Intersection" => Some(ShapeBoolOp::Intersect), - "Subtract" => Some(ShapeBoolOp::Subtract), - "Xor" => Some(ShapeBoolOp::Xor), - _ => None, - } -} - -#[allow(clippy::too_many_arguments)] -fn collect_shape_tree( - comp: &Comp, - node_id: NodeId, - time: f64, - expr: &ExprEngine, - parent_xform: Affine2D, - outline_override: Option, - depth: usize, -) -> Option { - if depth > 32 { - return None; - } - let node = comp.node(node_id); - if node.bypassed { - return node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) - }); - } - - match node.kind.as_str() { - "sNGon" | "sRectangle" | "sEllipse" | "sStar" => { - let tx = eval_first_num(comp, node, &["Translate.X", "XOffset"], time, 0.0, expr) as f32; - let ty = eval_first_num(comp, node, &["Translate.Y", "YOffset"], time, 0.0, expr) as f32; - let angle = eval_first_num(comp, node, &["Angle", "Rotate", "ZRotation"], time, 0.0, expr) as f32; - let local = 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, 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; - - 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 } - } - _ => { - 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, - }) - } - "sTransform" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - let ox = eval_first_num(comp, node, &["XOffset", "Translate.X"], time, 0.0, expr) as f32; - let oy = eval_first_num(comp, node, &["YOffset", "Translate.Y"], time, 0.0, expr) as f32; - let px = eval_first_num(comp, node, &["XPivot", "Pivot.X"], time, 0.0, expr) as f32; - let py = eval_first_num(comp, node, &["YPivot", "Pivot.Y"], time, 0.0, expr) as f32; - 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 rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; - - let local = Affine2D::translate(ox + px, oy + py) - .mul(Affine2D::rotate_deg(rot)) - .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) - } - "sMerge" => { - let mut ports: Vec<(u32, &str)> = node - .inputs - .keys() - .filter_map(|k| { - let rest = k.strip_prefix("Input")?; - let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; - Some((idx, k.as_str())) - }) - .collect(); - 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( - comp, - src_id, - time, - expr, - parent_xform, - outline_override, - depth + 1, - ) { - children.push(tree); - } - } - } - if children.is_empty() { - None - } else { - Some(ShapeTree::Group(children)) - } - } - "sGrid" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - 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; - let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; - let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y)); - for iy in 0..cells_y { - let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; - for ix in 0..cells_x { - 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( - comp, - src_id, - time, - expr, - cell_xf, - outline_override, - depth + 1, - ) { - children.push(tree); - } - } - } - if children.is_empty() { - None - } else { - Some(ShapeTree::Group(children)) - } - } - "sOutline" => { - let src_id = node - .connected_node("Input") - .or_else(|| node.connected_node("Input1")) - .and_then(|s| comp.find_node(s))?; - let thickness = eval_first_num(comp, node, &["Thickness", "BorderWidth"], time, 0.01, expr) as f32; - if thickness <= 0.0 { - return None; + ShapeTree::Modify { op, post_xform, child } => { + 3u8.hash(h); + op.hash_into(h); + post_xform.hash_into(h); + child.hash_into(h); } - 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, 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) } - "sBoolean" => { - 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_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 child = |port: &str| { - node.connected_node(port) - .and_then(|s| comp.find_node(s)) - .and_then(|id| { - collect_shape_tree(comp, id, time, expr, parent_xform, outline_override, depth + 1) - }) - }; - let a = child("Input1").or_else(|| child("Input"))?; - // Input2 absent passes Input1 through (recolored) whatever the operation; Input1 absent renders empty. - let (op, b) = match (parse_bool_op(node), child("Input2")) { - (_, None) => (ShapeBoolOp::Union, ShapeTree::Group(Vec::new())), - (Some(op), Some(b)) => (op, b), - (None, Some(_)) => return None, - }; - Some(ShapeTree::Boolean { - op, - color, - opacity, - keep_style, - a: Box::new(a), - b: Box::new(b), - }) - } - "PipeRouter" | "Fuse.Wireless" => { - let src_id = 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) - } - "MacroOperator" | "GroupOperator" => { - let out_id = node.macro_output?; - collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1) - } - _ => None, - } -} - -fn build_primitive_commands(kind: ShapePrimKind, xform: Affine2D, dims: [u32; 2]) -> Vec { - let wf = dims[0] as f32; - let hf = dims[1] as f32; - let to_px = |local: [f32; 2]| -> zeno::Vector { - let wpt = xform.apply(local); - let px = (wpt[0] + 0.5) * wf; - let py = 0.5 * hf - wpt[1] * wf; - zeno::Vector::new(px, py) - }; - - const KAPPA: f32 = 0.55228475; - let mut cmds = Vec::new(); - match kind { - ShapePrimKind::NGon { sides, width, height } => { - let n = sides.max(3); - let rx = width * 0.5; - let ry = height * 0.5; - if rx <= 1e-6 || ry <= 1e-6 { - return cmds; - } - for k in 0..n { - let theta = (k as f32) * std::f32::consts::TAU / (n as f32); - let v = to_px([rx * theta.cos(), ry * theta.sin()]); - if k == 0 { - cmds.push(zeno::Command::MoveTo(v)); - } else { - cmds.push(zeno::Command::LineTo(v)); - } - } - cmds.push(zeno::Command::Close); - } - ShapePrimKind::Rectangle { width, height, corner_radius } => { - let hx = width * 0.5; - let hy = height * 0.5; - if hx <= 1e-6 || hy <= 1e-6 { - return cmds; - } - let r = corner_radius.min(hx.min(hy)); - if r <= 1e-5 { - // Start at mid-right (+hx, 0) counter-clockwise so WritePosition matches sNGon/sEllipse. - cmds.push(zeno::Command::MoveTo(to_px([hx, 0.0]))); - cmds.push(zeno::Command::LineTo(to_px([hx, hy]))); - cmds.push(zeno::Command::LineTo(to_px([-hx, hy]))); - cmds.push(zeno::Command::LineTo(to_px([-hx, -hy]))); - cmds.push(zeno::Command::LineTo(to_px([hx, -hy]))); - cmds.push(zeno::Command::Close); - } else { - let k = r * KAPPA; - cmds.push(zeno::Command::MoveTo(to_px([hx, 0.0]))); - cmds.push(zeno::Command::LineTo(to_px([hx, hy - r]))); - cmds.push(zeno::Command::CurveTo( - to_px([hx, hy - r + k]), - to_px([hx - r + k, hy]), - to_px([hx - r, hy]), - )); - cmds.push(zeno::Command::LineTo(to_px([-hx + r, hy]))); - cmds.push(zeno::Command::CurveTo( - to_px([-hx + r - k, hy]), - to_px([-hx, hy - r + k]), - to_px([-hx, hy - r]), - )); - cmds.push(zeno::Command::LineTo(to_px([-hx, -hy + r]))); - cmds.push(zeno::Command::CurveTo( - to_px([-hx, -hy + r - k]), - to_px([-hx + r - k, -hy]), - to_px([-hx + r, -hy]), - )); - cmds.push(zeno::Command::LineTo(to_px([hx - r, -hy]))); - cmds.push(zeno::Command::CurveTo( - to_px([hx - r + k, -hy]), - to_px([hx, -hy + r - k]), - to_px([hx, -hy + r]), - )); - cmds.push(zeno::Command::Close); - } - } - ShapePrimKind::Ellipse { width, height } => { - let rx = width * 0.5; - let ry = height * 0.5; - if rx <= 1e-6 || ry <= 1e-6 { - return cmds; - } - let kx = rx * KAPPA; - let ky = ry * KAPPA; - cmds.push(zeno::Command::MoveTo(to_px([rx, 0.0]))); - cmds.push(zeno::Command::CurveTo( - to_px([rx, ky]), - to_px([kx, ry]), - to_px([0.0, ry]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([-kx, ry]), - to_px([-rx, ky]), - to_px([-rx, 0.0]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([-rx, -ky]), - to_px([-kx, -ry]), - to_px([0.0, -ry]), - )); - cmds.push(zeno::Command::CurveTo( - to_px([kx, -ry]), - to_px([rx, -ky]), - to_px([rx, 0.0]), - )); - cmds.push(zeno::Command::Close); - } - ShapePrimKind::Star { points, depth, width, height, corner_radius } => { - let n = points.max(3) as usize; - let rx = width * 0.5; - let ry = height * 0.5; - if rx <= 1e-6 || ry <= 1e-6 { - return cmds; - } - let total = n * 2; - let mut verts = Vec::with_capacity(total); - for k in 0..total { - let theta = (k as f32) * std::f32::consts::PI / (n as f32); - let s = if k % 2 == 0 { 1.0 } else { depth }; - verts.push([rx * s * theta.cos(), ry * s * theta.sin()]); - } - if corner_radius <= 1e-5 { - for (k, &pt) in verts.iter().enumerate() { - let v = to_px(pt); - if k == 0 { - cmds.push(zeno::Command::MoveTo(v)); - } else { - cmds.push(zeno::Command::LineTo(v)); - } - } - cmds.push(zeno::Command::Close); - } else { - for k in 0..total { - let prev = verts[(k + total - 1) % total]; - let curr = verts[k]; - let next = verts[(k + 1) % total]; - let d_prev = [prev[0] - curr[0], prev[1] - curr[1]]; - let d_next = [next[0] - curr[0], next[1] - curr[1]]; - let l_prev = d_prev[0].hypot(d_prev[1]); - let l_next = d_next[0].hypot(d_next[1]); - let r = corner_radius.min(0.45 * l_prev.min(l_next)); - if r <= 1e-6 { - let v = to_px(curr); - if k == 0 { - cmds.push(zeno::Command::MoveTo(v)); - } else { - cmds.push(zeno::Command::LineTo(v)); - } - } else { - let p_in = [curr[0] + d_prev[0] * (r / l_prev), curr[1] + d_prev[1] * (r / l_prev)]; - let p_out = [curr[0] + d_next[0] * (r / l_next), curr[1] + d_next[1] * (r / l_next)]; - if k == 0 { - cmds.push(zeno::Command::MoveTo(to_px(p_in))); - } else { - cmds.push(zeno::Command::LineTo(to_px(p_in))); - } - cmds.push(zeno::Command::QuadTo(to_px(curr), to_px(p_out))); - } - } - cmds.push(zeno::Command::Close); - } - } - } - cmds -} - -fn flatten_commands_to_poly(cmds: &[zeno::Command]) -> 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); - 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); - 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 -} - -/// Trims a closed command loop to arc-length fraction `[write_pos, write_pos + write_len]`. -fn trim_path_commands(cmds: Vec, write_pos: f32, write_len: f32) -> Vec { - if write_len <= 1e-5 { - return Vec::new(); - } - if write_len >= 1.0 - 1e-5 { - return cmds; - } - let poly = flatten_commands_to_poly(&cmds); - let n = poly.len(); - if n < 2 { - return Vec::new(); - } - let mut segs = Vec::with_capacity(n); - let mut total = 0.0_f32; - for i in 0..n { - let a = poly[i]; - let b = poly[(i + 1) % n]; - let len = (b[0] - a[0]).hypot(b[1] - a[1]); - segs.push((a, b, len)); - total += len; - } - if total <= 1e-5 { - return Vec::new(); - } - let s0 = write_pos.rem_euclid(1.0) * total; - let target = write_len * total; - let mut out = Vec::new(); - let mut acc = 0.0_f32; - let mut started = false; - let mut idx = 0usize; - while acc < s0 + target - 1e-5 && idx < n * 2 + 2 { - let (a, b, len) = segs[idx % n]; - idx += 1; - if len <= 1e-6 { - continue; - } - let seg_start = acc; - let seg_end = acc + len; - acc = seg_end; - if seg_end <= s0 { - continue; - } - let t0 = if !started { ((s0 - seg_start) / len).clamp(0.0, 1.0) } else { 0.0 }; - let t1 = ((s0 + target - seg_start) / len).clamp(0.0, 1.0); - if !started { - let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; - out.push(zeno::Command::MoveTo(zeno::Vector::new(p[0], p[1]))); - started = true; - } - let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; - out.push(zeno::Command::LineTo(zeno::Vector::new(q[0], q[1]))); - } - out -} - -/// Flattens `cmds` and clips the polygon to the canvas grown by `margin`; zeno stalls on diagonal edges tens of canvases long. -fn clip_to_viewport(cmds: Vec, dims: [u32; 2], margin: f32) -> Vec { - use zeno::Command::{Close, CurveTo, LineTo, MoveTo}; - let [w, h] = [dims[0] as f32, dims[1] as f32]; - let limit = 4.0 * w.max(h); - let far = |v: &zeno::Vector| v.x.abs() > limit || v.y.abs() > limit; - let huge = cmds.iter().any(|c| match c { - MoveTo(p) | LineTo(p) => far(p), - zeno::Command::QuadTo(a, p) => far(a) || far(p), - CurveTo(a, b, p) => far(a) || far(b) || far(p), - _ => false, - }); - if !huge { - return cmds; - } - let mut poly = flatten_commands_to_poly(&cmds); - 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::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 -} - -fn composite_over(dst: &mut [f32], src: &[f32]) { - for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { - let sa = s[3].clamp(0.0, 1.0); - if sa <= 1e-6 { - continue; - } - let inv = 1.0 - sa; - d[0] = s[0] + d[0] * inv; - d[1] = s[1] + d[1] * inv; - d[2] = s[2] + d[2] * inv; - d[3] = sa + d[3] * inv; - } -} - -fn rasterize_shape_tree_f32( - tree: &ShapeTree, - dims: [u32; 2], - dst: &mut [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, - } => { - let cmds = build_primitive_commands(*kind, *xform, 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; - } - cov_buf.fill(0); - let reach = 4.0 * w.max(h) as f32; - let stroke_px = (*border_width * xform.avg_scale() * (w as f32)).clamp(0.5, reach); - let cmds = clip_to_viewport(cmds, dims, if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }); - let cmds = if !*solid && (write_pos.abs() > 1e-5 || (*write_len - 1.0).abs() > 1e-5) { - trim_path_commands(cmds, *write_pos, *write_len) - } else { - cmds - }; - if cmds.is_empty() { - return; - } - let style = if *solid { - 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, dst, cov_buf, scratch); - } - } - ShapeTree::Boolean { op, color, opacity: _, keep_style, a, b } => { - let len = dst.len(); - let mut buf_a = vec![0.0f32; len]; - let mut buf_b = vec![0.0f32; len]; - rasterize_shape_tree_f32(a, dims, &mut buf_a, cov_buf, scratch); - rasterize_shape_tree_f32(b, dims, &mut buf_b, cov_buf, scratch); - let mut comb = vec![0.0f32; len]; - let ca = color[3].clamp(0.0, 1.0); - for ((ca_p, cb_p), out_p) in buf_a - .chunks_exact(4) - .zip(buf_b.chunks_exact(4)) - .zip(comb.chunks_exact_mut(4)) - { - let aa = ca_p[3].clamp(0.0, 1.0); - let ba = cb_p[3].clamp(0.0, 1.0); - let oa = match op { - ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), - ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), - ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), - ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), - }; - if *keep_style { - let s = if aa > 1e-6 { oa / aa } else { 0.0 }; - out_p[0] = ca_p[0] * s; - out_p[1] = ca_p[1] * s; - out_p[2] = ca_p[2] * s; - out_p[3] = oa; - } else { - // Opacity scales RGBA (baked into color); Alpha scales alpha only (not RGB). - out_p[0] = color[0] * oa; - out_p[1] = color[1] * oa; - out_p[2] = color[2] * oa; - out_p[3] = oa * ca; - } - } - composite_over(dst, &comb); - } - } -} - -fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec { - let px_count = (dims[0] as usize) * (dims[1] as usize); - let mut out = vec![0u8; px_count * 4]; - let Some(tree) = tree else { - return out; - }; - let b = blend.clamp(0.0, 1.0); - if b <= 1e-6 { - return out; - } - let mut accum = vec![0.0f32; px_count * 4]; - let mut cov_buf = vec![0u8; px_count]; - let mut scratch = zeno::Scratch::new(); - rasterize_shape_tree_f32(tree, dims, &mut accum, &mut cov_buf, &mut scratch); - for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { - dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; - dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; } - out } impl Engine { @@ -960,11 +310,21 @@ impl Engine { // Fusion sRender ignores Blend (always renders at full 1.0 opacity). 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) + collect_shape_tree( + comp, + src_id, + time, + &self.expr, + Affine2D::identity(), + None, + 0, + &mut prim_budget, + ) }); let (mask, mask_inv) = self.eval_mask_input_sized(comp, node, time, Some(dims), enc, visiting, stats); @@ -1050,378 +410,3 @@ impl Engine { out } } - -#[cfg(test)] -mod tests { - use super::*; - use crate::Engine; - - #[test] - fn test_s_render_ngon_transform_merge_and_boolean() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - NGon1 = sNGon { - Inputs = { - Sides = Input { Value = 6, }, - Width = Input { Value = 0.4, }, - Red = Input { Value = 1.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - XF1 = sTransform { - Inputs = { - XOffset = Input { Value = -0.2, }, - YOffset = Input { Value = 0.0, }, - XSize = Input { Value = 1.0, }, - YSize = Input { Value = 1.0, }, - ZRotation = Input { Value = 15.0, }, - Input = Input { SourceOp = "NGon1", Source = "Output", }, - }, - }, - Rect1 = sRectangle { - Inputs = { - Width = Input { Value = 0.3, }, - Height = Input { Value = 0.3, }, - CornerRadius = Input { Value = 0.05, }, - Translate = Input { Value = { 0.0, 0.0 }, }, - ["Translate.X"] = Input { Value = 0.2, }, - Red = Input { Value = 0.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 1.0, }, - }, - }, - Merge1 = sMerge { - Inputs = { - Input1 = Input { SourceOp = "XF1", Source = "Output", }, - Input2 = Input { SourceOp = "Rect1", Source = "Output", }, - }, - }, - Render1 = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "Merge1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let render_id = comp.find_node("Render1").unwrap(); - let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); - assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); - assert_eq!(tex.size, [128, 128]); - let px = eng.readback_rgba(&tex).expect("readback sRender"); - - // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red - let left = (64 * 128 + 38) * 4; - assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); - // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue - let right = (64 * 128 + 90) * 4; - assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); - // Top-left corner (0, 0) should be transparent - assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); - } - - - #[test] - fn test_s_boolean_uses_own_color_and_subtract_xor() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - NGon1 = sNGon { - Inputs = { - Sides = Input { Value = 5, }, - Width = Input { Value = 0.5, }, - Height = Input { Value = 0.5, }, - Red = Input { Value = 1.0, }, - Green = Input { Value = 0.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - Rect1 = sRectangle { - Inputs = { - Width = Input { Value = 0.35, }, - Height = Input { Value = 0.35, }, - ["Translate.X"] = Input { Value = 0.18, }, - Red = Input { Value = 0.0, }, - Green = Input { Value = 1.0, }, - Blue = Input { Value = 0.0, }, - }, - }, - BoolSub = sBoolean { - Inputs = { - Operation = Input { Value = FuID { "Subtract" }, }, - Input1 = Input { SourceOp = "Rect1", Source = "Output", }, - Input2 = Input { SourceOp = "NGon1", Source = "Output", }, - }, - }, - BoolXor = sBoolean { - Inputs = { - Operation = Input { Value = FuID { "Xor" }, }, - Input1 = Input { SourceOp = "NGon1", Source = "Output", }, - Input2 = Input { SourceOp = "Rect1", Source = "Output", }, - }, - }, - RSub = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "BoolSub", Source = "Output", }, - }, - }, - RXor = sRender { - Inputs = { - Width = Input { Value = 128, }, - Height = Input { Value = 128, }, - Input = Input { SourceOp = "BoolXor", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); - let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); - let px_sub = eng.readback_rgba(&tex_sub).unwrap(); - let px_xor = eng.readback_rgba(&tex_xor).unwrap(); - - // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! - let rect_only = (64 * 128 + 102) * 4; - assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); - assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); - - // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! - let overlap = (64 * 128 + 77) * 4; - assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); - assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); - - // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! - let ngon_only = (64 * 128 + 54) * 4; - assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); - } - - #[test] - fn test_s_boolean_operation_names_and_missing_inputs() { - let boolean = |name: &str, op: &str, inputs: &str| { - format!( - r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, - R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, - Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# - ) - }; - let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; - let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; - let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; - let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); - let src = format!( - r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ - Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, - Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, - Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, - {} {} {} {} {} {} - }} }}"#, - boolean("Inter", &fu("Intersection"), both), - boolean("Default", "", both), - boolean("Unknown", &fu("Intersect"), both), - boolean("SubFirst", &fu("Subtract"), first), - boolean("SubSecond", &fu("Subtract"), second), - boolean("UnionBoth", &fu("Union"), both), - ); - let comp = Comp::from_fusion_str(&src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { - return; - }; - let mut px = |name: &str, x: usize| { - let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); - let rgba = eng.readback_rgba(&tex).unwrap(); - let i = (64 * 128 + x) * 4; - [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] - }; - let white = [255; 4]; - let empty = [0; 4]; - // x=64 is inside both shapes, x=90 is inside only the rectangle. - assert_eq!(px("Inter", 64), white); - assert_eq!(px("Inter", 90), empty); - assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); - assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); - assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); - assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); - assert_eq!(px("UnionBoth", 90), white); - } - - #[test] - fn test_s_grid() { - let src = r#"{ - Tools = ordered() { - El1 = sEllipse { - Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, - }, - Gr1 = sGrid { - Inputs = { - Input = Input { SourceOp = "El1", Source = "Output", }, - CellsX = Input { Value = 3, }, - CellsY = Input { Value = 3, }, - XOffset = Input { Value = 0.25, }, - YOffset = Input { Value = 0.25, }, - }, - }, - SR1 = sRender { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Input = Input { SourceOp = "Gr1", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { return; }; - let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); - let px_sr = eng.readback_rgba(&t_sr).unwrap(); - assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); - assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); - assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); - } - #[test] - fn test_giant_rotated_shapes_clip_instead_of_hanging_and_alpha_stays_unpremultiplied() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - NG = sNGon { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Alpha = Input { Value = 0.25, }, Opacity = Input { Value = 0.5, }, Blue = Input { Value = 0.5, }, }, }, - Rect = sRectangle { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Angle = Input { Value = 33, }, }, }, - SRN = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "NG", Source = "Output", }, }, }, - SRR = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { return; }; - let (t, _) = eng.evaluate(&comp, comp.find_node("SRN").unwrap(), 0.0); - let px = eng.readback_rgba(&t).unwrap(); - let mid = (16 * 32 + 16) * 4; - assert_eq!(&px[mid..mid + 4], &[128, 128, 64, 32], "Opacity scales RGBA, Alpha scales alpha only"); - let (t, _) = eng.evaluate(&comp, comp.find_node("SRR").unwrap(), 0.0); - let px = eng.readback_rgba(&t).unwrap(); - assert_eq!(&px[mid..mid + 4], &[255, 255, 255, 255]); - assert_eq!(&px[0..4], &[255, 255, 255, 255], "giant rotated rectangle covers the corner"); - } - - #[test] - fn s_outline_negative_thickness_s_boolean_keep_style_and_s_render_blend() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - R1 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Red = Input { Value = 1.0, }, Green = Input { Value = 0.0, }, Blue = Input { Value = 0.0, }, }, }, - R2 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Blue = Input { Value = 1.0, }, }, }, - OutNeg = sOutline { Inputs = { Input = Input { SourceOp = "R1", Source = "Output", }, Thickness = Input { Value = -0.05, }, }, }, - SROutNeg = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "OutNeg", Source = "Output", }, }, }, - BoolKeep = sBoolean { Inputs = { - Input1 = Input { SourceOp = "R1", Source = "Output", }, - Input2 = Input { SourceOp = "R2", Source = "Output", }, - Operation = Input { Value = FuID { "Intersection" }, }, - StyleMode = Input { Value = FuID { "Keep" }, }, - Opacity = Input { Value = 0.2, }, - Green = Input { Value = 1.0, }, - }, }, - SRBool = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Blend = Input { Value = 0.2, }, Input = Input { SourceOp = "BoolKeep", Source = "Output", }, }, }, - }, - }"#; - let comp = Comp::from_fusion_str(src).unwrap(); - let Ok(mut eng) = Engine::new_headless() else { return; }; - let (t_out, _) = eng.evaluate(&comp, comp.find_node("SROutNeg").unwrap(), 0.0); - let px_out = eng.readback_rgba(&t_out).unwrap(); - assert!(px_out.iter().all(|&b| b == 0), "negative sOutline thickness should render empty"); - - let (t_bool, _) = eng.evaluate(&comp, comp.find_node("SRBool").unwrap(), 0.0); - let px_bool = eng.readback_rgba(&t_bool).unwrap(); - let mid = (16 * 32 + 16) * 4; - assert_eq!(&px_bool[mid..mid + 4], &[255, 0, 0, 255], "sBoolean Keep preserves Input1 style ignoring Opacity, and sRender ignores Blend"); - } - - #[test] - fn test_s_star_points_depth_rotation_and_outline() { - let src = r#"Composition { - CurrentTime = 0, - RenderRange = { 0, 1 }, - GlobalRange = { 0, 1 }, - Tools = ordered() { - Star5 = sStar { - Inputs = { - Points = Input { Value = 5, }, - Depth = Input { Value = 0.5, }, - Width = Input { Value = 0.6, }, - Height = Input { Value = 0.6, }, - Red = Input { Value = 1.0, }, - Green = Input { Value = 0.5, }, - Blue = Input { Value = 0.0, }, - }, - }, - StarOutline = sStar { - Inputs = { - NumberOfPoints = Input { Value = 6, }, - Depth = Input { Value = 0.4, }, - Width = Input { Value = 0.6, }, - Height = Input { Value = 0.6, }, - Solid = Input { Value = 0, }, - BorderWidth = Input { Value = 0.04, }, - CornerRadius = Input { Value = 0.02, }, - ZRotation = Input { Value = 30.0, }, - }, - }, - SRFill = sRender { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Input = Input { SourceOp = "Star5", Source = "Output", }, - }, - }, - SROutline = sRender { - Inputs = { - Width = Input { Value = 64, }, - Height = Input { Value = 64, }, - Input = Input { SourceOp = "StarOutline", Source = "Output", }, - }, - }, - }, - }"#; - let comp = Comp::from_fusion_str(src).expect("parse sStar comp"); - let Ok(mut eng) = Engine::new_headless() else { return }; - - let (tf, sf) = eng.evaluate(&comp, comp.find_node("SRFill").unwrap(), 0.0); - assert!(sf.unsupported_nodes.is_empty()); - let pf = eng.readback_rgba(&tf).unwrap(); - let px = |buf: &[u8], x: usize, y: usize| -> [u8; 4] { - let i = (y * 64 + x) * 4; - [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] - }; - // Center (32, 32) is solid orange. - let ctr = px(&pf, 32, 32); - assert!(ctr[0] > 240 && (ctr[1] as i32 - 128).abs() <= 4 && ctr[2] < 5 && ctr[3] == 255, "center={ctr:?}"); - // Rightmost outer tip at +X (r = 0.30 -> x ~ 50, y = 32) is covered! - assert!(px(&pf, 49, 32)[3] > 200, "outer tip at +X must be covered"); - // Opposite -X valley for odd 5-point star is at r = 0.15 (x ~ 22.4): x=24 inside, x=15 outside! - assert!(px(&pf, 24, 32)[3] > 200, "inner valley interior must be covered"); - assert_eq!(px(&pf, 15, 32)[3], 0, "outside -X inner valley must be empty"); - - // Outline mode: hollow center, non-empty stroke ring. - let (to, _) = eng.evaluate(&comp, comp.find_node("SROutline").unwrap(), 0.0); - let po = eng.readback_rgba(&to).unwrap(); - assert_eq!(px(&po, 32, 32)[3], 0, "outline sStar center must be hollow"); - let lit_px = po.chunks_exact(4).filter(|c| c[3] > 127).count(); - assert!(lit_px > 50, "outline sStar should render visible stroke pixels, got {lit_px}"); - } -} diff --git a/crates/engine/src/eval/shapes/collect.rs b/crates/engine/src/eval/shapes/collect.rs new file mode 100644 index 0000000000000000000000000000000000000000..b9d0b2edc77360f62879384630c702ca0ffebb03 --- /dev/null +++ b/crates/engine/src/eval/shapes/collect.rs @@ -0,0 +1,707 @@ +//! Graph collection for 2D vector shape nodes (`sNGon`, `sRectangle`, `sEllipse`, `sStar`, +//! `sPolygon`, `sTransform`, `sMerge`, `sGrid`, `sDuplicate`, `sJitter`, `sExpand`, `sOffset`, +//! `sOutline`, `sBoolean`). + +use model::{Comp, ExprEngine, Node, NodeId, ParamValue}; + +use super::{Affine2D, OutlineStyle, PathModifier, ShapeBoolOp, ShapePrimKind, ShapeTree}; + +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 +} + +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; + } + } + false +} + +/// Fusion accepts exactly `Union | Intersection | Subtract | Xor` (default `Intersection`); any other value renders empty. +fn parse_bool_op(node: &Node) -> Option { + if !node.inputs.contains_key("Operation") { + return Some(ShapeBoolOp::Intersect); + } + match node.static_str("Operation")? { + "Union" => Some(ShapeBoolOp::Union), + "Intersection" => Some(ShapeBoolOp::Intersect), + "Subtract" => Some(ShapeBoolOp::Subtract), + "Xor" => Some(ShapeBoolOp::Xor), + _ => None, + } +} + +/// 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, + node_id: NodeId, + time: f64, + expr: &ExprEngine, + parent_xform: Affine2D, + outline_override: Option, + depth: usize, + prim_budget: &mut usize, +) -> Option { + if depth > 32 || *prim_budget == 0 { + return None; + } + let node = comp.node(node_id); + if node.bypassed { + return node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .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, + ) + }); + } + + match node.kind.as_str() { + "sNGon" | "sRectangle" | "sEllipse" | "sStar" | "sPolygon" => { + *prim_budget = prim_budget.saturating_sub(1); + let [tx, ty] = eval_xy_or_point( + 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, + }) + } + "sTransform" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + let [ox, oy] = eval_xy_or_point( + comp, + node, + &["XOffset", "Translate.X"], + &["YOffset", "Translate.Y"], + "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 rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; + + let local = Affine2D::translate(ox + px, oy + py) + .mul(Affine2D::rotate_deg(rot)) + .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) + } + "sDuplicate" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + let copies = comp.eval_number(node, "Copies", time, 2.0, expr).round().clamp(0.0, 256.0) as usize; + if copies == 0 { + return None; + } + let [ox, oy] = eval_xy_or_point( + comp, + node, + &["XOffset", "Translate.X"], + &["YOffset", "Translate.Y"], + "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 lock_size = comp.eval_number(node, "LockSize", time, 1.0, expr) > 0.5; + 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 = if node.inputs.contains_key("YSize") { + comp.eval_number(node, "YSize", time, base_scale, expr) as f32 + } else if lock_size && node.inputs.contains_key("XSize") { + sx + } else { + base_scale as f32 + }; + let rot = eval_first_num(comp, node, &["ZRotation", "Rotate", "Angle"], time, 0.0, expr) as f32; + let time_offset = comp.eval_number(node, "TimeOffset", time, 0.0, expr); + + let step_xf = Affine2D::translate(ox + px, oy + py) + .mul(Affine2D::rotate_deg(rot)) + .mul(Affine2D::scale(sx, sy)) + .mul(Affine2D::translate(-px, -py)); + + let mut children = Vec::with_capacity(copies); + let mut cum_xf = Affine2D::identity(); + for i in 0..copies { + if *prim_budget == 0 { + break; + } + let copy_time = time + (i as f64) * time_offset; + let copy_xf = parent_xform.mul(cum_xf); + if let Some(tree) = collect_shape_tree( + comp, + src_id, + copy_time, + expr, + copy_xf, + outline_override, + depth + 1, + prim_budget, + ) { + children.push(tree); + } + cum_xf = cum_xf.mul(step_xf); + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sJitter" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + + let has_x = node.inputs.contains_key("XAmount") + || node.inputs.contains_key("PositionX") + || node.inputs.contains_key("XPosition"); + let has_y = node.inputs.contains_key("YAmount") + || node.inputs.contains_key("PositionY") + || node.inputs.contains_key("YPosition"); + let has_amt = node.inputs.contains_key("Amount"); + let amt = comp.eval_number(node, "Amount", time, 0.02, expr); + let x_amount = if has_x { + eval_first_num(comp, node, &["XAmount", "PositionX", "XPosition"], time, 0.0, expr) as f32 + } else if has_amt { + amt as f32 + } else if has_y { + 0.0 + } else { + 0.02 + }; + let y_amount = if has_y { + eval_first_num(comp, node, &["YAmount", "PositionY", "YPosition"], time, 0.0, expr) as f32 + } else if has_amt { + amt as f32 + } else if has_x { + 0.0 + } else { + 0.02 + }; + + let seed = eval_first_num(comp, node, &["Seed", "RandomSeed"], time, 0.0, expr).round() as i64; + let smoothness = eval_first_num(comp, node, &["Smoothness", "Smooth"], time, 0.0, expr) + .clamp(0.0, 100.0) as f32; + 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( + comp, + src_id, + time, + expr, + Affine2D::identity(), + outline_override, + depth + 1, + prim_budget, + )?; + + if x_amount.abs() <= 1e-6 && y_amount.abs() <= 1e-6 { + return Some(ShapeTree::Modify { + op: PathModifier::Offset { + offset_x: 0.0, + offset_y: 0.0, + contour_offset: 0.0, + position: 0.0, + join_style: 1, + miter_limit: 10.0, + }, + post_xform: parent_xform, + child: Box::new(child), + }); + } + + Some(ShapeTree::Modify { + op: PathModifier::Jitter { + x_amount, + y_amount, + seed, + smoothness, + per_shape, + }, + post_xform: parent_xform, + child: Box::new(child), + }) + } + "sExpand" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + 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( + comp, + src_id, + time, + expr, + parent_xform, + outline_override, + depth + 1, + prim_budget, + ); + } + + let child = collect_shape_tree( + comp, + src_id, + time, + expr, + Affine2D::identity(), + outline_override, + depth + 1, + prim_budget, + )?; + Some(ShapeTree::Modify { + op: PathModifier::Expand { + amount, + join_style, + miter_limit, + }, + post_xform: parent_xform, + child: Box::new(child), + }) + } + "sOffset" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + + 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; + let mut contour_offset = 0.0_f32; + if node.inputs.contains_key("Offset") { + if is_point_binding(comp, node, "Offset") { + let pt = comp.eval_point(node, "Offset", time, [0.0, 0.0], expr); + offset_x += pt[0] as f32; + offset_y += pt[1] as f32; + } else { + contour_offset = comp.eval_number(node, "Offset", time, 0.0, expr) as f32; + } + } + let position = eval_first_num(comp, node, &["Position", "PathPosition"], 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; + + // 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( + comp, + src_id, + time, + expr, + combined, + outline_override, + depth + 1, + prim_budget, + ); + } + + let child = collect_shape_tree( + comp, + src_id, + time, + expr, + Affine2D::identity(), + outline_override, + depth + 1, + prim_budget, + )?; + Some(ShapeTree::Modify { + op: PathModifier::Offset { + offset_x, + offset_y, + contour_offset, + position, + join_style, + miter_limit, + }, + post_xform: parent_xform, + child: Box::new(child), + }) + } + "sMerge" => { + let mut ports: Vec<(u32, &str)> = node + .inputs + .keys() + .filter_map(|k| { + let rest = k.strip_prefix("Input")?; + let idx: u32 = if rest.is_empty() { 0 } else { rest.parse().ok()? }; + Some((idx, k.as_str())) + }) + .collect(); + 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( + comp, + src_id, + time, + expr, + parent_xform, + outline_override, + depth + 1, + prim_budget, + ) { + children.push(tree); + } + } + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sGrid" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + 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; + let y_off = comp.eval_number(node, "YOffset", time, 0.2, expr) as f32; + let mut children = Vec::with_capacity(cells_x.saturating_mul(cells_y).min(*prim_budget)); + for iy in 0..cells_y { + let ty = (iy as f32 - (cells_y as f32 - 1.0) * 0.5) * y_off; + for ix in 0..cells_x { + if *prim_budget == 0 { + break; + } + 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( + comp, + src_id, + time, + expr, + cell_xf, + outline_override, + depth + 1, + prim_budget, + ) { + children.push(tree); + } + } + } + if children.is_empty() { + None + } else { + Some(ShapeTree::Group(children)) + } + } + "sOutline" => { + let src_id = node + .connected_node("Input") + .or_else(|| node.connected_node("Input1")) + .and_then(|s| comp.find_node(s))?; + 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 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) + } + "sBoolean" => { + 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_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 a = node + .connected_node("Input1") + .or_else(|| node.connected_node("Input")) + .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| comp.find_node(s)) + .and_then(|id| { + collect_shape_tree( + comp, + id, + time, + expr, + parent_xform, + outline_override, + 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())), + (Some(op), Some(b)) => (op, b), + (None, Some(_)) => return None, + }; + Some(ShapeTree::Boolean { + op, + color, + opacity, + keep_style, + a: Box::new(a), + b: Box::new(b), + }) + } + "PipeRouter" | "Fuse.Wireless" => { + let src_id = 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) + } + "MacroOperator" | "GroupOperator" => { + let out_id = node.macro_output?; + collect_shape_tree(comp, out_id, time, expr, parent_xform, outline_override, depth + 1, prim_budget) + } + _ => None, + } +} diff --git a/crates/engine/src/eval/shapes/geometry.rs b/crates/engine/src/eval/shapes/geometry.rs new file mode 100644 index 0000000000000000000000000000000000000000..524529a6b086ff76133f52edc480fb0069818adf --- /dev/null +++ b/crates/engine/src/eval/shapes/geometry.rs @@ -0,0 +1,892 @@ +//! 2D vector shape command generation, contour flattening, path modifiers +//! (`sExpand`, `sJitter`, `sOffset`), 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, +} + +#[inline] +fn shape_to_px(wpt: [f32; 2], dims: [u32; 2]) -> zeno::Vector { + let wf = dims[0] as f32; + let hf = dims[1] as f32; + zeno::Vector::new((wpt[0] + 0.5) * wf, 0.5 * hf - wpt[1] * wf) +} + +/// Builds shape-space `zeno::Command`s for a primitive and returns `(cmds, closed)`. +fn build_primitive_commands_shape(kind: &ShapePrimKind, xform: Affine2D) -> (Vec, bool) { + let to_v = |local: [f32; 2]| -> zeno::Vector { + let p = xform.apply(local); + zeno::Vector::new(p[0], p[1]) + }; + + const KAPPA: f32 = 0.55228475; + let mut cmds = Vec::new(); + match kind { + ShapePrimKind::NGon { sides, width, height } => { + let n = (*sides).max(3); + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return (cmds, true); + } + for k in 0..n { + let theta = (k as f32) * std::f32::consts::TAU / (n as f32); + let v = to_v([rx * theta.cos(), ry * theta.sin()]); + if k == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + cmds.push(zeno::Command::Close); + (cmds, true) + } + ShapePrimKind::Rectangle { width, height, corner_radius } => { + let hx = width * 0.5; + let hy = height * 0.5; + if hx <= 1e-6 || hy <= 1e-6 { + return (cmds, true); + } + let r = corner_radius.min(hx.min(hy)); + if r <= 1e-5 { + // Start at mid-right (+hx, 0) counter-clockwise so WritePosition matches sNGon/sEllipse. + cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0]))); + cmds.push(zeno::Command::LineTo(to_v([hx, hy]))); + cmds.push(zeno::Command::LineTo(to_v([-hx, hy]))); + cmds.push(zeno::Command::LineTo(to_v([-hx, -hy]))); + cmds.push(zeno::Command::LineTo(to_v([hx, -hy]))); + cmds.push(zeno::Command::Close); + } else { + let k = r * KAPPA; + cmds.push(zeno::Command::MoveTo(to_v([hx, 0.0]))); + cmds.push(zeno::Command::LineTo(to_v([hx, hy - r]))); + cmds.push(zeno::Command::CurveTo( + to_v([hx, hy - r + k]), + to_v([hx - r + k, hy]), + to_v([hx - r, hy]), + )); + cmds.push(zeno::Command::LineTo(to_v([-hx + r, hy]))); + cmds.push(zeno::Command::CurveTo( + to_v([-hx + r - k, hy]), + to_v([-hx, hy - r + k]), + to_v([-hx, hy - r]), + )); + cmds.push(zeno::Command::LineTo(to_v([-hx, -hy + r]))); + cmds.push(zeno::Command::CurveTo( + to_v([-hx, -hy + r - k]), + to_v([-hx + r - k, -hy]), + to_v([-hx + r, -hy]), + )); + cmds.push(zeno::Command::LineTo(to_v([hx - r, -hy]))); + cmds.push(zeno::Command::CurveTo( + to_v([hx - r + k, -hy]), + to_v([hx, -hy + r - k]), + to_v([hx, -hy + r]), + )); + cmds.push(zeno::Command::Close); + } + (cmds, true) + } + ShapePrimKind::Ellipse { width, height } => { + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return (cmds, true); + } + let kx = rx * KAPPA; + let ky = ry * KAPPA; + cmds.push(zeno::Command::MoveTo(to_v([rx, 0.0]))); + cmds.push(zeno::Command::CurveTo( + to_v([rx, ky]), + to_v([kx, ry]), + to_v([0.0, ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_v([-kx, ry]), + to_v([-rx, ky]), + to_v([-rx, 0.0]), + )); + cmds.push(zeno::Command::CurveTo( + to_v([-rx, -ky]), + to_v([-kx, -ry]), + to_v([0.0, -ry]), + )); + cmds.push(zeno::Command::CurveTo( + to_v([kx, -ry]), + to_v([rx, -ky]), + to_v([rx, 0.0]), + )); + cmds.push(zeno::Command::Close); + (cmds, true) + } + ShapePrimKind::Star { points, depth, width, height, corner_radius } => { + let n = (*points).max(3) as usize; + let rx = width * 0.5; + let ry = height * 0.5; + if rx <= 1e-6 || ry <= 1e-6 { + return (cmds, true); + } + let total = n * 2; + let mut verts = Vec::with_capacity(total); + for k in 0..total { + let theta = (k as f32) * std::f32::consts::PI / (n as f32); + let s = if k % 2 == 0 { 1.0 } else { *depth }; + verts.push([rx * s * theta.cos(), ry * s * theta.sin()]); + } + if *corner_radius <= 1e-5 { + for (k, &pt) in verts.iter().enumerate() { + let v = to_v(pt); + if k == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } + cmds.push(zeno::Command::Close); + } else { + for k in 0..total { + let prev = verts[(k + total - 1) % total]; + let curr = verts[k]; + let next = verts[(k + 1) % total]; + let d_prev = [prev[0] - curr[0], prev[1] - curr[1]]; + let d_next = [next[0] - curr[0], next[1] - curr[1]]; + let l_prev = d_prev[0].hypot(d_prev[1]); + let l_next = d_next[0].hypot(d_next[1]); + let r = corner_radius.min(0.45 * l_prev.min(l_next)); + if r <= 1e-6 { + let v = to_v(curr); + if k == 0 { + cmds.push(zeno::Command::MoveTo(v)); + } else { + cmds.push(zeno::Command::LineTo(v)); + } + } else { + let p_in = [curr[0] + d_prev[0] * (r / l_prev), curr[1] + d_prev[1] * (r / l_prev)]; + let p_out = [curr[0] + d_next[0] * (r / l_next), curr[1] + d_next[1] * (r / l_next)]; + if k == 0 { + cmds.push(zeno::Command::MoveTo(to_v(p_in))); + } else { + cmds.push(zeno::Command::LineTo(to_v(p_in))); + } + cmds.push(zeno::Command::QuadTo(to_v(curr), to_v(p_out))); + } + } + cmds.push(zeno::Command::Close); + } + (cmds, true) + } + ShapePrimKind::Polygon { points, closed } => { + if points.len() < 2 { + return (cmds, *closed); + } + cmds.push(zeno::Command::MoveTo(to_v([points[0].x as f32, points[0].y as f32]))); + let segs = if *closed { points.len() } else { points.len() - 1 }; + for i in 0..segs { + let a = &points[i]; + let b = &points[(i + 1) % points.len()]; + let p_b = to_v([b.x as f32, b.y as f32]); + let is_linear = (a.linear && b.linear) + || (a.rx.abs() < 1e-9 && a.ry.abs() < 1e-9 && b.lx.abs() < 1e-9 && b.ly.abs() < 1e-9); + if is_linear { + cmds.push(zeno::Command::LineTo(p_b)); + } else { + let c1 = to_v([(a.x + a.rx) as f32, (a.y + a.ry) as f32]); + let c2 = to_v([(b.x + b.lx) as f32, (b.y + b.ly) as f32]); + cmds.push(zeno::Command::CurveTo(c1, c2, p_b)); + } + } + if *closed { + cmds.push(zeno::Command::Close); + } + (cmds, *closed) + } + } +} + +/// 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, + xform: Affine2D, + mods: &[(PathModifier, Affine2D)], + shape_idx: u32, + dims: [u32; 2], +) -> (Vec, bool) { + let (shape_cmds, closed) = build_primitive_commands_shape(kind, xform); + if shape_cmds.is_empty() { + return (Vec::new(), closed); + } + + if mods.is_empty() { + let px_cmds = shape_cmds + .into_iter() + .map(|c| match c { + zeno::Command::MoveTo(p) => zeno::Command::MoveTo(shape_to_px([p.x, p.y], dims)), + zeno::Command::LineTo(p) => zeno::Command::LineTo(shape_to_px([p.x, p.y], dims)), + zeno::Command::QuadTo(a, p) => zeno::Command::QuadTo( + shape_to_px([a.x, a.y], dims), + shape_to_px([p.x, p.y], dims), + ), + zeno::Command::CurveTo(a, b, p) => zeno::Command::CurveTo( + shape_to_px([a.x, a.y], dims), + shape_to_px([b.x, b.y], dims), + shape_to_px([p.x, p.y], dims), + ), + zeno::Command::Close => zeno::Command::Close, + }) + .collect(); + 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 }; + + for (mod_idx, &(op, post_xform)) in mods.iter().enumerate() { + if contour.points.len() < 2 { + return (Vec::new(), contour.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); + } + 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]); + 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, + ]); + } else { + out.push([(q0[0] + q1[0]) * 0.5, (q0[1] + q1[1]) * 0.5]); + } + } + } + + // 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]); + } + 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 +} + +/// 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 } +} + +/// 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 +} + +/// Trims a command loop (closed or open) to arc-length fraction `[write_pos, write_pos + write_len]`. +pub(super) fn trim_path_commands( + cmds: Vec, + closed: bool, + write_pos: f32, + write_len: f32, +) -> Vec { + if write_len <= 1e-5 { + return Vec::new(); + } + 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 n = poly.len(); + if n < 2 { + return Vec::new(); + } + let seg_count = if closed { n } else { n - 1 }; + let mut segs = Vec::with_capacity(seg_count); + let mut total = 0.0_f32; + for i in 0..seg_count { + let a = poly[i]; + let b = poly[(i + 1) % n]; + let len = (b[0] - a[0]).hypot(b[1] - a[1]); + segs.push((a, b, len)); + total += len; + } + if total <= 1e-5 { + return Vec::new(); + } + let s0 = if closed { + write_pos.rem_euclid(1.0) * total + } else { + write_pos.clamp(0.0, 1.0) * total + }; + let target = if closed { + write_len * total + } else { + (write_len * total).min((total - s0).max(0.0)) + }; + if target <= 1e-5 { + return Vec::new(); + } + let mut out = Vec::new(); + let mut acc = 0.0_f32; + let mut started = false; + let mut idx = 0usize; + let max_iters = if closed { seg_count * 2 + 2 } else { seg_count }; + while acc < s0 + target - 1e-5 && idx < max_iters { + let (a, b, len) = segs[idx % seg_count]; + idx += 1; + if len <= 1e-6 { + continue; + } + let seg_start = acc; + let seg_end = acc + len; + acc = seg_end; + if seg_end <= s0 { + continue; + } + let t0 = if !started { ((s0 - seg_start) / len).clamp(0.0, 1.0) } else { 0.0 }; + let t1 = ((s0 + target - seg_start) / len).clamp(0.0, 1.0); + if !started { + let p = [a[0] + t0 * (b[0] - a[0]), a[1] + t0 * (b[1] - a[1])]; + out.push(zeno::Command::MoveTo(zeno::Vector::new(p[0], p[1]))); + started = true; + } + let q = [a[0] + t1 * (b[0] - a[0]), a[1] + t1 * (b[1] - a[1])]; + out.push(zeno::Command::LineTo(zeno::Vector::new(q[0], q[1]))); + } + out +} + +/// Flattens `cmds` and clips a closed polygon 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, + dims: [u32; 2], + margin: f32, +) -> Vec { + use zeno::Command::{Close, CurveTo, LineTo, MoveTo}; + let [w, h] = [dims[0] as f32, dims[1] as f32]; + let limit = 4.0 * w.max(h); + let far = |v: &zeno::Vector| v.x.abs() > limit || v.y.abs() > limit; + let huge = cmds.iter().any(|c| match c { + MoveTo(p) | LineTo(p) => far(p), + zeno::Command::QuadTo(a, p) => far(a) || far(p), + CurveTo(a, b, p) => far(a) || far(b) || far(p), + _ => false, + }); + if !huge || !closed { + return cmds; + } + let mut poly = flatten_commands_to_poly(&cmds); + 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::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/raster.rs b/crates/engine/src/eval/shapes/raster.rs new file mode 100644 index 0000000000000000000000000000000000000000..5d2083fbc6e51c5aca9a6f045033806027cb571f --- /dev/null +++ b/crates/engine/src/eval/shapes/raster.rs @@ -0,0 +1,191 @@ +//! CPU rasterizer for 2D vector `ShapeTree` hierarchies using `zeno`. + +use super::geometry::{build_primitive_commands_px, clip_to_viewport, trim_path_commands}; +use super::{Affine2D, PathModifier, ShapeBoolOp, ShapeTree}; + +fn composite_over(dst: &mut [f32], src: &[f32]) { + for (d, s) in dst.chunks_exact_mut(4).zip(src.chunks_exact(4)) { + let sa = s[3].clamp(0.0, 1.0); + if sa <= 1e-6 { + continue; + } + let inv = 1.0 - sa; + d[0] = s[0] + d[0] * inv; + d[1] = s[1] + d[1] * inv; + d[2] = s[2] + d[2] * inv; + d[3] = sa + d[3] * inv; + } +} + +fn rasterize_shape_tree_f32( + tree: &ShapeTree, + dims: [u32; 2], + mods: &[(PathModifier, Affine2D)], + shape_counter: &mut u32, + dst: &mut [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, + } => { + 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 { + 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, + dims, + if *solid { 4.0 } else { (8.0 + 6.0 * stroke_px).min(reach) }, + ); + 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::Modify { op, post_xform, child } => { + let mut next_mods = Vec::with_capacity(mods.len() + 1); + next_mods.push((*op, *post_xform)); + next_mods.extend_from_slice(mods); + rasterize_shape_tree_f32(child, dims, &next_mods, shape_counter, dst, cov_buf, scratch); + } + ShapeTree::Boolean { op, color, opacity: _, keep_style, a, b } => { + let len = dst.len(); + let mut buf_a = vec![0.0f32; len]; + let mut buf_b = vec![0.0f32; len]; + rasterize_shape_tree_f32(a, dims, mods, shape_counter, &mut buf_a, cov_buf, scratch); + rasterize_shape_tree_f32(b, dims, mods, shape_counter, &mut buf_b, cov_buf, scratch); + let mut comb = vec![0.0f32; len]; + let ca = color[3].clamp(0.0, 1.0); + for ((ca_p, cb_p), out_p) in buf_a + .chunks_exact(4) + .zip(buf_b.chunks_exact(4)) + .zip(comb.chunks_exact_mut(4)) + { + let aa = ca_p[3].clamp(0.0, 1.0); + let ba = cb_p[3].clamp(0.0, 1.0); + let oa = match op { + ShapeBoolOp::Union => (aa + ba - aa * ba).clamp(0.0, 1.0), + ShapeBoolOp::Intersect => (aa * ba).clamp(0.0, 1.0), + ShapeBoolOp::Subtract => (aa * (1.0 - ba)).clamp(0.0, 1.0), + ShapeBoolOp::Xor => (aa * (1.0 - ba) + ba * (1.0 - aa)).clamp(0.0, 1.0), + }; + if *keep_style { + let s = if aa > 1e-6 { oa / aa } else { 0.0 }; + out_p[0] = ca_p[0] * s; + out_p[1] = ca_p[1] * s; + out_p[2] = ca_p[2] * s; + out_p[3] = oa; + } else { + // Opacity scales RGBA (baked into color); Alpha scales alpha only (not RGB). + out_p[0] = color[0] * oa; + out_p[1] = color[1] * oa; + out_p[2] = color[2] * oa; + out_p[3] = oa * ca; + } + } + composite_over(dst, &comb); + } + } +} + +pub(super) fn rasterize_shape_tree_rgba8(tree: Option<&ShapeTree>, dims: [u32; 2], blend: f32) -> Vec { + let px_count = (dims[0] as usize) * (dims[1] as usize); + let mut out = vec![0u8; px_count * 4]; + let Some(tree) = tree else { + return out; + }; + let b = blend.clamp(0.0, 1.0); + if b <= 1e-6 { + return out; + } + let mut accum = vec![0.0f32; px_count * 4]; + let mut cov_buf = vec![0u8; px_count]; + let mut scratch = zeno::Scratch::new(); + let mut shape_counter = 0u32; + rasterize_shape_tree_f32(tree, dims, &[], &mut shape_counter, &mut accum, &mut cov_buf, &mut scratch); + for (dst_px, src_px) in out.chunks_exact_mut(4).zip(accum.chunks_exact(4)) { + dst_px[0] = (src_px[0] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[1] = (src_px[1] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[2] = (src_px[2] * b * 255.0).round().clamp(0.0, 255.0) as u8; + dst_px[3] = (src_px[3] * b * 255.0).round().clamp(0.0, 255.0) as u8; + } + out +} diff --git a/crates/engine/src/eval/shapes/tests.rs b/crates/engine/src/eval/shapes/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f21bc2c8653f926e990b3b23709c328a323c54e --- /dev/null +++ b/crates/engine/src/eval/shapes/tests.rs @@ -0,0 +1,746 @@ +use super::*; +use crate::Engine; + +#[test] +fn test_s_render_ngon_transform_merge_and_boolean() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NGon1 = sNGon { + Inputs = { + Sides = Input { Value = 6, }, + Width = Input { Value = 0.4, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + XF1 = sTransform { + Inputs = { + XOffset = Input { Value = -0.2, }, + YOffset = Input { Value = 0.0, }, + XSize = Input { Value = 1.0, }, + YSize = Input { Value = 1.0, }, + ZRotation = Input { Value = 15.0, }, + Input = Input { SourceOp = "NGon1", Source = "Output", }, + }, + }, + Rect1 = sRectangle { + Inputs = { + Width = Input { Value = 0.3, }, + Height = Input { Value = 0.3, }, + CornerRadius = Input { Value = 0.05, }, + Translate = Input { Value = { 0.0, 0.0 }, }, + ["Translate.X"] = Input { Value = 0.2, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 1.0, }, + }, + }, + Merge1 = sMerge { + Inputs = { + Input1 = Input { SourceOp = "XF1", Source = "Output", }, + Input2 = Input { SourceOp = "Rect1", Source = "Output", }, + }, + }, + Render1 = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "Merge1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sRender comp"); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let render_id = comp.find_node("Render1").unwrap(); + let (tex, stats) = eng.evaluate(&comp, render_id, 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + assert_eq!(tex.size, [128, 128]); + let px = eng.readback_rgba(&tex).expect("readback sRender"); + + // Left shape center (-0.2 -> x ~ 38, y ~ 64) should be solid red + let left = (64 * 128 + 38) * 4; + assert!(px[left] > 240 && px[left + 2] < 10 && px[left + 3] > 240, "left={:?}", &px[left..left + 4]); + // Right shape center (+0.2 -> x ~ 90, y ~ 64) should be solid blue + let right = (64 * 128 + 90) * 4; + assert!(px[right + 2] > 240 && px[right] < 10 && px[right + 3] > 240, "right={:?}", &px[right..right + 4]); + // Top-left corner (0, 0) should be transparent + assert_eq!(&px[0..4], &[0, 0, 0, 0], "corner should be transparent"); +} + +#[test] +fn test_s_boolean_uses_own_color_and_subtract_xor() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NGon1 = sNGon { + Inputs = { + Sides = Input { Value = 5, }, + Width = Input { Value = 0.5, }, + Height = Input { Value = 0.5, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + Rect1 = sRectangle { + Inputs = { + Width = Input { Value = 0.35, }, + Height = Input { Value = 0.35, }, + ["Translate.X"] = Input { Value = 0.18, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 1.0, }, + Blue = Input { Value = 0.0, }, + }, + }, + BoolSub = sBoolean { + Inputs = { + Operation = Input { Value = FuID { "Subtract" }, }, + Input1 = Input { SourceOp = "Rect1", Source = "Output", }, + Input2 = Input { SourceOp = "NGon1", Source = "Output", }, + }, + }, + BoolXor = sBoolean { + Inputs = { + Operation = Input { Value = FuID { "Xor" }, }, + Input1 = Input { SourceOp = "NGon1", Source = "Output", }, + Input2 = Input { SourceOp = "Rect1", Source = "Output", }, + }, + }, + RSub = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "BoolSub", Source = "Output", }, + }, + }, + RXor = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "BoolXor", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let (tex_sub, _) = eng.evaluate(&comp, comp.find_node("RSub").unwrap(), 0.0); + let (tex_xor, _) = eng.evaluate(&comp, comp.find_node("RXor").unwrap(), 0.0); + let px_sub = eng.readback_rgba(&tex_sub).unwrap(); + let px_xor = eng.readback_rgba(&tex_xor).unwrap(); + + // Far right of Rect (x=0.30 -> px=102, y=64): outside NGon (max x=0.25), inside Rect -> white! + let rect_only = (64 * 128 + 102) * 4; + assert_eq!(&px_sub[rect_only..rect_only + 4], &[255, 255, 255, 255]); + assert_eq!(&px_xor[rect_only..rect_only + 4], &[255, 255, 255, 255]); + + // Overlap region (x=0.10 -> px=77, y=64): subtracted/xored out -> transparent! + let overlap = (64 * 128 + 77) * 4; + assert_eq!(&px_sub[overlap..overlap + 4], &[0, 0, 0, 0]); + assert_eq!(&px_xor[overlap..overlap + 4], &[0, 0, 0, 0]); + + // Center (0,0 -> px=64, y=64): inside NGon, outside Rect (starts at 0.005) -> white in Xor! + let ngon_only = (64 * 128 + 54) * 4; + assert_eq!(&px_xor[ngon_only..ngon_only + 4], &[255, 255, 255, 255]); +} + +#[test] +fn test_s_boolean_operation_names_and_missing_inputs() { + let boolean = |name: &str, op: &str, inputs: &str| { + format!( + r#"{name} = sBoolean {{ Inputs = {{ {op} {inputs} }}, }}, + R{name} = sRender {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, + Input = Input {{ SourceOp = "{name}", Source = "Output", }}, }}, }},"# + ) + }; + let both = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", }, Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; + let first = r#"Input1 = Input { SourceOp = "Rect", Source = "Output", },"#; + let second = r#"Input2 = Input { SourceOp = "Ell", Source = "Output", },"#; + let fu = |v: &str| format!(r#"Operation = Input {{ Value = FuID {{ "{v}" }}, }},"#); + let src = format!( + r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 0 }}, GlobalRange = {{ 0, 0 }}, Tools = ordered() {{ + Rect = sRectangle {{ Inputs = {{ Width = Input {{ Value = 0.5, }}, Height = Input {{ Value = 0.2, }}, + Red = Input {{ Value = 1, }}, Green = Input {{ Value = 0, }}, Blue = Input {{ Value = 0, }}, }}, }}, + Ell = sEllipse {{ Inputs = {{ Width = Input {{ Value = 0.3, }}, Height = Input {{ Value = 0.3, }}, }}, }}, + {} {} {} {} {} {} + }} }}"#, + boolean("Inter", &fu("Intersection"), both), + boolean("Default", "", both), + boolean("Unknown", &fu("Intersect"), both), + boolean("SubFirst", &fu("Subtract"), first), + boolean("SubSecond", &fu("Subtract"), second), + boolean("UnionBoth", &fu("Union"), both), + ); + let comp = Comp::from_fusion_str(&src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { + return; + }; + let mut px = |name: &str, x: usize| { + let (tex, _) = eng.evaluate(&comp, comp.find_node(&format!("R{name}")).unwrap(), 0.0); + let rgba = eng.readback_rgba(&tex).unwrap(); + let i = (64 * 128 + x) * 4; + [rgba[i], rgba[i + 1], rgba[i + 2], rgba[i + 3]] + }; + let white = [255; 4]; + let empty = [0; 4]; + // x=64 is inside both shapes, x=90 is inside only the rectangle. + assert_eq!(px("Inter", 64), white); + assert_eq!(px("Inter", 90), empty); + assert_eq!(px("Default", 64), white, "Operation defaults to Intersection"); + assert_eq!(px("Unknown", 64), empty, "unrecognized operation names render nothing"); + assert_eq!(px("SubFirst", 90), white, "a missing Input2 passes Input1 through in the boolean's own color"); + assert_eq!(px("SubSecond", 64), empty, "a missing Input1 renders nothing"); + assert_eq!(px("UnionBoth", 90), white); +} + +#[test] +fn test_s_grid() { + let src = r#"{ + Tools = ordered() { + El1 = sEllipse { + Inputs = { Width = Input { Value = 0.1, }, Height = Input { Value = 0.1, }, }, + }, + Gr1 = sGrid { + Inputs = { + Input = Input { SourceOp = "El1", Source = "Output", }, + CellsX = Input { Value = 3, }, + CellsY = Input { Value = 3, }, + XOffset = Input { Value = 0.25, }, + YOffset = Input { Value = 0.25, }, + }, + }, + SR1 = sRender { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Input = Input { SourceOp = "Gr1", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return; }; + let (t_sr, _) = eng.evaluate(&comp, comp.find_node("SR1").unwrap(), 0.0); + let px_sr = eng.readback_rgba(&t_sr).unwrap(); + assert_eq!(&px_sr[(32 * 64 + 32) * 4..(32 * 64 + 32) * 4 + 4], &[255, 255, 255, 255]); + assert_eq!(&px_sr[(32 * 64 + 48) * 4..(32 * 64 + 48) * 4 + 4], &[255, 255, 255, 255]); + assert_eq!(&px_sr[0..4], &[0, 0, 0, 0]); +} + +#[test] +fn test_giant_rotated_shapes_clip_instead_of_hanging_and_alpha_stays_unpremultiplied() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + NG = sNGon { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Alpha = Input { Value = 0.25, }, Opacity = Input { Value = 0.5, }, Blue = Input { Value = 0.5, }, }, }, + Rect = sRectangle { Inputs = { Width = Input { Value = 256, }, Height = Input { Value = 256, }, Angle = Input { Value = 33, }, }, }, + SRN = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "NG", Source = "Output", }, }, }, + SRR = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return; }; + let (t, _) = eng.evaluate(&comp, comp.find_node("SRN").unwrap(), 0.0); + let px = eng.readback_rgba(&t).unwrap(); + let mid = (16 * 32 + 16) * 4; + assert_eq!(&px[mid..mid + 4], &[128, 128, 64, 32], "Opacity scales RGBA, Alpha scales alpha only"); + let (t, _) = eng.evaluate(&comp, comp.find_node("SRR").unwrap(), 0.0); + let px = eng.readback_rgba(&t).unwrap(); + assert_eq!(&px[mid..mid + 4], &[255, 255, 255, 255]); + assert_eq!(&px[0..4], &[255, 255, 255, 255], "giant rotated rectangle covers the corner"); +} + +#[test] +fn s_outline_negative_thickness_s_boolean_keep_style_and_s_render_blend() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + R1 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Red = Input { Value = 1.0, }, Green = Input { Value = 0.0, }, Blue = Input { Value = 0.0, }, }, }, + R2 = sRectangle { Inputs = { Width = Input { Value = 0.8, }, Height = Input { Value = 0.8, }, Blue = Input { Value = 1.0, }, }, }, + OutNeg = sOutline { Inputs = { Input = Input { SourceOp = "R1", Source = "Output", }, Thickness = Input { Value = -0.05, }, }, }, + SROutNeg = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Input = Input { SourceOp = "OutNeg", Source = "Output", }, }, }, + BoolKeep = sBoolean { Inputs = { + Input1 = Input { SourceOp = "R1", Source = "Output", }, + Input2 = Input { SourceOp = "R2", Source = "Output", }, + Operation = Input { Value = FuID { "Intersection" }, }, + StyleMode = Input { Value = FuID { "Keep" }, }, + Opacity = Input { Value = 0.2, }, + Green = Input { Value = 1.0, }, + }, }, + SRBool = sRender { Inputs = { Width = Input { Value = 32, }, Height = Input { Value = 32, }, Blend = Input { Value = 0.2, }, Input = Input { SourceOp = "BoolKeep", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).unwrap(); + let Ok(mut eng) = Engine::new_headless() else { return; }; + let (t_out, _) = eng.evaluate(&comp, comp.find_node("SROutNeg").unwrap(), 0.0); + let px_out = eng.readback_rgba(&t_out).unwrap(); + assert!(px_out.iter().all(|&b| b == 0), "negative sOutline thickness should render empty"); + + let (t_bool, _) = eng.evaluate(&comp, comp.find_node("SRBool").unwrap(), 0.0); + let px_bool = eng.readback_rgba(&t_bool).unwrap(); + let mid = (16 * 32 + 16) * 4; + assert_eq!(&px_bool[mid..mid + 4], &[255, 0, 0, 255], "sBoolean Keep preserves Input1 style ignoring Opacity, and sRender ignores Blend"); +} + +#[test] +fn test_s_star_points_depth_rotation_and_outline() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + Star5 = sStar { + Inputs = { + Points = Input { Value = 5, }, + Depth = Input { Value = 0.5, }, + Width = Input { Value = 0.6, }, + Height = Input { Value = 0.6, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.5, }, + Blue = Input { Value = 0.0, }, + }, + }, + StarOutline = sStar { + Inputs = { + NumberOfPoints = Input { Value = 6, }, + Depth = Input { Value = 0.4, }, + Width = Input { Value = 0.6, }, + Height = Input { Value = 0.6, }, + Solid = Input { Value = 0, }, + BorderWidth = Input { Value = 0.04, }, + CornerRadius = Input { Value = 0.02, }, + ZRotation = Input { Value = 30.0, }, + }, + }, + SRFill = sRender { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Input = Input { SourceOp = "Star5", Source = "Output", }, + }, + }, + SROutline = sRender { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Input = Input { SourceOp = "StarOutline", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sStar comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (tf, sf) = eng.evaluate(&comp, comp.find_node("SRFill").unwrap(), 0.0); + assert!(sf.unsupported_nodes.is_empty()); + let pf = eng.readback_rgba(&tf).unwrap(); + let px = |buf: &[u8], x: usize, y: usize| -> [u8; 4] { + let i = (y * 64 + x) * 4; + [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] + }; + // Center (32, 32) is solid orange. + let ctr = px(&pf, 32, 32); + assert!(ctr[0] > 240 && (ctr[1] as i32 - 128).abs() <= 4 && ctr[2] < 5 && ctr[3] == 255, "center={ctr:?}"); + // Rightmost outer tip at +X (r = 0.30 -> x ~ 50, y = 32) is covered! + assert!(px(&pf, 49, 32)[3] > 200, "outer tip at +X must be covered"); + // Opposite -X valley for odd 5-point star is at r = 0.15 (x ~ 22.4): x=24 inside, x=15 outside! + assert!(px(&pf, 24, 32)[3] > 200, "inner valley interior must be covered"); + assert_eq!(px(&pf, 15, 32)[3], 0, "outside -X inner valley must be empty"); + + // Outline mode: hollow center, non-empty stroke ring. + let (to, _) = eng.evaluate(&comp, comp.find_node("SROutline").unwrap(), 0.0); + let po = eng.readback_rgba(&to).unwrap(); + assert_eq!(px(&po, 32, 32)[3], 0, "outline sStar center must be hollow"); + let lit_px = po.chunks_exact(4).filter(|c| c[3] > 127).count(); + assert!(lit_px > 50, "outline sStar should render visible stroke pixels, got {lit_px}"); +} + +#[test] +fn test_s_duplicate_cumulative_transform_and_time_offset() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 10 }, + GlobalRange = { 0, 10 }, + Tools = ordered() { + AnimRed = BezierSpline { + KeyFrames = { + [0] = { 0.0, Flags = { Linear = true } }, + [10] = { 1.0, Flags = { Linear = true } }, + }, + }, + Dot = sRectangle { + Inputs = { + Width = Input { Value = 0.1, }, + Height = Input { Value = 0.1, }, + Red = Input { SourceOp = "AnimRed", Source = "Value", }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 1.0, }, + }, + }, + Dup = sDuplicate { + Inputs = { + Input = Input { SourceOp = "Dot", Source = "Output", }, + Copies = Input { Value = 3, }, + XOffset = Input { Value = 0.2, }, + YOffset = Input { Value = 0.0, }, + XSize = Input { Value = 1.0, }, + YSize = Input { Value = 1.0, }, + ZRotation = Input { Value = 0.0, }, + TimeOffset = Input { Value = 5.0, }, + }, + }, + DupRot = sDuplicate { + Inputs = { + Input = Input { SourceOp = "Dot", Source = "Output", }, + Copies = Input { Value = 4, }, + ZRotation = Input { Value = 90.0, }, + XPivot = Input { Value = 0.2, }, + YPivot = Input { Value = 0.0, }, + }, + }, + SR = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "Dup", Source = "Output", }, + }, + }, + SRRot = sRender { + Inputs = { + Width = Input { Value = 128, }, + Height = Input { Value = 128, }, + Input = Input { SourceOp = "DupRot", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sDuplicate comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (tex, stats) = eng.evaluate(&comp, comp.find_node("SR").unwrap(), 0.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let buf = eng.readback_rgba(&tex).unwrap(); + let sample = |x: usize, y: usize| -> [u8; 4] { + let i = (y * 128 + x) * 4; + [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]] + }; + // Copy 0 at x=0.0 -> px=64 (t=0 -> Red=0, Blue=255) + let c0 = sample(64, 64); + assert!(c0[0] < 5 && c0[2] > 250 && c0[3] == 255, "copy0={c0:?}"); + // Copy 1 at x=+0.2 -> px=90 (t=5 -> Red~128, Blue=255) + let c1 = sample(90, 64); + assert!((c1[0] as i32 - 128).abs() <= 4 && c1[2] > 250 && c1[3] == 255, "copy1={c1:?}"); + // Copy 2 at x=+0.4 -> px=115 (t=10 -> Red=255, Blue=255) + let c2 = sample(115, 64); + assert!(c2[0] > 250 && c2[2] > 250 && c2[3] == 255, "copy2={c2:?}"); + // Left side should remain transparent + assert_eq!(sample(20, 64)[3], 0); + + // Pivot rotation check: copy 0 at (0,0), copy 1 rotated 90 deg CCW around (0.2, 0) -> (0.2, -0.2) -> px=(90, 90) + let (tex_r, _) = eng.evaluate(&comp, comp.find_node("SRRot").unwrap(), 0.0); + let buf_r = eng.readback_rgba(&tex_r).unwrap(); + assert_eq!(buf_r[(64 * 128 + 64) * 4 + 3], 255, "rot copy0 at origin"); + assert_eq!(buf_r[(90 * 128 + 90) * 4 + 3], 255, "rot copy1 at (0.2, -0.2)"); + assert_eq!(buf_r[(64 * 128 + 115) * 4 + 3], 255, "rot copy2 at (0.4, 0.0)"); + assert_eq!(buf_r[(38 * 128 + 90) * 4 + 3], 255, "rot copy3 at (0.2, +0.2)"); +} + +#[test] +fn test_s_jitter_deterministic_seed_smoothness_and_per_shape() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + Rect = sRectangle { + Inputs = { Width = Input { Value = 0.4, }, Height = Input { Value = 0.4, }, }, + }, + JitA = sJitter { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + XAmount = Input { Value = 0.08, }, + YAmount = Input { Value = 0.08, }, + Seed = Input { Value = 7, }, + Smoothness = Input { Value = 0.0, }, + }, + }, + JitB = sJitter { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + XAmount = Input { Value = 0.08, }, + YAmount = Input { Value = 0.08, }, + Seed = Input { Value = 99, }, + Smoothness = Input { Value = 0.0, }, + }, + }, + JitSmooth = sJitter { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + XAmount = Input { Value = 0.08, }, + YAmount = Input { Value = 0.08, }, + Seed = Input { Value = 7, }, + Smoothness = Input { Value = 2.0, }, + }, + }, + SRef = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, + SJA = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitA", Source = "Output", }, }, }, + SJB = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitB", Source = "Output", }, }, }, + SJS = sRender { Inputs = { Width = Input { Value = 96, }, Height = Input { Value = 96, }, Input = Input { SourceOp = "JitSmooth", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sJitter comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (t_ref, _) = eng.evaluate(&comp, comp.find_node("SRef").unwrap(), 0.0); + let (t_a1, s_a) = eng.evaluate(&comp, comp.find_node("SJA").unwrap(), 0.0); + let (t_b, _) = eng.evaluate(&comp, comp.find_node("SJB").unwrap(), 0.0); + let (t_sm, _) = eng.evaluate(&comp, comp.find_node("SJS").unwrap(), 0.0); + assert!(s_a.unsupported_nodes.is_empty()); + + let p_ref = eng.readback_rgba(&t_ref).unwrap(); + let p_a1 = eng.readback_rgba(&t_a1).unwrap(); + let p_b = eng.readback_rgba(&t_b).unwrap(); + let p_sm = eng.readback_rgba(&t_sm).unwrap(); + + assert_ne!(p_ref, p_a1, "sJitter must deform the rectangle"); + assert_ne!(p_a1, p_b, "different Seed must produce different jitter"); + assert_ne!(p_a1, p_sm, "Smoothness > 0 must alter contour jitter"); + + // Re-evaluating with a fresh engine must be bit-identical (deterministic). + let Ok(mut eng2) = Engine::new_headless() else { return }; + let (t_a2, _) = eng2.evaluate(&comp, comp.find_node("SJA").unwrap(), 0.0); + assert_eq!(p_a1, eng2.readback_rgba(&t_a2).unwrap()); +} + +#[test] +fn test_s_expand_inflate_deflate_joins_and_collapse() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + Rect = sRectangle { + Inputs = { Width = Input { Value = 0.3, }, Height = Input { Value = 0.3, }, }, + }, + ExpOut = sExpand { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Amount = Input { Value = 0.1, }, + JoinStyle = Input { Value = 2, }, + }, + }, + ExpBevel = sExpand { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Amount = Input { Value = 0.1, }, + JoinStyle = Input { Value = 0, }, + }, + }, + ExpIn = sExpand { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Distance = Input { Value = -0.075, }, + }, + }, + ExpCollapse = sExpand { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Amount = Input { Value = -0.25, }, + }, + }, + SRef = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "Rect", Source = "Output", }, }, }, + SOut = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpOut", Source = "Output", }, }, }, + SBevel = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpBevel", Source = "Output", }, }, }, + SIn = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpIn", Source = "Output", }, }, }, + SCol = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "ExpCollapse", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sExpand comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let count_lit = |buf: &[u8]| buf.chunks_exact(4).filter(|c| c[3] > 127).count(); + let (t_ref, _) = eng.evaluate(&comp, comp.find_node("SRef").unwrap(), 0.0); + let (t_out, s_out) = eng.evaluate(&comp, comp.find_node("SOut").unwrap(), 0.0); + let (t_bev, _) = eng.evaluate(&comp, comp.find_node("SBevel").unwrap(), 0.0); + let (t_in, _) = eng.evaluate(&comp, comp.find_node("SIn").unwrap(), 0.0); + let (t_col, _) = eng.evaluate(&comp, comp.find_node("SCol").unwrap(), 0.0); + assert!(s_out.unsupported_nodes.is_empty()); + + let lit_ref = count_lit(&eng.readback_rgba(&t_ref).unwrap()); // ~30x30 = 900 + let lit_out = count_lit(&eng.readback_rgba(&t_out).unwrap()); // ~50x50 = 2500 + let lit_bev = count_lit(&eng.readback_rgba(&t_bev).unwrap()); // ~2500 - 4*50 = 2300 + let lit_in = count_lit(&eng.readback_rgba(&t_in).unwrap()); // ~15x15 = 225 + let lit_col = count_lit(&eng.readback_rgba(&t_col).unwrap()); // 0 + + assert!(lit_out > lit_ref * 2, "expanded area should exceed 2x original (ref={lit_ref}, out={lit_out})"); + assert!(lit_bev < lit_out && lit_bev > lit_ref * 2, "bevel join should trim miter corners (bev={lit_bev}, out={lit_out})"); + assert!(lit_in > 100 && lit_in < lit_ref / 2, "deflated area should shrink substantially (ref={lit_ref}, in={lit_in})"); + assert_eq!(lit_col, 0, "over-deflated shape must collapse cleanly to empty"); +} + +#[test] +fn test_s_offset_translate_contour_and_path_position() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + Rect = sRectangle { + Inputs = { Width = Input { Value = 0.2, }, Height = Input { Value = 0.2, }, }, + }, + OffXY = sOffset { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + XOffset = Input { Value = 0.25, }, + YOffset = Input { Value = -0.15, }, + }, + }, + OffContour = sOffset { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Offset = Input { Value = 0.08, }, + }, + }, + OffPos = sOffset { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Position = Input { Value = 0.5, }, + }, + }, + Out0 = sOutline { + Inputs = { + Input = Input { SourceOp = "Rect", Source = "Output", }, + Thickness = Input { Value = 0.04, }, + WriteLength = Input { Value = 0.25, }, + }, + }, + OutShifted = sOutline { + Inputs = { + Input = Input { SourceOp = "OffPos", Source = "Output", }, + Thickness = Input { Value = 0.04, }, + WriteLength = Input { Value = 0.25, }, + }, + }, + SXY = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OffXY", Source = "Output", }, }, }, + SCtr = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OffContour", Source = "Output", }, }, }, + SOut0 = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "Out0", Source = "Output", }, }, }, + SOutS = sRender { Inputs = { Width = Input { Value = 100, }, Height = Input { Value = 100, }, Input = Input { SourceOp = "OutShifted", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sOffset comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (t_xy, s_xy) = eng.evaluate(&comp, comp.find_node("SXY").unwrap(), 0.0); + assert!(s_xy.unsupported_nodes.is_empty()); + let p_xy = eng.readback_rgba(&t_xy).unwrap(); + // Center shifted to (+0.25, -0.15) -> px = (75, 65); origin (50, 50) should be empty. + assert_eq!(p_xy[(65 * 100 + 75) * 4 + 3], 255, "translated rect center must be covered"); + assert_eq!(p_xy[(50 * 100 + 50) * 4 + 3], 0, "original center must be empty"); + + // Scalar Offset inflates 0.2x0.2 -> 0.36x0.36 (~1296 px vs ~400 px). + let (t_ctr, _) = eng.evaluate(&comp, comp.find_node("SCtr").unwrap(), 0.0); + let lit_ctr = eng.readback_rgba(&t_ctr).unwrap().chunks_exact(4).filter(|c| c[3] > 127).count(); + assert!(lit_ctr > 900, "scalar sOffset should expand contour area, got {lit_ctr}"); + + // Position=0.5 shifts the trimmed 25% outline stroke to the opposite side of the contour! + let (t_o0, _) = eng.evaluate(&comp, comp.find_node("SOut0").unwrap(), 0.0); + let (t_os, _) = eng.evaluate(&comp, comp.find_node("SOutS").unwrap(), 0.0); + let p_o0 = eng.readback_rgba(&t_o0).unwrap(); + let p_os = eng.readback_rgba(&t_os).unwrap(); + assert_ne!(p_o0, p_os, "sOffset Position must shift parametric stroke origin along the path"); +} + +#[test] +fn test_s_polygon_closed_open_bezier_and_transform() { + let src = r#"Composition { + CurrentTime = 0, + RenderRange = { 0, 1 }, + GlobalRange = { 0, 1 }, + Tools = ordered() { + PolyClosed = sPolygon { + Inputs = { + Solid = Input { Value = 1, }, + Red = Input { Value = 0.0, }, + Green = Input { Value = 1.0, }, + Blue = Input { Value = 0.0, }, + Scale = Input { Value = 1.5, }, + ["Translate.X"] = Input { Value = 0.05, }, + Polyline = Input { + Value = Polyline { + Closed = true, + Points = { + { Linear = true, X = -0.2, Y = -0.2 }, + { Linear = true, X = 0.2, Y = -0.2 }, + { Linear = true, X = 0.0, Y = 0.2 }, + }, + }, + }, + }, + }, + PolyOpen = sPolygon { + Inputs = { + Solid = Input { Value = 0, }, + BorderWidth = Input { Value = 0.04, }, + Red = Input { Value = 1.0, }, + Green = Input { Value = 0.0, }, + Blue = Input { Value = 0.0, }, + Polyline = Input { + Value = Polyline { + Closed = false, + Points = { + { X = -0.35, Y = 0.0, RX = 0.1, RY = 0.2 }, + { X = 0.35, Y = 0.0, LX = -0.1, LY = 0.2 }, + }, + }, + }, + }, + }, + SRClosed = sRender { + Inputs = { + Width = Input { Value = 100, }, + Height = Input { Value = 100, }, + Input = Input { SourceOp = "PolyClosed", Source = "Output", }, + }, + }, + SROpen = sRender { + Inputs = { + Width = Input { Value = 100, }, + Height = Input { Value = 100, }, + Input = Input { SourceOp = "PolyOpen", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(src).expect("parse sPolygon comp"); + let Ok(mut eng) = Engine::new_headless() else { return }; + + let (t_cl, s_cl) = eng.evaluate(&comp, comp.find_node("SRClosed").unwrap(), 0.0); + assert!(s_cl.unsupported_nodes.is_empty(), "unsupported: {:?}", s_cl.unsupported_nodes); + let p_cl = eng.readback_rgba(&t_cl).unwrap(); + // Triangle shifted by +0.05 -> interior at px=(55, 55) should be solid green. + let i_mid = (55 * 100 + 55) * 4; + assert_eq!(&p_cl[i_mid..i_mid + 4], &[0, 255, 0, 255]); + assert_eq!(&p_cl[0..4], &[0, 0, 0, 0]); + + // Open Bezier arch arcs upward above y=0 (so y=50, x=50 is empty, while upper apex y~35, x=50 is red!). + let (t_op, _) = eng.evaluate(&comp, comp.find_node("SROpen").unwrap(), 0.0); + let p_op = eng.readback_rgba(&t_op).unwrap(); + assert_eq!(p_op[(50 * 100 + 50) * 4 + 3], 0, "open arch chord midpoint must remain hollow"); + 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"); +} diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index 78309e13ca226305d3c61ff24dcc2a38c19a5109..78c01a28cc1d60815cb2e1c7f52563bebab599b7 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -1,8 +1,10 @@ //! Fusion deterministic particle simulation & 2D rendering system. //! //! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`, -//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode). +//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pVortex`, `pFlock`, `pSpawn`, +//! `pChangeStyle`, `pGradientForce`, `pMerge`, and `pRender` (2D mode). +mod forces; mod plan; mod raster; mod sim; @@ -11,10 +13,13 @@ mod tests; pub use plan::collect_bitmap_sources; +use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, HashMap}; +use std::hash::{Hash, Hasher}; use model::{Comp, ExprEngine, NodeId}; +use forces::build_gradient_fields; use plan::{build_particle_plan, particle_subgraph_hash}; use raster::rasterize_particles; use sim::step_simulation; @@ -95,6 +100,14 @@ struct SimState { #[derive(Clone, Copy, Debug)] struct Particle { emitter_hash: u64, + /// Particle set membership bitmask (bit 0 = Set1 .. bit 31 = Set32). + sets: u32, + /// Optional per-particle style override applied by `pChangeStyle` / `pSpawn`. + style_override: Option, + /// Optional NGon sides override (0 = inherit from emitter). + ngon_sides_override: u8, + /// Optional bitmap sprite owner hash override (0 = use `emitter_hash`). + bitmap_owner_hash: u64, pos: [f64; 3], vel: [f64; 3], rot_z: f64, @@ -229,7 +242,19 @@ pub fn render_particles_2d( .clamp(0.0, MAX_SIM_WINDOW as f64) as i64; let sim_origin = base_start.saturating_sub(pre_gen); - let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start); + 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() { + let mut h = DefaultHasher::new(); + subgraph_hash.hash(&mut h); + let mut gf_ids: Vec = gradient_fields.keys().copied().collect(); + gf_ids.sort_by_key(|id| id.0); + for id in gf_ids { + id.0.hash(&mut h); + gradient_fields[&id].content_hash.hash(&mut h); + } + subgraph_hash = h.finish(); + } let key = (rnode.name.clone(), subgraph_hash); // Evict stale subgraph hashes for this render node while keeping other pRender entries. cache @@ -245,7 +270,7 @@ 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, f, expr); + step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); maybe_record_snapshot(cached, f); } cached.current_frame = target_frame; @@ -259,7 +284,7 @@ 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, f, expr); + step_simulation(&mut cached.state, comp, &plan, &gradient_fields, f, expr); maybe_record_snapshot(cached, f); } } @@ -284,7 +309,7 @@ pub fn render_particles_2d( snapshots: BTreeMap::new(), }; for f in sim_start..=target_frame { - step_simulation(&mut sim.state, comp, &plan, f, expr); + step_simulation(&mut sim.state, comp, &plan, &gradient_fields, f, expr); maybe_record_snapshot(&mut sim, f); } cache.entries.insert(key.clone(), sim); diff --git a/crates/engine/src/particles/forces.rs b/crates/engine/src/particles/forces.rs new file mode 100644 index 0000000000000000000000000000000000000000..c35c76fd40a8e29f945b646e03742f8349cd8fae --- /dev/null +++ b/crates/engine/src/particles/forces.rs @@ -0,0 +1,814 @@ +//! Extended 2D particle modifiers & forces: +//! - `pVortex`: tangential swirl + radial inward/outward vortex force +//! - `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering +//! - `pSpawn`: child particle spawning from living parents (capped at `MAX_PARTICLES`) +//! - `pChangeStyle`: color/size/alpha/style modification over life or within a region +//! - `pGradientForce`: spatial luminance-gradient force from a pre-sampled 64x64 image grid + +use std::collections::hash_map::DefaultHasher; +use std::collections::{HashMap, HashSet}; +use std::hash::{Hash, Hasher}; + +use model::{Comp, ExprEngine, Node, NodeId}; + +use super::sim::RegionSpec; +use super::{ + MAX_PARTICLES, Particle, ParticleStyleKind, SplitMix64, SpriteImage, VELOCITY_SCALE, + stable_name_hash, +}; + +/// Resolution of the pre-sampled luminance gradient grid for `pGradientForce`. +const GRAD_GRID_DIM: usize = 64; + +/// Maximum neighbors examined per particle in `pFlock` to guarantee O(N) worst-case runtime +/// even when all particles coincide at a single point. +const FLOCK_MAX_NEIGHBORS: usize = 32; + +/// Force scale constant for `pVortex` (render widths per frame^2 at unit strength and distance). +const VORTEX_FORCE_SCALE: f64 = 1.0e-3; + +/// Pre-sampled 2D spatial luminance gradient field `[dL/du, dL/dv]` in Y-up particle coordinates. +#[derive(Clone, Debug)] +pub(super) struct GradientField { + w: usize, + h: usize, + aspect: f64, + /// Interleaved `[gx, gy]` per grid cell (row 0 = top of image, row `h-1` = bottom). + grads: Vec<[f32; 2]>, + pub(super) content_hash: u64, +} + +impl GradientField { + pub(super) fn from_sprite(sprite: &SpriteImage, channel: &str) -> Option { + 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 None; + } + let gw = sw.min(GRAD_GRID_DIM).max(2); + let gh = sh.min(GRAD_GRID_DIM).max(2); + + let sample_scalar = |px: &[u8]| -> f32 { + let r = px[0] as f32 / 255.0; + let g = px[1] as f32 / 255.0; + let b = px[2] as f32 / 255.0; + let a = px[3] as f32 / 255.0; + match channel { + "Red" | "R" => r, + "Green" | "G" => g, + "Blue" | "B" => b, + "Alpha" | "A" => a, + _ => 0.2126 * r + 0.7152 * g + 0.0722 * b, + } + }; + + // Downsample source image into `gw x gh` scalar luminance grid via box averaging. + let mut luma = vec![0.0_f32; gw * gh]; + for gy in 0..gh { + let y0 = gy * sh / gh; + let y1 = ((gy + 1) * sh / gh).max(y0 + 1).min(sh); + for gx in 0..gw { + let x0 = gx * sw / gw; + let x1 = ((gx + 1) * sw / gw).max(x0 + 1).min(sw); + let mut sum = 0.0_f32; + let mut cnt = 0u32; + // Sample up to a 4x4 stride inside each bin so huge 4K inputs stay instant. + let step_y = ((y1 - y0) / 4).max(1); + let step_x = ((x1 - x0) / 4).max(1); + let mut sy = y0; + while sy < y1 { + let row = sy * sw; + let mut sx = x0; + while sx < x1 { + let off = (row + sx) * 4; + sum += sample_scalar(&sprite.rgba[off..off + 4]); + cnt += 1; + sx += step_x; + } + sy += step_y; + } + luma[gy * gw + gx] = if cnt > 0 { sum / cnt as f32 } else { 0.0 }; + } + } + + // Compute resolution-independent central differences: dL/du (+X right) and dL/dv (+Y up). + let mut grads = vec![[0.0_f32; 2]; gw * gh]; + let mut hasher = DefaultHasher::new(); + gw.hash(&mut hasher); + gh.hash(&mut hasher); + sw.hash(&mut hasher); + sh.hash(&mut hasher); + channel.hash(&mut hasher); + + let scale_x = (gw.saturating_sub(1)) as f32; + let scale_y = (gh.saturating_sub(1)) as f32; + for gy in 0..gh { + let ym = gy.saturating_sub(1); + let yp = (gy + 1).min(gh - 1); + let dy_span = (yp - ym).max(1) as f32; + for gx in 0..gw { + let xm = gx.saturating_sub(1); + let xp = (gx + 1).min(gw - 1); + let dx_span = (xp - xm).max(1) as f32; + + let dl_dx = (luma[gy * gw + xp] - luma[gy * gw + xm]) / dx_span * scale_x; + // Image row 0 is top (+Y in particle space), row gh-1 is bottom (-Y). + let dl_dy = (luma[ym * gw + gx] - luma[yp * gw + gx]) / dy_span * scale_y; + let g = [dl_dx, dl_dy]; + grads[gy * gw + gx] = g; + g[0].to_bits().hash(&mut hasher); + g[1].to_bits().hash(&mut hasher); + } + } + + Some(Self { + w: gw, + h: gh, + aspect: sw as f64 / sh as f64, + grads, + content_hash: hasher.finish(), + }) + } + + /// Bilinearly samples `[dL/du, dL/dv]` at particle world position `(px, py)`. + #[inline] + fn sample(&self, px: f64, py: f64) -> [f64; 2] { + let u = px + 0.5; + let v = 0.5 - py * self.aspect; + if !(-0.05..=1.05).contains(&u) || !(-0.05..=1.05).contains(&v) { + return [0.0, 0.0]; + } + let fx = u.clamp(0.0, 1.0) * (self.w - 1) as f64; + let fy = v.clamp(0.0, 1.0) * (self.h - 1) as f64; + let x0 = (fx.floor() as usize).min(self.w - 1); + let y0 = (fy.floor() as usize).min(self.h - 1); + let x1 = (x0 + 1).min(self.w - 1); + let y1 = (y0 + 1).min(self.h - 1); + let tx = fx - x0 as f64; + let ty = fy - y0 as f64; + + let g00 = self.grads[y0 * self.w + x0]; + let g10 = self.grads[y0 * self.w + x1]; + let g01 = self.grads[y1 * self.w + x0]; + let g11 = self.grads[y1 * self.w + x1]; + + let gx0 = g00[0] as f64 + (g10[0] as f64 - g00[0] as f64) * tx; + let gx1 = g01[0] as f64 + (g11[0] as f64 - g01[0] as f64) * tx; + let gy0 = g00[1] as f64 + (g10[1] as f64 - g00[1] as f64) * tx; + let gy1 = g01[1] as f64 + (g11[1] as f64 - g01[1] as f64) * tx; + [gx0 + (gx1 - gx0) * ty, gy0 + (gy1 - gy0) * ty] + } +} + +pub(super) fn build_gradient_fields( + comp: &Comp, + modifiers: &[(NodeId, HashSet)], + sprites: &HashMap, +) -> HashMap { + let mut fields = HashMap::new(); + for &(mod_id, _) in modifiers { + let Some(node) = comp.nodes.get(mod_id.0) else { + continue; + }; + if node.kind != "pGradientForce" { + continue; + } + let Some(sprite) = sprites.get(&mod_id) else { + continue; + }; + let channel = node.static_str("Channel").unwrap_or("Luma"); + if let Some(field) = GradientField::from_sprite(sprite, channel) { + fields.insert(mod_id, field); + } + } + fields +} + +pub(super) fn parse_particle_style(s: &str) -> Option { + match s { + "ParticleStylePoint" | "Point" => Some(ParticleStyleKind::Point), + "ParticleStyleBlob" | "Blob" => Some(ParticleStyleKind::Blob), + "ParticleStyleNGon" | "NGon" => Some(ParticleStyleKind::NGon), + "ParticleStyleBitmap" | "Bitmap" => Some(ParticleStyleKind::Bitmap), + "ParticleStyleBrush" | "Brush" => Some(ParticleStyleKind::Brush), + _ => None, + } +} + +fn eval_first_num( + comp: &Comp, + node: &Node, + keys: &[&str], + t: f64, + default: f64, + expr: &ExprEngine, +) -> f64 { + for &k in keys { + if node.inputs.contains_key(k) { + return comp.eval_number(node, k, t, default, expr); + } + } + default +} + +/// Reads particle set bitmask from `Set1..=Set32` or integer `Set` (1..=32). +pub(super) fn read_sets_mask(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Option { + let mut mask = 0u32; + let mut any_key = false; + if node.inputs.contains_key("Set") { + any_key = true; + let idx = comp.eval_number(node, "Set", t, 1.0, expr).round() as i32; + if (1..=32).contains(&idx) { + mask |= 1u32 << (idx - 1); + } + } + for key in node.inputs.keys() { + if let Some(rest) = key.strip_prefix("Set") { + if let Ok(idx) = rest.parse::() { + if (1..=32).contains(&idx) { + any_key = true; + if comp.eval_number(node, key, t, 0.0, expr) > 0.5 { + mask |= 1u32 << (idx - 1); + } + } + } + } + } + any_key.then_some(mask) +} + +struct ModifierFilter { + region: RegionSpec, + invert_region: bool, + probability: f64, + start_age: f64, + end_age: f64, + set_mask: Option, + dont_affect_sets: bool, +} + +impl ModifierFilter { + fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { + let region = if node.static_str("Region").is_some() { + RegionSpec::from_node(comp, node, t, expr) + } else { + RegionSpec::All + }; + let invert_region = matches!(node.static_str("RegionMode"), Some("Outside" | "Leaving")); + let probability = comp.eval_number(node, "Probability", t, 1.0, expr).clamp(0.0, 1.0); + let start_age = comp.eval_number(node, "StartAge", t, 0.0, expr).clamp(0.0, 1.0); + let end_age = comp.eval_number(node, "EndAge", t, 1.0, expr).clamp(0.0, 1.0); + let set_mask = if node.kind == "pSpawn" && !node.inputs.contains_key("SetMode") { + None + } else { + read_sets_mask(comp, node, t, expr) + }; + let dont_affect_sets = matches!(node.static_str("SetMode"), Some("DontAffect" | "Don't Affect")); + Self { + region, + invert_region, + probability, + start_age, + end_age, + set_mask, + dont_affect_sets, + } + } + + #[inline] + fn matches(&self, p: &Particle, scope: &HashSet, rng: &mut SplitMix64) -> bool { + if !p.alive || !scope.contains(&p.emitter_hash) { + return false; + } + let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); + if life_frac < self.start_age - 1e-9 || life_frac > self.end_age + 1e-9 { + return false; + } + if let Some(mask) = self.set_mask { + let hit = (p.sets & mask) != 0; + if (!self.dont_affect_sets && !hit) || (self.dont_affect_sets && hit) { + return false; + } + } + let inside = self.region.contains(p.pos); + if (!self.invert_region && !inside) || (self.invert_region && inside) { + return false; + } + if self.probability < 1.0 - 1e-9 && rng.next_f64() > self.probability { + return false; + } + true + } +} + +/// Dispatches `pVortex`, `pFlock`, `pSpawn`, `pChangeStyle`, and `pGradientForce`. +#[allow(clippy::too_many_arguments)] +pub(super) fn apply_extended_modifier( + particles: &mut Vec, + comp: &Comp, + node: &Node, + mod_id: NodeId, + scope: &HashSet, + emitter_nodes: &HashMap, + gradient_fields: &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), + "pChangeStyle" => apply_change_style(particles, comp, node, scope, t, expr), + "pGradientForce" => { + if let Some(field) = gradient_fields.get(&mod_id) { + apply_gradient_force(particles, comp, node, scope, field, t, expr); + } + } + _ => {} + } +} + +/// `pVortex`: tangential swirl + radial spiral force around `Center` / `Translate`. +fn apply_vortex( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let strength = comp.eval_number(node, "Strength", t, 0.1, expr); + if strength.abs() < 1e-12 { + return; + } + let power = comp.eval_number(node, "Power", t, 2.0, expr); + let angle = comp.eval_number(node, "Angle", t, 0.0, expr).to_radians(); + let (sin_a, cos_a) = angle.sin_cos(); + + 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 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 rx = p.pos[0] - cx; + let ry = p.pos[1] - cy; + let dist = (rx * rx + ry * ry).sqrt(); + if dist < 1e-7 { + continue; + } + let inv_d = 1.0 / dist; + let r_hat_x = rx * inv_d; + let r_hat_y = ry * inv_d; + // CCW tangential unit vector around center. + let t_hat_x = -r_hat_y; + let t_hat_y = r_hat_x; + + // Angle = 0 => pure tangential swirl; positive Angle spirals inward; negative spirals outward. + let fx = t_hat_x * cos_a - r_hat_x * sin_a; + let fy = t_hat_y * cos_a - r_hat_y * sin_a; + + let falloff = dist.max(0.02).powf(power); + let mag = (strength * VORTEX_FORCE_SCALE / falloff).clamp(-0.2, 0.2); + p.vel[0] += fx * mag; + p.vel[1] += fy * mag; + } +} + +/// `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering. +fn apply_flock( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + let strength = comp.eval_number(node, "Strength", t, 1.0, expr); + if strength.abs() < 1e-12 { + return; + } + let cohesion = eval_first_num(comp, node, &["Cohesion", "AttractStrength", "CohesionStrength"], t, 0.1, expr); + let separation = eval_first_num(comp, node, &["Separation", "RepelStrength", "SeparationStrength"], t, 0.1, expr); + let alignment = eval_first_num(comp, node, &["Alignment", "AlignStrength", "AlignmentStrength"], t, 0.1, expr); + if cohesion.abs() < 1e-12 && separation.abs() < 1e-12 && alignment.abs() < 1e-12 { + return; + } + + let radius = eval_first_num(comp, node, &["Radius", "InfluenceRadius", "Distance", "AttractDistance"], t, 0.15, expr) + .max(1e-4); + let sep_radius = eval_first_num(comp, node, &["RepelDistance", "SeparationRadius"], t, radius * 0.5, expr) + .clamp(1e-5, radius); + let radius_sq = radius * radius; + let inv_cell = 1.0 / radius.max(0.01); + + 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 mut active: Vec = Vec::new(); + let mut grid: HashMap<(i32, i32), Vec> = HashMap::new(); + + for (idx, p) in particles.iter().enumerate() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + active.push(idx); + let cx = (p.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32; + let cy = (p.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32; + grid.entry((cx, cy)).or_default().push(idx); + } + + if active.len() < 2 { + return; + } + + let mut deltas = vec![[0.0_f64; 3]; active.len()]; + for (slot, &i) in active.iter().enumerate() { + let pi = &particles[i]; + let cx = (pi.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32; + let cy = (pi.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32; + + let mut sum_pos = [0.0_f64; 3]; + let mut sum_vel = [0.0_f64; 3]; + let mut sep_vec = [0.0_f64; 3]; + let mut n_count = 0usize; + let mut sep_count = 0usize; + let mut inspected = 0usize; + + 'cells: for dy in -1..=1 { + for dx in -1..=1 { + let Some(bucket) = grid.get(&(cx + dx, cy + dy)) else { + continue; + }; + for &j in bucket { + if j == i { + continue; + } + inspected += 1; + if inspected > FLOCK_MAX_NEIGHBORS { + break 'cells; + } + let pj = &particles[j]; + let rx = pj.pos[0] - pi.pos[0]; + let ry = pj.pos[1] - pi.pos[1]; + let rz = pj.pos[2] - pi.pos[2]; + let d2 = rx * rx + ry * ry + rz * rz; + if d2 >= radius_sq || d2 <= 1e-12 { + continue; + } + n_count += 1; + sum_pos[0] += pj.pos[0]; + sum_pos[1] += pj.pos[1]; + sum_pos[2] += pj.pos[2]; + sum_vel[0] += pj.vel[0]; + sum_vel[1] += pj.vel[1]; + sum_vel[2] += pj.vel[2]; + + let d = d2.sqrt(); + if d < sep_radius { + let weight = (1.0 - d / sep_radius) / d; + sep_vec[0] -= rx * weight; + sep_vec[1] -= ry * weight; + sep_vec[2] -= rz * weight; + sep_count += 1; + } + } + } + } + + if n_count == 0 { + continue; + } + let inv_n = 1.0 / n_count as f64; + let mut acc = [0.0_f64; 3]; + for a in 0..3 { + let coh = (sum_pos[a] * inv_n - pi.pos[a]) * cohesion * strength * 0.05; + let align = (sum_vel[a] * inv_n - pi.vel[a]) * alignment * strength * 0.2; + let sep = if sep_count > 0 { + (sep_vec[a] / sep_count as f64) * separation * strength * 0.02 + } else { + 0.0 + }; + acc[a] = coh + align + sep; + } + let mag = (acc[0] * acc[0] + acc[1] * acc[1] + acc[2] * acc[2]).sqrt(); + const MAX_FLOCK_ACCEL: f64 = 0.05; + if mag > MAX_FLOCK_ACCEL { + let s = MAX_FLOCK_ACCEL / mag; + acc[0] *= s; + acc[1] *= s; + acc[2] *= s; + } + deltas[slot] = acc; + } + + for (&i, acc) in active.iter().zip(deltas.iter()) { + particles[i].vel[0] += acc[0]; + particles[i].vel[1] += acc[1]; + particles[i].vel[2] += acc[2]; + } +} + +/// `pSpawn`: spawns child particles from living parent particles, respecting `MAX_PARTICLES`. +fn apply_spawn( + particles: &mut Vec, + comp: &Comp, + node: &Node, + scope: &HashSet, + emitter_nodes: &HashMap, + t: f64, + expr: &ExprEngine, +) { + if particles.len() >= MAX_PARTICLES { + return; + } + let number = comp.eval_number(node, "Number", t, 1.0, expr).max(0.0); + let number_var = comp.eval_number(node, "NumberVariance", t, 0.0, expr).max(0.0); + if number <= 1e-9 && number_var <= 1e-9 { + return; + } + + let lifespan_base = comp.eval_number(node, "Lifespan", t, 50.0, expr).max(1.0); + let lifespan_var = comp.eval_number(node, "LifespanVariance", t, 0.0, expr).max(0.0); + let vel_transfer = eval_first_num(comp, node, &["VelocityTransfer", "InheritVelocity"], t, 1.0, expr); + 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 pos_var = comp.eval_number(node, "PositionVariance", 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 has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size"); + let size_base = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0); + let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0); + + let has_r = node.inputs.contains_key("ParticleStyle.Red") || node.inputs.contains_key("Red"); + let has_g = node.inputs.contains_key("ParticleStyle.Green") || node.inputs.contains_key("Green"); + let has_b = node.inputs.contains_key("ParticleStyle.Blue") || node.inputs.contains_key("Blue"); + let has_a = node.inputs.contains_key("ParticleStyle.Alpha") || node.inputs.contains_key("Alpha"); + let col_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let col_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let col_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let col_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + + let explicit_style = node.static_str("Style").and_then(parse_particle_style); + let ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") { + comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr) + .round() + .clamp(3.0, 64.0) as u8 + } else { + 0 + }; + let child_sets = read_sets_mask(comp, node, t, expr); + let spawn_hash = stable_name_hash(&node.name); + let has_spawn_bitmap = node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some(); + + 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 remaining_cap = MAX_PARTICLES.saturating_sub(particles.len()); + let mut spawned: Vec = Vec::new(); + let parent_count = particles.len(); + + for idx in 0..parent_count { + if spawned.len() >= remaining_cap { + break; + } + let parent = particles[idx]; + if !filter.matches(&parent, scope, &mut rng) { + continue; + } + + let rate = (number + rng.signed() * number_var).max(0.0); + let whole = rate.floor() as usize; + let frac = rate - whole as f64; + let count = whole + usize::from(frac > 1e-9 && rng.next_f64() < frac); + if count == 0 { + continue; + } + + // Inherit parent's visual style when `pSpawn` does not explicitly specify `Style`. + let child_style = explicit_style.or(parent.style_override).or_else(|| { + emitter_nodes + .get(&parent.emitter_hash) + .and_then(|id| comp.nodes.get(id.0)) + .and_then(|en| en.static_str("Style")) + .and_then(parse_particle_style) + }); + let child_bitmap_owner = if has_spawn_bitmap { + spawn_hash + } else if explicit_style.is_none() { + if parent.bitmap_owner_hash != 0 { + parent.bitmap_owner_hash + } else { + parent.emitter_hash + } + } else { + 0 + }; + + for _ in 0..count { + if spawned.len() >= remaining_cap { + break; + } + let mut pos = parent.pos; + if pos_var > 0.0 { + pos[0] += rng.signed() * pos_var; + pos[1] += rng.signed() * pos_var; + pos[2] += rng.signed() * pos_var; + } + 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 = [ + parent.vel[0] * vel_transfer + speed * ang.cos() * cos_z, + parent.vel[1] * vel_transfer + speed * ang.sin() * cos_z, + parent.vel[2] * vel_transfer + speed * ang_z.sin(), + ]; + let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0); + let size = if has_size { + (size_base + rng.signed() * size_var).max(0.0) + } else { + parent.size + }; + let color = [ + if has_r { col_r } else { parent.color[0] }, + if has_g { col_g } else { parent.color[1] }, + if has_b { col_b } else { parent.color[2] }, + if has_a { col_a } else { parent.color[3] }, + ]; + spawned.push(Particle { + emitter_hash: spawn_hash, + sets: child_sets.unwrap_or(parent.sets), + style_override: child_style, + ngon_sides_override: if ngon_sides >= 3 { + ngon_sides + } else { + parent.ngon_sides_override + }, + bitmap_owner_hash: child_bitmap_owner, + pos, + vel, + rot_z: rot_z_base + rng.signed() * rot_z_var, + spin_z: spin_z_base + rng.signed() * spin_z_var, + age: 0.0, + lifespan, + size, + color, + alive: true, + }); + } + } + + particles.extend(spawned); +} + +/// `pChangeStyle`: modifies particle color, alpha, size, and style over life or inside a region. +fn apply_change_style( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + t: f64, + expr: &ExprEngine, +) { + 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 has_r = node.inputs.contains_key("ParticleStyle.Red") + || node.inputs.contains_key("Red") + || node.inputs.contains_key("Color.R"); + let has_g = node.inputs.contains_key("ParticleStyle.Green") + || node.inputs.contains_key("Green") + || node.inputs.contains_key("Color.G"); + let has_b = node.inputs.contains_key("ParticleStyle.Blue") + || node.inputs.contains_key("Blue") + || node.inputs.contains_key("Color.B"); + let has_a = node.inputs.contains_key("ParticleStyle.Alpha") + || node.inputs.contains_key("Alpha") + || node.inputs.contains_key("Color.A"); + + let new_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red", "Color.R"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let new_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green", "Color.G"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let new_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue", "Color.B"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + let new_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha", "Color.A"], t, 1.0, expr).clamp(0.0, 1.0) as f32; + + let color_grad = comp + .eval_gradient(node, "ParticleStyle.ColorOverLife", t) + .or_else(|| comp.eval_gradient(node, "Color", t)); + + let has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size"); + let new_size = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0); + let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0); + let size_over_life = node + .inputs + .get("ParticleStyle.SizeOverLife") + .and_then(|b| b.source_op.as_deref()) + .and_then(|src| comp.splines.get(src)); + + let new_style = node.static_str("Style").and_then(parse_particle_style); + let new_ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") { + comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr) + .round() + .clamp(3.0, 64.0) as u8 + } else { + 0 + }; + let bitmap_owner = if node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() { + stable_name_hash(&node.name) + } else { + 0 + }; + + for p in particles.iter_mut() { + if !filter.matches(p, scope, &mut rng) { + continue; + } + let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0); + if has_r { + p.color[0] = new_r; + } + if has_g { + p.color[1] = new_g; + } + if has_b { + p.color[2] = new_b; + } + if has_a { + p.color[3] = new_a; + } + if let Some(ref grad) = color_grad { + let g = grad.sample(life_frac); + p.color[0] = g[0].clamp(0.0, 1.0); + p.color[1] = g[1].clamp(0.0, 1.0); + p.color[2] = g[2].clamp(0.0, 1.0); + p.color[3] = g[3].clamp(0.0, 1.0); + } + if has_size { + let mut s = (new_size + rng.signed() * size_var).max(0.0); + if let Some(sp) = size_over_life { + s *= (2.0 * sp.eval(life_frac)).max(0.0); + } + p.size = s; + } else if let Some(sp) = size_over_life { + p.size = (p.size * (2.0 * sp.eval(life_frac)).max(0.0)).max(0.0); + } + if let Some(st) = new_style { + p.style_override = Some(st); + if st == ParticleStyleKind::NGon && new_ngon_sides >= 3 { + p.ngon_sides_override = new_ngon_sides; + } + if st == ParticleStyleKind::Bitmap && bitmap_owner != 0 { + p.bitmap_owner_hash = bitmap_owner; + } + } + } +} + +/// `pGradientForce`: accelerates particles along the spatial luminance gradient of its input image. +fn apply_gradient_force( + particles: &mut [Particle], + comp: &Comp, + node: &Node, + scope: &HashSet, + field: &GradientField, + t: f64, + expr: &ExprEngine, +) { + let strength = comp.eval_number(node, "Strength", t, 0.1, expr); + if strength.abs() < 1e-12 { + return; + } + let scale = strength * VELOCITY_SCALE * VELOCITY_SCALE; + 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 [gx, gy] = field.sample(p.pos[0], p.pos[1]); + p.vel[0] += (gx * scale).clamp(-0.1, 0.1); + p.vel[1] += (gy * scale).clamp(-0.1, 0.1); + } +} diff --git a/crates/engine/src/particles/plan.rs b/crates/engine/src/particles/plan.rs index d298ed95e4a74a7692f182b7a15e1521676e9935..f0f9d499a0591d32256ca65a89a96497c97845fd 100644 --- a/crates/engine/src/particles/plan.rs +++ b/crates/engine/src/particles/plan.rs @@ -89,12 +89,21 @@ fn collect_bitmap_sources_dfs( return; } - if node.kind == "pEmitter" { + if matches!(node.kind.as_str(), "pEmitter" | "pSpawn" | "pChangeStyle") { if let Some(src_name) = node.connected_node("ParticleStyleBitmap.DropToolsHere") { if let Some(&src_id) = comp.node_by_name.get(src_name) { out.push((node_id, src_id)); } } + } else if node.kind == "pGradientForce" { + for port in ["Image", "Bitmap", "BitmapInput", "GradientImage"] { + 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; + } + } + } } for up_id in particle_stream_inputs(comp, node) { @@ -179,6 +188,13 @@ fn build_plan_dfs( emitter_nodes.insert(emitter_hash, node_id); scope.insert(emitter_hash); } + } else if !node.bypassed && node.kind == "pSpawn" { + // `pSpawn` reads only upstream particle scopes (preventing self-spawning loops), + // then adds its own hash so downstream forces and `pRender` include its children. + modifiers.push((node_id, scope.clone())); + let spawn_hash = stable_name_hash(&node.name); + emitter_nodes.insert(spawn_hash, node_id); + scope.insert(spawn_hash); } else if !node.bypassed && matches!( node.kind.as_str(), @@ -189,8 +205,15 @@ fn build_plan_dfs( | "pFriction" | "pKill" | "pBounce" + | "pVortex" + | "pFlock" + | "pChangeStyle" + | "pGradientForce" ) { + if node.kind == "pChangeStyle" && node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() { + emitter_nodes.insert(stable_name_hash(&node.name), node_id); + } modifiers.push((node_id, scope.clone())); } diff --git a/crates/engine/src/particles/raster.rs b/crates/engine/src/particles/raster.rs index bc13abc85bcf0860c8c6306e40da130d7586327f..d09d785a08bb6b18f9a3c15726c0757c20f96447 100644 --- a/crates/engine/src/particles/raster.rs +++ b/crates/engine/src/particles/raster.rs @@ -285,8 +285,23 @@ pub(super) fn rasterize_particles( let cx = (p.pos[0] * depth_scale + 0.5) * w_f; let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f; - if props.style == ParticleStyleKind::Bitmap { - if let Some((_, nominal)) = props.resolved_sprite() { + let eff_style = p.style_override.unwrap_or(props.style); + let eff_ngon_sides = if p.ngon_sides_override >= 3 { + p.ngon_sides_override as f64 + } else { + props.ngon_sides + }; + + if eff_style == ParticleStyleKind::Bitmap { + let bmp_idx = if p.bitmap_owner_hash != 0 { + props_list + .iter() + .position(|pr| pr.emitter_hash == p.bitmap_owner_hash) + .unwrap_or(props_idx) + } else { + props_idx + }; + if let Some((_, nominal)) = props_list[bmp_idx].resolved_sprite() { let draw_w = size_world * nominal[0] * px_scale; let draw_h = size_world * nominal[1] * px_scale; if draw_w < 0.5 || draw_h < 0.5 { @@ -317,7 +332,7 @@ pub(super) fn rasterize_particles( max_y, color: [cr, cg, cb, ca], shape: DrawShape::Bitmap { - emitter_idx: props_idx, + emitter_idx: bmp_idx, cx, cy, draw_w, @@ -329,7 +344,7 @@ pub(super) fn rasterize_particles( } } - match props.style { + match eff_style { ParticleStyleKind::Point => { let ix = cx.floor() as isize; let iy = cy.floor() as isize; @@ -390,7 +405,7 @@ pub(super) fn rasterize_particles( let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else { continue; }; - let sides = props.ngon_sides; + let sides = eff_ngon_sides; let spike_period = std::f64::consts::TAU / sides; let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); let sharpness = 4.5 * (3.0 / sides).powf(2.8); diff --git a/crates/engine/src/particles/sim.rs b/crates/engine/src/particles/sim.rs index 121ba32d085a1a793e5c91ecfd3634bc3ae830f9..6d65dfd1d0f836e3d1e63add3d636ceeb828678b 100644 --- a/crates/engine/src/particles/sim.rs +++ b/crates/engine/src/particles/sim.rs @@ -1,7 +1,8 @@ -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; -use model::{Comp, ExprEngine, Node}; +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, @@ -13,18 +14,34 @@ pub(super) fn step_simulation( state: &mut SimState, comp: &Comp, plan: &ParticlePlan, + gradient_fields: &HashMap, frame: i64, expr: &ExprEngine, ) { let t = frame as f64; - // 1. Apply forces & kills to existing live particles, then integrate motion and age. + // 1. Apply forces, spawns, style changes & kills to existing live particles, then integrate motion and age. if !state.particles.is_empty() { for (mod_id, scope) in &plan.modifiers { let Some(node) = comp.nodes.get(mod_id.0) else { continue; }; - apply_modifier(&mut state.particles, comp, node, scope, t, expr); + match node.kind.as_str() { + "pVortex" | "pFlock" | "pSpawn" | "pChangeStyle" | "pGradientForce" => { + apply_extended_modifier( + &mut state.particles, + comp, + node, + *mod_id, + scope, + &plan.emitter_nodes, + gradient_fields, + t, + expr, + ); + } + _ => apply_modifier(&mut state.particles, comp, node, scope, t, expr), + } } for p in &mut state.particles { @@ -176,6 +193,7 @@ fn emit_particles( .max(0.0); let region = RegionSpec::from_node(comp, node, t, expr); + let emitter_sets = read_sets_mask(comp, node, t, expr).unwrap_or(1u32); state.particles.reserve(emit_count); for _ in 0..emit_count { @@ -219,6 +237,10 @@ fn emit_particles( state.particles.push(Particle { emitter_hash, + sets: emitter_sets, + style_override: None, + ngon_sides_override: 0, + bitmap_owner_hash: 0, pos, vel, rot_z, @@ -366,7 +388,7 @@ impl RegionSpec { } } - fn contains(&self, p: [f64; 3]) -> bool { + pub(super) fn contains(&self, p: [f64; 3]) -> bool { match *self { Self::All => true, Self::Point { center } => { diff --git a/crates/engine/src/particles/tests.rs b/crates/engine/src/particles/tests.rs index 62e5f8d40c81208e682ca73bdae0788dbdb39e75..92f10002c3f5e9137f6ca2b6c64191b6d971b05e 100644 --- a/crates/engine/src/particles/tests.rs +++ b/crates/engine/src/particles/tests.rs @@ -263,8 +263,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(); for f in 0..=4 { - step_simulation(&mut state, &comp, &plan, f, &expr); + step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); } let first = state.particles.first().expect("particle emitted"); let init_vx = 0.1 * (-60.0_f64).to_radians().cos(); @@ -629,3 +630,475 @@ Composition { let img = render_particles_2d(&mut cache, &comp, pr, 5.0, [64, 64], &expr, &sprites); assert_eq!(img.len(), 64 * 64 * 4); } + +#[test] +fn test_p_vortex_swirl_and_spiral_angle() { + let make_comp = |angle: f64| { + format!( + r#"Composition {{ + GlobalRange = {{ 0, 20 }}, + RenderRange = {{ 0, 20 }}, + 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.2, }}, + ["Point.Translate.Y"] = Input {{ Value = 0.0, }}, + Style = Input {{ Value = FuID {{ "ParticleStyleBlob" }}, }}, + ["ParticleStyle.Size"] = Input {{ Value = 0.5, }}, + }}, + }}, + V = pVortex {{ + Inputs = {{ + Input = Input {{ SourceOp = "E", Source = "Output", }}, + Strength = Input {{ Value = 1.0, }}, + Power = Input {{ Value = 1.0, }}, + Angle = Input {{ Value = {angle}, }}, + ["Translate.X"] = Input {{ Value = 0.0, }}, + ["Translate.Y"] = Input {{ Value = 0.0, }}, + }}, + }}, + R = pRender {{ + Inputs = {{ Input = Input {{ SourceOp = "V", Source = "Output", }}, }}, + }}, + }}, + }}"# + ) + }; + + let expr = ExprEngine::new(); + let empty_fields = 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); + } + 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); + + // Angle = +60: inward spiral -> radius shrinks relative to initial 0.2. + let comp_in = Comp::from_fusion_str(&make_comp(60.0)).unwrap(); + 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); + } + 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}"); + + // Angle = -60: outward spiral -> radius grows relative to initial 0.2. + let comp_out = Comp::from_fusion_str(&make_comp(-60.0)).unwrap(); + 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); + } + 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}"); +} + +#[test] +fn test_p_flock_cohesion_separation_alignment_and_perf() { + let comp_src = r#"Composition { + GlobalRange = { 0, 20 }, + RenderRange = { 0, 20 }, + Tools = ordered() { + EN = BezierSpline { + KeyFrames = { + [0] = { 1, Flags = { Linear = true } }, + [1] = { 0, Flags = { Linear = true } }, + }, + }, + E1 = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = -0.08, }, + Velocity = Input { Value = 0.0, }, + }, + }, + E2 = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 50, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.08, }, + Velocity = Input { Value = 0.2, }, + Angle = Input { Value = 90.0, }, + }, + }, + M = pMerge { + Inputs = { + Input1 = Input { SourceOp = "E1", Source = "Output", }, + Input2 = Input { SourceOp = "E2", Source = "Output", }, + }, + }, + FlockCoh = pFlock { + Inputs = { + Input = Input { SourceOp = "M", Source = "Output", }, + Cohesion = Input { Value = 1.0, }, + Separation = Input { Value = 0.0, }, + Alignment = Input { Value = 1.0, }, + Radius = Input { Value = 0.3, }, + Strength = Input { Value = 1.0, }, + }, + }, + FlockSep = pFlock { + Inputs = { + Input = Input { SourceOp = "M", Source = "Output", }, + Cohesion = Input { Value = 0.0, }, + Separation = Input { Value = 1.0, }, + Alignment = Input { Value = 0.0, }, + Radius = Input { Value = 0.4, }, + Strength = Input { Value = 1.0, }, + }, + }, + RCoh = pRender { Inputs = { Input = Input { SourceOp = "FlockCoh", Source = "Output", }, }, }, + RSep = pRender { Inputs = { Input = Input { SourceOp = "FlockSep", Source = "Output", }, }, }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let expr = ExprEngine::new(); + let empty_fields = 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); + } + 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}"); + assert!(state_coh.particles[0].vel[1] > 0.002, "alignment should pull stationary particle toward neighbor +Y vel"); + + // Separation: particles within repel radius push farther apart. + 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); + } + 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}"); + + // Stress check: 2,000 overlapping particles must step quickly without O(N^2) stall. + let heavy_src = r#"Composition { + GlobalRange = { 0, 5 }, + RenderRange = { 0, 5 }, + Tools = ordered() { + E = pEmitter { + Inputs = { + Number = Input { Value = 1000, }, + Lifespan = Input { Value = 20, }, + }, + }, + F = pFlock { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + Radius = Input { Value = 0.2, }, + }, + }, + R = pRender { Inputs = { Input = Input { SourceOp = "F", Source = "Output", }, }, }, + }, + }"#; + let heavy_comp = Comp::from_fusion_str(heavy_src).unwrap(); + let heavy_plan = build_particle_plan(&heavy_comp, heavy_comp.node_by_name["R"]); + 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); + } + assert!(heavy_state.particles.len() >= 2000); + assert!( + t0.elapsed() < std::time::Duration::from_secs(2), + "pFlock on 2000+ overlapping particles took too long: {:?}", + t0.elapsed() + ); +} + +#[test] +fn test_p_spawn_children_velocity_transfer_and_cap() { + let comp_src = r#"Composition { + GlobalRange = { 0, 20 }, + RenderRange = { 0, 20 }, + 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 = 20, }, + Velocity = Input { Value = 0.5, }, + Angle = Input { Value = 0.0, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 0.6, }, + ["ParticleStyle.Red"] = Input { Value = 1.0, }, + ["ParticleStyle.Green"] = Input { Value = 0.0, }, + ["ParticleStyle.Blue"] = Input { Value = 0.0, }, + }, + }, + S = pSpawn { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + Number = Input { Value = 3, }, + Lifespan = Input { Value = 10, }, + VelocityTransfer = Input { Value = 0.5, }, + Velocity = Input { Value = 0.2, }, + Angle = Input { Value = 90.0, }, + Set = Input { Value = 2, }, + Style = Input { Value = FuID { "ParticleStyleNGon" }, }, + ["ParticleStyle.Red"] = Input { Value = 0.0, }, + ["ParticleStyle.Green"] = Input { Value = 1.0, }, + ["ParticleStyle.Blue"] = Input { Value = 0.0, }, + }, + }, + R = pRender { + Inputs = { Input = Input { SourceOp = "S", 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 mut state = SimState::default(); + + // 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. + for f in 0..=2 { + step_simulation(&mut state, &comp, &plan, &empty_fields, f, &expr); + } + assert_eq!(state.particles.len(), 14, "expected 2 parents + 12 non-recursive children"); + + let spawn_hash = stable_name_hash("S"); + let children: Vec<_> = state.particles.iter().filter(|p| p.emitter_hash == spawn_hash).collect(); + assert_eq!(children.len(), 12); + for ch in &children { + assert_eq!(ch.sets, 1u32 << 1, "child should be assigned to Set 2"); + assert_eq!(ch.style_override, Some(ParticleStyleKind::NGon)); + assert!((ch.vel[0] - 0.025).abs() < 1e-6, "VelocityTransfer=0.5 of vx=0.05 -> 0.025, got {}", ch.vel[0]); + assert!((ch.vel[1] - 0.02).abs() < 1e-6, "Velocity=0.2 at Angle=90 -> vy=0.02, got {}", ch.vel[1]); + assert!((ch.color[1] - 1.0).abs() < 1e-5 && ch.color[0] < 1e-5); + } + + // Verify rendering includes both parents and children. + let mut cache = ParticleCache::default(); + let img = render_particles_2d(&mut cache, &comp, render_id, 3.0, [128, 128], &expr, &HashMap::new()); + let green_px = img.chunks_exact(4).filter(|c| c[1] > 40 && c[0] < 10 && c[3] > 20).count(); + assert!(green_px > 10, "spawned green child particles must render visibly, got {green_px}"); +} + +#[test] +fn test_p_change_style_color_size_style_and_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 } }, + }, + }, + E_in = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 20, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = -0.2, }, + Style = Input { Value = FuID { "ParticleStylePoint" }, }, + ["ParticleStyle.Size"] = Input { Value = 0.2, }, + ["ParticleStyle.Red"] = Input { Value = 1.0, }, + ["ParticleStyle.Green"] = Input { Value = 0.0, }, + ["ParticleStyle.Blue"] = Input { Value = 0.0, }, + }, + }, + E_out = pEmitter { + Inputs = { + Number = Input { SourceOp = "EN", Source = "Value", }, + Lifespan = Input { Value = 20, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.25, }, + Style = Input { Value = FuID { "ParticleStylePoint" }, }, + ["ParticleStyle.Size"] = Input { Value = 0.2, }, + ["ParticleStyle.Red"] = Input { Value = 1.0, }, + ["ParticleStyle.Green"] = Input { Value = 0.0, }, + ["ParticleStyle.Blue"] = Input { Value = 0.0, }, + }, + }, + M = pMerge { + Inputs = { + Input1 = Input { SourceOp = "E_in", Source = "Output", }, + Input2 = Input { SourceOp = "E_out", Source = "Output", }, + }, + }, + CS = pChangeStyle { + Inputs = { + Input = Input { SourceOp = "M", Source = "Output", }, + Region = Input { Value = FuID { "SphereRgn" }, }, + ["SphereRgn.Translate.X"] = Input { Value = -0.2, }, + ["SphereRgn.Size"] = Input { Value = 0.2, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 1.5, }, + ["ParticleStyle.Red"] = Input { Value = 0.0, }, + ["ParticleStyle.Green"] = Input { Value = 0.0, }, + ["ParticleStyle.Blue"] = Input { Value = 1.0, }, + Probability = Input { Value = 1.0, }, + }, + }, + R = pRender { + Inputs = { Input = Input { SourceOp = "CS", 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 mut state = SimState::default(); + for f in 0..=2 { + step_simulation(&mut state, &comp, &plan, &empty_fields, f, &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(); + + assert_eq!(p_in.style_override, Some(ParticleStyleKind::Blob)); + assert!((p_in.size - 1.5).abs() < 1e-6); + assert!(p_in.color[2] > 0.99 && p_in.color[0] < 0.01); + + assert_eq!(p_out.style_override, None, "particle outside Region must keep original style"); + assert!((p_out.size - 0.2).abs() < 1e-6); + assert!(p_out.color[0] > 0.99 && p_out.color[2] < 0.01); + + // Rendered buffer must have a large blue blob on the left and a tiny red point on the right. + let mut cache = ParticleCache::default(); + let img = render_particles_2d(&mut cache, &comp, render_id, 2.0, [100, 100], &expr, &HashMap::new()); + let blue_px = img.chunks_exact(4).filter(|c| c[2] > 40 && c[0] < 10 && c[3] > 20).count(); + let red_px = img.chunks_exact(4).filter(|c| c[0] > 40 && c[2] < 10 && c[3] > 20).count(); + assert!(blue_px > 20, "changed particle must render as a large blue blob, got {blue_px}"); + assert_eq!(red_px, 1, "unchanged particle must remain a 1px red point, got {red_px}"); +} + +#[test] +fn test_p_gradient_force_luma_gradient_and_gpu_eval() { + let comp_src = r#"Composition { + GlobalRange = { 0, 10 }, + RenderRange = { 0, 10 }, + Tools = ordered() { + RampBG = Background { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Type = Input { Value = FuID { "Horizontal" }, }, + TopLeftRed = Input { Value = 0.0, }, + TopLeftGreen = Input { Value = 0.0, }, + TopLeftBlue = Input { Value = 0.0, }, + TopRightRed = Input { Value = 1.0, }, + TopRightGreen = Input { Value = 1.0, }, + TopRightBlue = Input { Value = 1.0, }, + }, + }, + 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 = 30, }, + Region = Input { Value = FuID { "Point" }, }, + ["Point.Translate.X"] = Input { Value = 0.0, }, + ["Point.Translate.Y"] = Input { Value = 0.0, }, + Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 1.0, }, + }, + }, + GF = pGradientForce { + Inputs = { + Input = Input { SourceOp = "E", Source = "Output", }, + Image = Input { SourceOp = "RampBG", Source = "Output", }, + Strength = Input { Value = 1.0, }, + }, + }, + R = pRender { + Inputs = { + Width = Input { Value = 64, }, + Height = Input { Value = 64, }, + Input = Input { SourceOp = "GF", Source = "Output", }, + }, + }, + }, + }"#; + let comp = Comp::from_fusion_str(comp_src).unwrap(); + let render_id = comp.node_by_name["R"]; + let gf_id = comp.node_by_name["GF"]; + let bg_id = comp.node_by_name["RampBG"]; + + // 1. Verify bitmap/image source discovery for pGradientForce. + let sources = collect_bitmap_sources(&comp, render_id); + assert_eq!(sources, vec![(gf_id, bg_id)]); + + // 2. Build a synthetic left-to-right linear ramp sprite and verify rightward acceleration. + let mut ramp_rgba = vec![0u8; 64 * 64 * 4]; + for y in 0..64 { + for x in 0..64 { + let v = (x * 255 / 63) as u8; + let off = (y * 64 + x) * 4; + ramp_rgba[off] = v; + ramp_rgba[off + 1] = v; + ramp_rgba[off + 2] = v; + ramp_rgba[off + 3] = 255; + } + } + let mut sprites = HashMap::new(); + sprites.insert(gf_id, SpriteImage { size: [64, 64], rgba: ramp_rgba }); + + let plan = build_particle_plan(&comp, render_id); + let fields = super::forces::build_gradient_fields(&comp, &plan.modifiers, &sprites); + let expr = ExprEngine::new(); + let mut state = SimState::default(); + for f in 0..=4 { + step_simulation(&mut state, &comp, &plan, &fields, f, &expr); + } + let p = state.particles[0]; + assert!(p.vel[0] > 0.02, "left-to-right bright ramp must push particle +X, got {:?}", p.vel); + assert!(p.vel[1].abs() < 1e-4, "horizontal ramp must have near-zero Y force, got {}", p.vel[1]); + assert!(p.pos[0] > 0.05, "particle should move significantly right, got x={}", p.pos[0]); + + // 3. End-to-end GPU evaluation of RampBG -> pGradientForce -> pRender. + let Ok(mut eng) = crate::Engine::new_headless() else { return }; + let (tex, stats) = eng.evaluate(&comp, render_id, 5.0); + assert!(stats.unsupported_nodes.is_empty(), "unsupported: {:?}", stats.unsupported_nodes); + let px = eng.readback_rgba(&tex).unwrap(); + let px_ref = px.as_slice(); + // Particle started at x=32 and moved right into the right half (x > 36). + let right_mass: u64 = (0..64) + .flat_map(|y| (36..64).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) + .sum(); + let left_mass: u64 = (0..64) + .flat_map(|y| (0..28).map(move |x| px_ref[(y * 64 + x) * 4 + 3] as u64)) + .sum(); + assert!( + right_mass > left_mass * 4 + 100, + "GPU pGradientForce should push particle into right half (left={left_mass}, right={right_mass})" + ); +}