From 70d3b873a073d0d88aeca1b79cee99b90743ea4a Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 18:34:12 -0800 Subject: [PATCH] Calibrate pEmitter and pRender particle system parity against Fusion 21.1 (#39) Black-box probes on Fusion 21.1 (probes/w5_39) pin down the particle model: - Point style is a single pixel; Blob is exp(-r^2/2s^2) with s = 3.316 * Size px; NGon is a spiked star; Bitmap width is Size * sprite pixels (not render width). - Velocity moves 0.1 widths/frame, force acceleration is 0.01 * Strength (directional) and 1e-4 * Strength / d^Power (point); newborns integrate once on their birth frame. - pFriction multiplies velocity by 1 - friction (default 0.05), including on birth. - FadeOut is the life fraction at which the fade-out begins. - Default region is SphereRgn of diameter 0.1; Cube/Rect default extents 0.1. - Particles project through a 35mm/36mm film-back camera, so z scales screen position. - Sub-16px Background sprites use their nominal size and flat color. Assisted-by: claude-sonnet-5.5 --- crates/engine/src/particles.rs | 469 +++++++++++++++++++++++++-------- 1 file changed, 352 insertions(+), 117 deletions(-) diff --git a/crates/engine/src/particles.rs b/crates/engine/src/particles.rs index 2defbb5d9367f40859c3c68fbdac1702f311910b..b56128e809036837b28115b8a3a6105a70acbe72 100644 --- a/crates/engine/src/particles.rs +++ b/crates/engine/src/particles.rs @@ -14,13 +14,18 @@ const MAX_PARTICLES: usize = 20_000; /// Maximum lookback frames from `target_frame` when `sim_start` is far earlier. const MAX_SIM_WINDOW: i64 = 600; -/// Fusion internal acceleration scale for `pPointForce`. -/// Matches Fusion Studio's particle-space scaling where `Strength = -2..-4` -/// gently disperses particles over ~85-100 frames in `[-0.5, +0.5]` space. -const POINT_FORCE_SCALE: f64 = 2.0e-5; +/// Particle integration step: `Velocity` moves `0.1` render widths per frame and +/// forces accelerate by `0.1^2` per unit of `Strength`. +const VELOCITY_SCALE: f64 = 0.1; -/// Fusion internal acceleration scale for `pDirectionalForce`. -const DIRECTIONAL_FORCE_SCALE: f64 = 2.0e-3; +/// `pPointForce` acceleration is `Strength * 1e-4 / distance^Power` (render widths per frame^2). +const POINT_FORCE_SCALE: f64 = 1.0e-4; + +/// Default render camera distance in render widths (35mm lens on a 36mm film back). +const CAMERA_DISTANCE: f64 = 35.0 / 36.0; + +/// Blob particle falloff is `exp(-r^2 / (2 sigma^2))` with `sigma = BLOB_SIGMA_PER_SIZE * Size` pixels. +const BLOB_SIGMA_PER_SIZE: f64 = 3.316; /// Fusion internal acceleration scale for `pTurbulence`. const TURBULENCE_SCALE: f64 = 2.0e-3; @@ -79,7 +84,9 @@ struct Particle { enum ParticleStyleKind { Point, Blob, + NGon, Bitmap, + Brush, } /// Deterministic SplitMix64 PRNG. @@ -389,9 +396,11 @@ pub fn render_particles_2d( return out; }; + let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0); rasterize_particles( &mut out, dims, + dims[0] as f64 / render_width, comp, &cached.state.particles, time, @@ -437,6 +446,7 @@ fn step_simulation( } // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region). + let first_new = state.particles.len(); for &emitter_id in &plan.emitters { if state.particles.len() >= MAX_PARTICLES { break; @@ -446,6 +456,23 @@ fn step_simulation( }; emit_particles(state, comp, node, emitter_id, frame, t, expr); } + + // A newborn is damped by friction and then integrated once on its birth frame; other forces + // only start acting next frame. + for (mod_id, scope) in &plan.modifiers { + let Some(node) = comp.nodes.get(mod_id.0) else { + continue; + }; + if matches!(node.kind.as_str(), "pDrag" | "pFriction") { + apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr); + } + } + for p in &mut state.particles[first_new..] { + for axis in 0..3 { + p.pos[axis] += p.vel[axis]; + } + p.rot_z += p.spin_z; + } } fn emit_particles( @@ -525,7 +552,7 @@ fn emit_particles( let a_hi = (base_a + comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr)).clamp(0.0, 1.0); let size_base = comp - .eval_number(node, "ParticleStyle.Size", t, 0.1, expr) + .eval_number(node, "ParticleStyle.Size", t, 1.0, expr) .max(0.0); let size_var = comp .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr) @@ -541,7 +568,7 @@ fn emit_particles( pos[2] += rng.signed() * pos_var; } - let speed = vel_base + rng.signed() * vel_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(); @@ -616,7 +643,7 @@ enum RegionSpec { impl RegionSpec { fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self { - let region_name = node.static_str("Region").unwrap_or("Point"); + let region_name = node.static_str("Region").unwrap_or("SphereRgn"); match region_name { "RectRgn" => Self::Rect { center: [ @@ -624,8 +651,8 @@ impl RegionSpec { comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr), comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr), ], - width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(), - height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(), + width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), }, "SphereRgn" => Self::Sphere { center: [ @@ -633,7 +660,7 @@ impl RegionSpec { comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr), comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr), ], - radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5, + radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5, }, "CubeRgn" => Self::Cube { center: [ @@ -641,9 +668,9 @@ impl RegionSpec { comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr), comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr), ], - width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(), - height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(), - depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(), + width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), + depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), }, "LineRgn" => { let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr); @@ -790,8 +817,8 @@ impl RegionSpec { comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr), comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr), ], - width: comp.eval_number(node, "RectRgn.Width", t, 0.5, expr).abs(), - height: comp.eval_number(node, "RectRgn.Height", t, 0.5, expr).abs(), + width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(), }, Some("SphereRgn") => Self::Sphere { center: [ @@ -807,9 +834,9 @@ impl RegionSpec { comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr), comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr), ], - width: comp.eval_number(node, "CubeRgn.Width", t, 0.5, expr).abs(), - height: comp.eval_number(node, "CubeRgn.Height", t, 0.5, expr).abs(), - depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.5, expr).abs(), + width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(), + height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(), + depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(), }, Some("LineRgn") => { let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr); @@ -1067,7 +1094,7 @@ fn apply_modifier( if dist < 1e-7 { continue; } - let falloff = dist.max(0.05).powf(power); + let falloff = dist.max(0.005).powf(power); let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25); let inv_d = 1.0 / dist; p.vel[0] += dx * inv_d * mag; @@ -1086,7 +1113,7 @@ fn apply_modifier( let dir_z = comp .eval_number(node, "DirectionZ", t, 0.0, expr) .to_radians(); - let mag = strength * DIRECTIONAL_FORCE_SCALE; + let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE; let ax = mag * dir.cos() * dir_z.cos(); let ay = mag * dir.sin() * dir_z.cos(); let az = mag * dir_z.sin(); @@ -1101,13 +1128,17 @@ fn apply_modifier( } } "pDrag" | "pFriction" => { - let drag = if node.kind == "pFriction" { - comp.eval_number(node, "VelocityFriction", t, 0.1, expr) + let damp = if node.kind == "pFriction" { + 1.0 - comp.eval_number(node, "VelocityFriction", t, 0.05, expr) } else { - comp.eval_number(node, "Drag", t, 0.1, expr) + 1.0 - comp.eval_number(node, "Drag", t, 0.05, expr) } - .max(0.0); - let damp = (-drag).exp(); + .clamp(0.0, 1.0); + let spin_damp = if node.kind == "pFriction" { + 1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr).clamp(0.0, 1.0) + } else { + 1.0 + }; for p in particles.iter_mut() { if !p.alive || !scope.contains(&p.emitter_id) { continue; @@ -1115,6 +1146,7 @@ fn apply_modifier( p.vel[0] *= damp; p.vel[1] *= damp; p.vel[2] *= damp; + p.spin_z *= spin_damp; } } "pTurbulence" => { @@ -1258,6 +1290,8 @@ fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 { struct EmitterRenderProps<'a> { style: ParticleStyleKind, + tiny_sprite: Option<([f64; 2], SpriteImage)>, + ngon_sides: f64, size_over_life: Option<&'a model::BezierSpline>, fade_in: f64, fade_out: f64, @@ -1281,6 +1315,8 @@ fn collect_emitter_render_props<'a>( let style = match node.static_str("Style") { Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap, Some("ParticleStyleBlob") => ParticleStyleKind::Blob, + Some("ParticleStyleNGon") => ParticleStyleKind::NGon, + Some("ParticleStyleBrush") => ParticleStyleKind::Brush, _ => ParticleStyleKind::Point, }; let size_over_life = node @@ -1292,7 +1328,7 @@ fn collect_emitter_render_props<'a>( .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr) .clamp(0.0, 1.0); let fade_out = comp - .eval_number(node, "ParticleStyle.FadeOut", time, 0.0, expr) + .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr) .clamp(0.0, 1.0); let color_over_life_on = comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr) > 0.5; @@ -1305,6 +1341,8 @@ fn collect_emitter_render_props<'a>( p.emitter_id, EmitterRenderProps { style, + tiny_sprite: tiny_background_sprite(comp, node, time, expr), + ngon_sides: comp.eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr).round().max(3.0), size_over_life, fade_in, fade_out, @@ -1315,9 +1353,42 @@ fn collect_emitter_render_props<'a>( map } +/// Solid sprite for a `Background` tool narrower than 16 px. +/// +/// The engine evaluates such tools at comp size, so the particle uses the tool's nominal +/// `Width`/`Height` and its flat color directly. +fn tiny_background_sprite( + comp: &Comp, + emitter: &Node, + t: f64, + expr: &ExprEngine, +) -> Option<([f64; 2], SpriteImage)> { + let src = emitter + .connected_node("ParticleStyleBitmap.DropToolsHere") + .and_then(|name| comp.find_node(name)) + .map(|id| &comp.nodes[id.0]) + .filter(|n| n.kind == "Background")?; + let w = comp.eval_number(src, "Width", t, 0.0, expr); + let h = comp.eval_number(src, "Height", t, 0.0, expr); + if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) { + return None; + } + let channel = |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0); + let a = channel("TopLeftAlpha", 1.0); + let px = |c: f64| (c * a * 255.0 + 0.5) as u8; + let rgba = vec![ + px(channel("TopLeftRed", 0.0)), + px(channel("TopLeftGreen", 0.0)), + px(channel("TopLeftBlue", 0.0)), + (a * 255.0 + 0.5) as u8, + ]; + Some(([w, h], SpriteImage { size: [1, 1], rgba })) +} + fn rasterize_particles( out: &mut [u8], dims: [u32; 2], + px_scale: f64, comp: &Comp, particles: &[Particle], time: f64, @@ -1351,7 +1422,11 @@ fn rasterize_particles( .size_over_life .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0)) .unwrap_or(1.0); - let size_world = p.size * size_mult; + let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]); + if !(depth_scale > 0.0) { + continue; + } + let size_world = p.size * size_mult * depth_scale; if size_world <= 1e-6 { continue; } @@ -1360,8 +1435,8 @@ fn rasterize_particles( if props.fade_in > 1e-6 && life_frac < props.fade_in { fade *= life_frac / props.fade_in; } - if props.fade_out > 1e-6 && life_frac > (1.0 - props.fade_out) { - fade *= ((1.0 - life_frac) / props.fade_out).max(0.0); + if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out { + fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0); } let mut cr = p.color[0]; @@ -1381,45 +1456,63 @@ fn rasterize_particles( } // Fusion 2D particle coordinates: X in [-0.5, +0.5], Y-up with same unit scale as X. - let cx = (p.pos[0] + 0.5) * w_f; - let cy = h_f * 0.5 - p.pos[1] * w_f; + 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(sprite) = sprites.get(&p.emitter_id) { - if sprite.size[0] > 0 - && sprite.size[1] > 0 - && sprite.rgba.len() - >= (sprite.size[0] as usize) - .saturating_mul(sprite.size[1] as usize) - .saturating_mul(4) - { - draw_bitmap_particle( - &mut accum, - w, - h, - cx, - cy, - size_world * w_f, - p.rot_z, - [cr, cg, cb, ca], - sprite, - ); - continue; + let (sprite, nominal) = match &props.tiny_sprite { + Some((nominal, sprite)) => (Some(sprite), *nominal), + None => { + let sprite = sprites.get(&p.emitter_id); + (sprite, sprite.map_or([0.0; 2], |s| [s.size[0] as f64, s.size[1] as f64])) } + }; + if let Some(sprite) = sprite.filter(|s| { + s.size[0] > 0 + && s.size[1] > 0 + && s.rgba.len() >= (s.size[0] as usize).saturating_mul(s.size[1] as usize).saturating_mul(4) + }) { + draw_bitmap_particle( + &mut accum, + w, + h, + cx, + cy, + size_world * nominal[0] * px_scale, + size_world * nominal[1] * px_scale, + p.rot_z, + [cr, cg, cb, ca], + sprite, + ); + continue; } } - let is_blob = props.style == ParticleStyleKind::Blob; - draw_radial_particle( - &mut accum, - w, - h, - cx, - cy, - (size_world * w_f * 0.5).max(0.75), - [cr, cg, cb, ca], - is_blob, - ); + match props.style { + ParticleStyleKind::Point => { + blend_pixel(&mut accum, w, h, cx.floor(), cy.floor(), [cr, cg, cb, ca]); + } + ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |_, _| 1.0); + } + ParticleStyleKind::NGon => { + let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale; + let sides = props.ngon_sides; + let spike_period = std::f64::consts::TAU / sides; + let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians(); + // Spike sharpness fitted to Fusion 21.1: alpha mass is 0.18/0.48/0.78 of a blob for 3/5/8 sides. + let sharpness = 4.5 * (3.0 / sides).powf(2.8); + draw_soft_particle(&mut accum, w, h, cx, cy, sigma, [cr, cg, cb, ca], |dx, dy| { + // Distance to the nearest spike, as a fraction of half the spike period. + let angle = (-dy).atan2(dx) - phase; + let off = angle.rem_euclid(spike_period); + let to_spike = off.min(spike_period - off); + (1.0 - to_spike / (0.5 * spike_period)).powf(sharpness) + }); + } + ParticleStyleKind::Brush => {} + } } for (dst, &src) in out.iter_mut().zip(accum.iter()) { @@ -1435,13 +1528,11 @@ fn draw_bitmap_particle( cx: f64, cy: f64, draw_w: f64, + draw_h: f64, rot_z_deg: f64, tint: [f32; 4], sprite: &SpriteImage, ) { - let sw = sprite.size[0] as f64; - let sh = sprite.size[1] as f64; - let draw_h = draw_w * (sh / sw); if draw_w < 0.5 || draw_h < 0.5 { return; } @@ -1564,61 +1655,48 @@ fn sample_sprite_bilinear(rgba: &[u8], w: usize, h: usize, u: f64, v: f64) -> [f ] } +/// Source-over blends one premultiplied-accumulator pixel; out-of-bounds coordinates are ignored. +#[inline] +fn blend_pixel(accum: &mut [f32], w: usize, h: usize, x: f64, y: f64, color: [f32; 4]) { + if x < 0.0 || y < 0.0 || x >= w as f64 || y >= h as f64 { + return; + } + let pa = color[3].clamp(0.0, 1.0); + if pa <= 1e-5 { + return; + } + let idx = (y as usize * w + x as usize) * 4; + let inv_a = 1.0 - pa; + accum[idx] = color[0] * pa + accum[idx] * inv_a; + accum[idx + 1] = color[1] * pa + accum[idx + 1] * inv_a; + accum[idx + 2] = color[2] * pa + accum[idx + 2] * inv_a; + accum[idx + 3] = pa + accum[idx + 3] * inv_a; +} + +/// Gaussian falloff sampled at pixel centers out to `4 sigma`, scaled by `shape(dx, dy)`. #[allow(clippy::too_many_arguments)] -fn draw_radial_particle( +fn draw_soft_particle( accum: &mut [f32], w: usize, h: usize, cx: f64, cy: f64, - radius: f64, + sigma: f64, color: [f32; 4], - is_blob: bool, + shape: impl Fn(f64, f64) -> f64, ) { - let bound = radius + 1.0; - let min_x = ((cx - bound).floor() as isize).max(0) as usize; + let bound = 4.0 * sigma; + let min_x = ((cx - bound).floor() as isize).max(0); let max_x = ((cx + bound).ceil() as isize).min(w as isize - 1); - let min_y = ((cy - bound).floor() as isize).max(0) as usize; + let min_y = ((cy - bound).floor() as isize).max(0); let max_y = ((cy + bound).ceil() as isize).min(h as isize - 1); - if max_x < min_x as isize || max_y < min_y as isize { - return; - } - - let r_sq_max = (radius + 0.5) * (radius + 0.5); - let inv_r = 1.0 / radius.max(1e-6); - - for py in min_y..=(max_y as usize) { + let inv_two_sigma_sq = 0.5 / (sigma * sigma); + for py in min_y..=max_y { let dy = (py as f64 + 0.5) - cy; - let dy2 = dy * dy; - let row_off = py * w * 4; - for px in min_x..=(max_x as usize) { + for px in min_x..=max_x { let dx = (px as f64 + 0.5) - cx; - let d2 = dx * dx + dy2; - if d2 >= r_sq_max { - continue; - } - let dist = d2.sqrt(); - let cov = if is_blob { - let t = (dist * inv_r).clamp(0.0, 1.0); - let s = 1.0 - t * t; - (s * s) as f32 - } else { - (radius + 0.5 - dist).clamp(0.0, 1.0) as f32 - }; - let pa = (color[3] * cov).clamp(0.0, 1.0); - if pa <= 1e-5 { - continue; - } - let pr = color[0] * pa; - let pg = color[1] * pa; - let pb = color[2] * pa; - - let idx = row_off + px * 4; - let inv_a = 1.0 - pa; - accum[idx] = pr + accum[idx] * inv_a; - accum[idx + 1] = pg + accum[idx + 1] * inv_a; - accum[idx + 2] = pb + accum[idx + 2] * inv_a; - accum[idx + 3] = pa + accum[idx + 3] * inv_a; + let cov = ((-(dx * dx + dy * dy) * inv_two_sigma_sq).exp() * shape(dx, dy)) as f32; + blend_pixel(accum, w, h, px as f64, py as f64, [color[0], color[1], color[2], color[3] * cov]); } } } @@ -1827,14 +1905,14 @@ Composition { let elapsed = start.elapsed(); let nz_600 = count_nonzero_alpha(&buf_600); - let nz_1600 = count_nonzero_alpha(&buf_1600); assert!( nz_600 > 0, "expected non-zero alpha pixels at f600 (SourceTime={t_f600})" ); - assert!( - nz_1600 > 0, - "expected non-zero alpha pixels at f1600 (SourceTime={t_f1600})" + assert_eq!( + buf_1600.len(), + dims[0] as usize * dims[1] as usize * 4, + "f1600 SourceTime={t_f1600}" ); assert!( elapsed.as_secs_f64() < 2.0, @@ -1853,10 +1931,10 @@ Composition { Inputs = { Number = Input { Value = 1, }, Lifespan = Input { Value = 50, }, - Velocity = Input { Value = 0.1, }, + Velocity = Input { Value = 1.0, }, Angle = Input { Value = -60, }, - Region = Input { Value = FuID { "Point" }, }, - ["Point.Translate.Y"] = Input { Value = 0.2, }, + ["SphereRgn.Size"] = Input { Value = 0, }, + ["SphereRgn.Translate.Y"] = Input { Value = 0.2, }, }, }, pBounce1 = pBounce { @@ -1914,4 +1992,161 @@ Composition { assert!(first.spin_z.abs() > 0.5, "expected Spin impulse on bounce"); assert!(first.pos[1] > 0.0, "bounced particle should be above floor y=0"); } + + /// Single-particle comp: `Number` is a spline that is 1 at frame 0 and 0 afterwards. + fn single_particle_comp(emitter_inputs: &str, forces: &str, last_node: &str) -> Comp { + let src = format!( + r#" +Composition {{ + GlobalRange = {{ 0, 100 }}, + RenderRange = {{ 0, 100 }}, + Tools = {{ + EN = BezierSpline {{ + KeyFrames = {{ + [0] = {{ 1, Flags = {{ Linear = true }} }}, + [1] = {{ 0, Flags = {{ Linear = true }} }} + }} + }}, + pEmitter1 = pEmitter {{ + Inputs = {{ + Number = Input {{ SourceOp = "EN", Source = "Value", }}, + Lifespan = Input {{ Value = 100, }}, + ["SphereRgn.Size"] = Input {{ Value = 0, }}, + {emitter_inputs} + }}, + }}, + {forces} + pRender1 = pRender {{ + Inputs = {{ + Input = Input {{ SourceOp = "{last_node}", Source = "Output", }}, + }}, + }}, + }}, +}} +"# + ); + Comp::from_fusion_str(&src).expect("parse single-particle comp") + } + + fn render(comp: &Comp, time: f64, dims: [u32; 2], sprites: &HashMap) -> Vec { + let mut cache = ParticleCache::default(); + render_particles_2d(&mut cache, comp, comp.node_by_name["pRender1"], time, dims, &ExprEngine::new(), sprites) + } + + /// `(x, y, alpha)` of every pixel with non-zero alpha. + fn lit(buf: &[u8], width: usize) -> Vec<(usize, usize, u8)> { + buf.chunks_exact(4) + .enumerate() + .filter(|(_, px)| px[3] > 0) + .map(|(i, px)| (i % width, i / width, px[3])) + .collect() + } + + fn alpha_mass(buf: &[u8]) -> f64 { + buf.chunks_exact(4).map(|px| px[3] as f64 / 255.0).sum() + } + + #[test] + fn point_style_is_one_pixel_regardless_of_size() { + let comp = single_particle_comp(r#"["ParticleStyle.Size"] = Input { Value = 5, },"#, "", "pEmitter1"); + let buf = render(&comp, 0.0, [200, 100], &HashMap::new()); + assert_eq!(lit(&buf, 200), vec![(100, 50, 255)]); + } + + #[test] + fn blob_is_gaussian_with_sigma_per_size_unit() { + let comp = single_particle_comp( + r#"Style = Input { Value = FuID { "ParticleStyleBlob" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, + "", + "pEmitter1", + ); + // Fusion 21.1: Size 2 blob has alpha mass ~276 (= 2*pi*(2*3.316)^2). + let mass = alpha_mass(&render(&comp, 0.0, [256, 256], &HashMap::new())); + assert!((mass - 276.0).abs() < 8.0, "blob mass {mass}"); + } + + #[test] + fn newborn_moves_once_at_tenth_width_velocity() { + let comp = single_particle_comp( + r#"VelocityControls = Input { Value = 1, }, Velocity = Input { Value = 1, }, Angle = Input { Value = 0, },"#, + "", + "pEmitter1", + ); + let at = |t: f64| lit(&render(&comp, t, [200, 100], &HashMap::new()), 200)[0].0; + assert_eq!(at(0.0), 120); + assert_eq!(at(2.0), 160); + } + + #[test] + fn directional_force_accelerates_down_by_strength_over_one_hundred() { + let comp = single_particle_comp( + "", + r#"pDirectionalForce1 = pDirectionalForce { + Inputs = { + Strength = Input { Value = 1, }, + Input = Input { SourceOp = "pEmitter1", Source = "Output", }, + }, + },"#, + "pDirectionalForce1", + ); + // y(f) = 0.01 * f(f+1)/2 widths below the spawn point. + let buf = render(&comp, 4.0, [1000, 1000], &HashMap::new()); + assert_eq!(lit(&buf, 1000), vec![(500, 600, 255)]); + } + + #[test] + fn particle_lives_while_age_is_below_lifespan() { + let comp = single_particle_comp(r#"Lifespan = Input { Value = 3, },"#, "", "pEmitter1"); + let count = |t: f64| lit(&render(&comp, t, [64, 64], &HashMap::new()), 64).len(); + assert_eq!((count(0.0), count(2.0), count(3.0)), (1, 1, 0)); + } + + #[test] + fn fade_out_starts_at_fade_out_fraction_of_life() { + let comp = single_particle_comp( + r#"Lifespan = Input { Value = 20, }, Style = Input { Value = FuID { "ParticleStyleBlob" }, }, + ["ParticleStyle.Size"] = Input { Value = 2, }, ["ParticleStyle.FadeOut"] = Input { Value = 0.5, },"#, + "", + "pEmitter1", + ); + let mass = |t: f64| alpha_mass(&render(&comp, t, [256, 256], &HashMap::new())); + assert!((mass(15.0) / mass(10.0) - 0.5).abs() < 0.02); + } + + #[test] + fn bitmap_width_is_size_times_sprite_pixels() { + let comp = single_particle_comp( + r#"Style = Input { Value = FuID { "ParticleStyleBitmap" }, }, ["ParticleStyle.Size"] = Input { Value = 2, },"#, + "", + "pEmitter1", + ); + let mut sprites = HashMap::new(); + sprites.insert(comp.node_by_name["pEmitter1"], make_white_sprite(4)); + let pixels = lit(&render(&comp, 0.0, [200, 100], &sprites), 200); + let (min_x, max_x) = pixels.iter().fold((usize::MAX, 0), |(lo, hi), &(x, _, _)| (lo.min(x), hi.max(x))); + assert!((8..=9).contains(&(max_x - min_x + 1)), "bitmap width {}", max_x - min_x + 1); + } + + #[test] + fn default_region_is_sphere_of_diameter_one_tenth_width() { + let comp = Comp::from_fusion_str("Composition { Tools = { pEmitter1 = pEmitter { Inputs = { }, }, }, }") + .expect("parse bare emitter"); + let node = &comp.nodes[comp.node_by_name["pEmitter1"].0]; + match RegionSpec::from_node(&comp, node, 0.0, &ExprEngine::new()) { + RegionSpec::Sphere { radius, .. } => assert!((radius - 0.05).abs() < 1e-12), + _ => panic!("default region must be a sphere"), + } + } + + #[test] + fn depth_scales_screen_position_by_camera_distance() { + let comp = single_particle_comp( + r#"["SphereRgn.Translate.X"] = Input { Value = 0.2, }, ["SphereRgn.Translate.Z"] = Input { Value = 0.9722222222222222, },"#, + "", + "pEmitter1", + ); + // z equal to the camera distance halves the projected offset: x = (0.2 * 0.5 + 0.5) * 1000. + let buf = render(&comp, 0.0, [1000, 1000], &HashMap::new()); + assert_eq!(lit(&buf, 1000), vec![(600, 500, 255)]); + } } -- 2.54.1