1//! Fusion deterministic particle simulation & 2D rendering system.
2//!
3//! Supports `pEmitter`, `pPointForce`, `pDirectionalForce`, `pTurbulence`,
4//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pVortex`, `pFlock`, `pSpawn`,
5//! `pChangeStyle`, `pGradientForce`, `pMerge`, and `pRender` (2D mode).
6
7mod custom;
8mod custom_eval;
9mod extra_forces;
10mod forces;
11mod plan;
12mod raster;
13mod sim;
14#[cfg(test)]
15mod extra_tests;
16#[cfg(test)]
17mod tests;
18
19pub use plan::collect_bitmap_sources;
20
21use std::collections::hash_map::DefaultHasher;
22use std::collections::{BTreeMap, HashMap};
23use std::hash::{Hash, Hasher};
24
25use model::{Comp, ExprEngine, NodeId};
26
27use forces::build_gradient_fields;
28use plan::{build_particle_plan, particle_subgraph_hash};
29use raster::rasterize_particles;
30use sim::step_simulation;
31
32/// Maximum simultaneous live particles kept in a single simulation to prevent
33/// pathological comps from hanging or exhausting memory.
34const MAX_PARTICLES: usize = 20_000;
35
36/// Maximum cold-start lookback frames from `target_frame` when `base_start` is far earlier.
37const MAX_SIM_WINDOW: i64 = 600;
38
39/// Periodic snapshot interval (frames from `base_start`) for fast backward scrubbing.
40const SNAPSHOT_INTERVAL: i64 = 60;
41
42/// Maximum periodic snapshots retained per cached particle simulation.
43const MAX_SNAPSHOTS: usize = 32;
44
45/// Particle integration step: `Velocity` moves `0.1` render widths per frame and
46/// forces accelerate by `0.1^2` per unit of `Strength`.
47const VELOCITY_SCALE: f64 = 0.1;
48
49/// `pPointForce` acceleration is `Strength * 1e-4 / distance^Power` (render widths per frame^2).
50const POINT_FORCE_SCALE: f64 = 1.0e-4;
51
52/// Default render camera distance in render widths (35mm lens on a 36mm film back).
53const CAMERA_DISTANCE: f64 = 35.0 / 36.0;
54
55/// Blob particle falloff is `exp(-r^2 / (2 sigma^2))` with `sigma = BLOB_SIGMA_PER_SIZE * Size` pixels.
56const BLOB_SIGMA_PER_SIZE: f64 = 3.316;
57
58/// Fusion internal acceleration scale for `pTurbulence`.
59const TURBULENCE_SCALE: f64 = 2.0e-3;
60
61/// Premultiplied RGBA8 bitmap sprite image used by `ParticleStyleBitmap`.
62#[derive(Clone, Debug)]
63pub struct SpriteImage {
64 pub size: [u32; 2],
65 pub rgba: Vec<u8>,
66}
67
68/// Persistent frame-to-frame cache for deterministic particle simulations and scratch raster buffers.
69///
70/// Keyed by `(render_node_name, subgraph_hash)`. Advancing sequentially `f -> f+1`
71/// only steps 1 frame even past `MAX_SIM_WINDOW`, while periodic snapshots every
72/// `SNAPSHOT_INTERVAL` frames accelerate backward scrubbing.
73#[derive(Default)]
74pub struct ParticleCache {
75 entries: HashMap<(String, u64), CachedSim>,
76 /// Reusable premultiplied RGBA32F accumulation canvas (kept zeroed between calls).
77 scratch_accum: Vec<f32>,
78 /// Reusable draw-command list to avoid per-frame allocations.
79 scratch_cmds: Vec<raster::DrawCmd>,
80}
81
82impl ParticleCache {
83 pub fn clear(&mut self) {
84 self.entries.clear();
85 self.scratch_accum.clear();
86 self.scratch_cmds.clear();
87 }
88}
89
90#[derive(Clone)]
91struct CachedSim {
92 base_start: i64,
93 current_frame: i64,
94 state: SimState,
95 snapshots: BTreeMap<i64, SimState>,
96}
97
98#[derive(Clone)]
99struct SimState {
100 particles: Vec<Particle>,
101 /// Fractional emission accumulator per `pEmitter` stable name hash.
102 emit_accum: HashMap<u64, f64>,
103 /// Monotonically increasing particle ID counter for `id` in `pCustom` / `pAvoid`.
104 next_id: u32,
105}
106
107impl Default for SimState {
108 fn default() -> Self {
109 Self {
110 particles: Vec::new(),
111 emit_accum: HashMap::new(),
112 next_id: 1,
113 }
114 }
115}
116
117#[derive(Clone, Copy, Debug)]
118struct Particle {
119 emitter_hash: u64,
120 id: u32,
121 /// Particle set membership bitmask (bit 0 = Set1 .. bit 31 = Set32).
122 sets: u32,
123 /// Optional per-particle style override applied by `pChangeStyle` / `pSpawn`.
124 style_override: Option<ParticleStyleKind>,
125 /// Optional NGon sides override (0 = inherit from emitter).
126 ngon_sides_override: u8,
127 /// Optional bitmap sprite owner hash override (0 = use `emitter_hash`).
128 bitmap_owner_hash: u64,
129 pos: [f64; 3],
130 vel: [f64; 3],
131 rot_xy: [f64; 2],
132 rot_z: f64,
133 spin_xy: [f64; 2],
134 spin_z: f64,
135 age: f64,
136 lifespan: f64,
137 size: f64,
138 mass: f64,
139 user: f64,
140 color: [f32; 4],
141 alive: bool,
142}
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145enum ParticleStyleKind {
146 Point,
147 Blob,
148 NGon,
149 Bitmap,
150 Brush,
151}
152
153/// Stable FNV-1a 64-bit hash of a node name (independent of `NodeId` index).
154#[inline]
155fn stable_name_hash(name: &str) -> u64 {
156 let mut h = 0xcbf2_9ce4_8422_2325_u64;
157 for &b in name.as_bytes() {
158 h ^= u64::from(b);
159 h = h.wrapping_mul(0x0100_0000_01b3);
160 }
161 h
162}
163
164/// Deterministic SplitMix64 PRNG.
165#[derive(Clone, Copy)]
166struct SplitMix64(u64);
167
168impl SplitMix64 {
169 fn from_parts(seed: i64, frame: i64, node_name: &str) -> Self {
170 let mut s = (seed as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
171 s ^= (frame as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
172 s ^= stable_name_hash(node_name).wrapping_mul(0x94D0_49BB_1331_11EB);
173 let mut rng = Self(s ^ 0xD1B5_4A32_D192_ED03);
174 let _ = rng.next_u64();
175 rng
176 }
177
178 #[inline]
179 fn next_u64(&mut self) -> u64 {
180 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
181 let mut z = self.0;
182 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
183 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
184 z ^ (z >> 31)
185 }
186
187 /// Uniform float in `[0.0, 1.0)`.
188 #[inline]
189 fn next_f64(&mut self) -> f64 {
190 (self.next_u64() >> 11) as f64 * (1.0 / ((1u64 << 53) as f64))
191 }
192
193 /// Uniform float in `[-1.0, 1.0)`.
194 #[inline]
195 fn signed(&mut self) -> f64 {
196 self.next_f64() * 2.0 - 1.0
197 }
198
199 /// Uniform float in `[lo, hi]`.
200 #[inline]
201 fn range(&mut self, lo: f64, hi: f64) -> f64 {
202 let (a, b) = if lo <= hi { (lo, hi) } else { (hi, lo) };
203 a + (b - a) * self.next_f64()
204 }
205}
206
207fn maybe_record_snapshot(cached: &mut CachedSim, frame: i64) {
208 let delta = i128::from(frame) - i128::from(cached.base_start);
209 if delta.rem_euclid(i128::from(SNAPSHOT_INTERVAL)) == 0 {
210 cached.snapshots.insert(frame, cached.state.clone());
211 while cached.snapshots.len() > MAX_SNAPSHOTS {
212 if let Some(&oldest) = cached.snapshots.keys().next() {
213 cached.snapshots.remove(&oldest);
214 } else {
215 break;
216 }
217 }
218 }
219}
220
221/// Runs deterministic frame-stepped particle simulation up to `time.floor()` and
222/// rasterizes all live particles into a premultiplied RGBA8 buffer of size
223/// `dims[0] * dims[1] * 4`.
224pub fn render_particles_2d(
225 cache: &mut ParticleCache,
226 comp: &Comp,
227 render_node: NodeId,
228 time: f64,
229 dims: [u32; 2],
230 expr: &ExprEngine,
231 sprites: &HashMap<NodeId, SpriteImage>,
232) -> Vec<u8> {
233 let pixel_count = (dims[0] as usize).saturating_mul(dims[1] as usize);
234 let mut out = vec![0u8; pixel_count.saturating_mul(4)];
235 if pixel_count == 0 || !time.is_finite() {
236 return out;
237 }
238
239 let Some(rnode) = comp.nodes.get(render_node.0) else {
240 return out;
241 };
242 if rnode.bypassed {
243 return out;
244 }
245
246 let plan = build_particle_plan(comp, render_node);
247 if plan.emitters.is_empty() {
248 return out;
249 }
250
251 let target_frame = time.floor() as i64;
252 let base_start = if comp.global_range[0] <= 0 {
253 0
254 } else {
255 comp.global_range[0]
256 };
257 if target_frame < base_start {
258 return out;
259 }
260
261 let pre_gen = comp
262 .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr)
263 .round()
264 .clamp(0.0, MAX_SIM_WINDOW as f64) as i64;
265 let sim_origin = base_start.saturating_sub(pre_gen);
266
267 let gradient_fields = build_gradient_fields(comp, &plan.modifiers, sprites);
268 let mut subgraph_hash = particle_subgraph_hash(comp, render_node, base_start);
269 if !gradient_fields.is_empty() || !sprites.is_empty() {
270 let mut h = DefaultHasher::new();
271 subgraph_hash.hash(&mut h);
272 let mut gf_ids: Vec<NodeId> = gradient_fields.keys().copied().collect();
273 gf_ids.sort_by_key(|id| id.0);
274 for id in gf_ids {
275 id.0.hash(&mut h);
276 gradient_fields[&id].content_hash.hash(&mut h);
277 }
278 let mut spr_ids: Vec<NodeId> = sprites.keys().copied().collect();
279 spr_ids.sort_by_key(|id| id.0);
280 for id in spr_ids {
281 let sp = &sprites[&id];
282 id.0.hash(&mut h);
283 sp.size.hash(&mut h);
284 sp.rgba.len().hash(&mut h);
285 let step = (sp.rgba.len() / 256).max(1);
286 for b in sp.rgba.iter().step_by(step) {
287 b.hash(&mut h);
288 }
289 }
290 subgraph_hash = h.finish();
291 }
292 let key = (rnode.name.clone(), subgraph_hash);
293 // Evict stale subgraph hashes for this render node while keeping other pRender entries.
294 cache
295 .entries
296 .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash);
297
298 let cold_sim_start = |target: i64| sim_origin.max(target.saturating_sub(MAX_SIM_WINDOW));
299
300 let need_cold_init = match cache.entries.get_mut(&key) {
301 Some(cached) if cached.base_start == sim_origin => {
302 if target_frame == cached.current_frame {
303 false
304 } else if target_frame > cached.current_frame {
305 if i128::from(target_frame) - i128::from(cached.current_frame) <= i128::from(MAX_SIM_WINDOW) {
306 for f in cached.current_frame.saturating_add(1)..=target_frame {
307 step_simulation(
308 &mut cached.state,
309 comp,
310 &plan,
311 &gradient_fields,
312 sprites,
313 f,
314 sim_origin,
315 expr,
316 );
317 maybe_record_snapshot(cached, f);
318 }
319 cached.current_frame = target_frame;
320 false
321 } else {
322 true
323 }
324 } else if let Some((&snap_f, snap_state)) = cached.snapshots.range(..=target_frame).next_back() {
325 if i128::from(target_frame) - i128::from(snap_f) <= i128::from(MAX_SIM_WINDOW) {
326 cached.state = snap_state.clone();
327 cached.current_frame = snap_f;
328 if snap_f < target_frame {
329 for f in snap_f.saturating_add(1)..=target_frame {
330 step_simulation(
331 &mut cached.state,
332 comp,
333 &plan,
334 &gradient_fields,
335 sprites,
336 f,
337 sim_origin,
338 expr,
339 );
340 maybe_record_snapshot(cached, f);
341 }
342 }
343 cached.current_frame = target_frame;
344 false
345 } else {
346 true
347 }
348 } else {
349 true
350 }
351 }
352 _ => true,
353 };
354
355 if need_cold_init {
356 let sim_start = cold_sim_start(target_frame);
357 let mut sim = CachedSim {
358 base_start: sim_origin,
359 current_frame: target_frame,
360 state: SimState::default(),
361 snapshots: BTreeMap::new(),
362 };
363 for f in sim_start..=target_frame {
364 step_simulation(
365 &mut sim.state,
366 comp,
367 &plan,
368 &gradient_fields,
369 sprites,
370 f,
371 sim_start,
372 expr,
373 );
374 maybe_record_snapshot(&mut sim, f);
375 }
376 cache.entries.insert(key.clone(), sim);
377 }
378
379 let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0);
380 let particles_len = cache.entries.get(&key).map_or(0, |c| c.state.particles.len());
381 if particles_len == 0 {
382 return out;
383 }
384
385 // Temporarily take `entries` out so `scratch_accum` and `scratch_cmds` can be borrowed mutably.
386 let entries = std::mem::take(&mut cache.entries);
387 if let Some(cached) = entries.get(&key) {
388 rasterize_particles(
389 &mut out,
390 &mut cache.scratch_accum,
391 &mut cache.scratch_cmds,
392 dims,
393 dims[0] as f64 / render_width,
394 comp,
395 &plan.emitter_nodes,
396 &cached.state.particles,
397 time,
398 expr,
399 sprites,
400 );
401 }
402 cache.entries = entries;
403 out
404}
405
406/// Per-frame particle emission, regions, forces, collisions, and simulation stepping.
407#[cfg(test)]
408mod w26c_tests {
409 use super::*;
410
411 #[test]
412 fn default_size_is_one_tenth_and_pregenerate_frames_emits_preroll() {
413 let comp_src = r#"
414Composition {
415 GlobalRange = { 0, 20 },
416 RenderRange = { 0, 20 },
417 Tools = {
418 E = pEmitter {
419 Inputs = {
420 RandomSeed = Input { Value = 42, },
421 Style = Input { Value = FuID { "ParticleStyleBlob" }, },
422 Number = Input { Value = 10, },
423 Velocity = Input { Value = 0.05, },
424 },
425 },
426 R_default = pRender {
427 Inputs = {
428 Width = Input { Value = 256, },
429 Height = Input { Value = 256, },
430 Input = Input { SourceOp = "E", Source = "Output", },
431 },
432 },
433 R_pre = pRender {
434 Inputs = {
435 Width = Input { Value = 256, },
436 Height = Input { Value = 256, },
437 PreGenerateFrames = Input { Value = 20, },
438 Input = Input { SourceOp = "E", Source = "Output", },
439 },
440 },
441 },
442}
443"#;
444 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
445 let expr = ExprEngine::new();
446 let sprites = HashMap::new();
447
448 let mut cache = ParticleCache::default();
449 let img_default = render_particles_2d(
450 &mut cache,
451 &comp,
452 comp.node_by_name["R_default"],
453 0.0,
454 [256, 256],
455 &expr,
456 &sprites,
457 );
458 // Default Size = 0.1 produces compact ~0.33px-sigma blobs (~7 alpha mass for 10 blobs).
459 let alpha_mass_default: f64 = img_default
460 .chunks_exact(4)
461 .map(|px| px[3] as f64 / 255.0)
462 .sum();
463 assert!(
464 alpha_mass_default > 3.0 && alpha_mass_default < 15.0,
465 "expected Size=0.1 alpha mass in (3, 15), got {alpha_mass_default}"
466 );
467 assert!(
468 cache.scratch_accum.iter().all(|&x| x == 0.0),
469 "scratch_accum must be zeroed after render"
470 );
471
472 let img_pre = render_particles_2d(
473 &mut cache,
474 &comp,
475 comp.node_by_name["R_pre"],
476 0.0,
477 [256, 256],
478 &expr,
479 &sprites,
480 );
481 let alpha_mass_pre: f64 = img_pre
482 .chunks_exact(4)
483 .map(|px| px[3] as f64 / 255.0)
484 .sum();
485 assert!(
486 alpha_mass_pre > alpha_mass_default * 8.0,
487 "PreGenerateFrames=20 should accumulate ~21x particles (default={alpha_mass_default}, pre={alpha_mass_pre})"
488 );
489 assert!(
490 cache.scratch_accum.iter().all(|&x| x == 0.0),
491 "scratch_accum must stay zeroed after PreGenerateFrames render"
492 );
493 }
494
495 #[test]
496 fn scratch_buffer_reuse_and_parallel_band_determinism() {
497 let comp_src = r#"
498Composition {
499 GlobalRange = { 0, 50 },
500 RenderRange = { 0, 50 },
501 Tools = {
502 E_blob = pEmitter {
503 Inputs = {
504 RandomSeed = Input { Value = 11, },
505 Style = Input { Value = FuID { "ParticleStyleBlob" }, },
506 Number = Input { Value = 40, },
507 Velocity = Input { Value = 0.4, },
508 AngleVariance = Input { Value = 180, },
509 ["ParticleStyle.Size"] = Input { Value = 0.6, },
510 ["ParticleStyle.RedHigh"] = Input { Value = -0.5, },
511 },
512 },
513 E_ngon = pEmitter {
514 Inputs = {
515 RandomSeed = Input { Value = 22, },
516 Style = Input { Value = FuID { "ParticleStyleNGon" }, },
517 Number = Input { Value = 25, },
518 Velocity = Input { Value = 0.3, },
519 AngleVariance = Input { Value = 180, },
520 RotationZVariance = Input { Value = 180, },
521 ["ParticleStyle.Size"] = Input { Value = 0.5, },
522 },
523 },
524 E_bmp = pEmitter {
525 Inputs = {
526 RandomSeed = Input { Value = 33, },
527 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
528 Number = Input { Value = 25, },
529 Velocity = Input { Value = 0.35, },
530 AngleVariance = Input { Value = 180, },
531 RotationZVariance = Input { Value = 45, },
532 ["ParticleStyle.Size"] = Input { Value = 1.2, },
533 },
534 },
535 M1 = pMerge {
536 Inputs = {
537 Input1 = Input { SourceOp = "E_blob", Source = "Output", },
538 Input2 = Input { SourceOp = "E_ngon", Source = "Output", },
539 },
540 },
541 M2 = pMerge {
542 Inputs = {
543 Input1 = Input { SourceOp = "M1", Source = "Output", },
544 Input2 = Input { SourceOp = "E_bmp", Source = "Output", },
545 },
546 },
547 R = pRender {
548 Inputs = {
549 Width = Input { Value = 640, },
550 Height = Input { Value = 360, },
551 Input = Input { SourceOp = "M2", Source = "Output", },
552 },
553 },
554 },
555}
556"#;
557 let comp = Comp::from_fusion_str(comp_src).expect("parse multi-style comp");
558 let render_id = comp.node_by_name["R"];
559 let bmp_id = comp.node_by_name["E_bmp"];
560 let expr = ExprEngine::new();
561 let mut sprites = HashMap::new();
562 let mut sprite_rgba = vec![0u8; 8 * 8 * 4];
563 for (i, px) in sprite_rgba.chunks_exact_mut(4).enumerate() {
564 px[0] = ((i * 37) % 256) as u8;
565 px[1] = 200;
566 px[2] = 120;
567 px[3] = 220;
568 }
569 sprites.insert(bmp_id, SpriteImage { size: [8, 8], rgba: sprite_rgba });
570
571 // Render at 640x360 (triggers parallel band rasterizer) twice with separate caches: must be bit-identical.
572 let mut cache_a = ParticleCache::default();
573 let mut cache_b = ParticleCache::default();
574 let buf_a = render_particles_2d(&mut cache_a, &comp, render_id, 15.0, [640, 360], &expr, &sprites);
575 let buf_b = render_particles_2d(&mut cache_b, &comp, render_id, 15.0, [640, 360], &expr, &sprites);
576 assert_eq!(buf_a, buf_b, "multi-style 640x360 render must be bit-for-bit deterministic");
577 assert!(buf_a.chunks_exact(4).any(|px| px[3] > 0));
578 assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0));
579
580 // Reusing the same cache at smaller and larger resolutions must not leak stale scratch pixels.
581 let small = render_particles_2d(&mut cache_a, &comp, render_id, 16.0, [120, 80], &expr, &sprites);
582 let mut fresh_small = ParticleCache::default();
583 let small_ref = render_particles_2d(&mut fresh_small, &comp, render_id, 16.0, [120, 80], &expr, &sprites);
584 assert_eq!(small, small_ref);
585
586 let large = render_particles_2d(&mut cache_a, &comp, render_id, 17.0, [720, 405], &expr, &sprites);
587 let mut fresh_large = ParticleCache::default();
588 let large_ref = render_particles_2d(&mut fresh_large, &comp, render_id, 17.0, [720, 405], &expr, &sprites);
589 assert_eq!(large, large_ref);
590 assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0));
591 }
592
593 #[test]
594 fn fast_path_unrotated_and_1x1_bitmap_match_bounds_and_clipping() {
595 let comp_src = r#"
596Composition {
597 GlobalRange = { 0, 10 },
598 RenderRange = { 0, 10 },
599 Tools = {
600 EN = BezierSpline {
601 KeyFrames = {
602 [0] = { 1, Flags = { Linear = true } },
603 [1] = { 0, Flags = { Linear = true } }
604 }
605 },
606 BG1x1 = Background {
607 Inputs = {
608 Width = Input { Value = 4, },
609 Height = Input { Value = 4, },
610 TopLeftRed = Input { Value = 0.5, },
611 TopLeftGreen = Input { Value = 0.25, },
612 TopLeftBlue = Input { Value = 1.0, },
613 TopLeftAlpha = Input { Value = 0.8, },
614 },
615 },
616 E = pEmitter {
617 Inputs = {
618 Number = Input { SourceOp = "EN", Source = "Value", },
619 Lifespan = Input { Value = 10, },
620 ["SphereRgn.Size"] = Input { Value = 0, },
621 ["SphereRgn.Translate.X"] = Input { Value = -0.49, },
622 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
623 ["ParticleStyleBitmap.DropToolsHere"] = Input { SourceOp = "BG1x1", Source = "Output", },
624 ["ParticleStyle.Size"] = Input { Value = 2, },
625 },
626 },
627 R = pRender {
628 Inputs = {
629 Width = Input { Value = 100, },
630 Height = Input { Value = 100, },
631 Input = Input { SourceOp = "E", Source = "Output", },
632 },
633 },
634 },
635}
636"#;
637 let comp = Comp::from_fusion_str(comp_src).expect("parse 1x1 bitmap comp");
638 let mut cache = ParticleCache::default();
639 let img = render_particles_2d(
640 &mut cache,
641 &comp,
642 comp.node_by_name["R"],
643 0.0,
644 [100, 100],
645 &ExprEngine::new(),
646 &HashMap::new(),
647 );
648 // Particle centered at x = 1 px with 8 px width must clip cleanly at left edge (x=0) without wrapping.
649 let lit_cols: Vec<usize> = (0..100)
650 .filter(|&x| img[(50 * 100 + x) * 4 + 3] > 0)
651 .collect();
652 assert_eq!(lit_cols, vec![0, 1, 2, 3, 4]);
653 assert_eq!(img[(50 * 100 + 99) * 4 + 3], 0, "must not wrap to right edge");
654 }
655}