authoravatarclover caruso<git@paperclover.net>2026-12-01 15:30:23-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 15:49:39-08:00
logfb8cf0b99d4b4ae93c1a9a612d5ab31e815cd8c5
treee1a2f2834cbdb7111a459b95aa03b72e3d3d94f5
parentd83257b4dee1816c191667fd1599560b7d231441
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

perf(engine): optimize particle rasterization and improve pEmitter/pRender parity


1 files changed, 2168 insertions(+), 20 deletions(-)

crates/engine/src/particles.rs+2168-20
......@@ -4,8 +4,6 @@
44//! `pDrag` / `pFriction`, `pKill`, `pBounce`, `pMerge`, and `pRender` (2D mode).
55
66mod plan;
7mod raster;
8mod sim;
97#[cfg(test)]
108mod tests;
119
......@@ -55,7 +53,7 @@ pub struct SpriteImage {
5553 pub rgba: Vec<u8>,
5654}
5755
58/// Persistent frame-to-frame cache for deterministic particle simulations.
56/// Persistent frame-to-frame cache for deterministic particle simulations and scratch raster buffers.
5957///
6058/// Keyed by `(render_node_name, subgraph_hash)`. Advancing sequentially `f -> f+1`
6159/// only steps 1 frame even past `MAX_SIM_WINDOW`, while periodic snapshots every
......@@ -63,11 +61,17 @@ pub struct SpriteImage {
6361#[derive(Default)]
6462pub struct ParticleCache {
6563 entries: HashMap<(String, u64), CachedSim>,
64 /// Reusable premultiplied RGBA32F accumulation canvas (kept zeroed between calls).
65 scratch_accum: Vec<f32>,
66 /// Reusable draw-command list to avoid per-frame allocations.
67 scratch_cmds: Vec<raster::DrawCmd>,
6668}
6769
6870impl ParticleCache {
6971 pub fn clear(&mut self) {
7072 self.entries.clear();
73 self.scratch_accum.clear();
74 self.scratch_cmds.clear();
7175 }
7276}
7377
......@@ -216,6 +220,12 @@ pub fn render_particles_2d(
216220 return out;
217221 }
218222
223 let pre_gen = comp
224 .eval_number(rnode, "PreGenerateFrames", time, 0.0, expr)
225 .round()
226 .clamp(0.0, MAX_SIM_WINDOW as f64) as i64;
227 let sim_origin = base_start - pre_gen;
228
219229 let subgraph_hash = particle_subgraph_hash(comp, render_node, base_start);
220230 let key = (rnode.name.clone(), subgraph_hash);
221231 // Evict stale subgraph hashes for this render node while keeping other pRender entries.
......@@ -223,10 +233,10 @@ pub fn render_particles_2d(
223233 .entries
224234 .retain(|(name, h), _| name != &key.0 || *h == subgraph_hash);
225235
226 let cold_sim_start = |target: i64| base_start.max(target - MAX_SIM_WINDOW);
236 let cold_sim_start = |target: i64| sim_origin.max(target - MAX_SIM_WINDOW);
227237
228238 let need_cold_init = match cache.entries.get_mut(&key) {
229 Some(cached) if cached.base_start == base_start => {
239 Some(cached) if cached.base_start == sim_origin => {
230240 if target_frame == cached.current_frame {
231241 false
232242 } else if target_frame > cached.current_frame {
......@@ -259,7 +269,7 @@ pub fn render_particles_2d(
259269 if need_cold_init {
260270 let sim_start = cold_sim_start(target_frame);
261271 let mut sim = CachedSim {
262 base_start,
272 base_start: sim_origin,
263273 current_frame: target_frame,
264274 state: SimState::default(),
265275 snapshots: BTreeMap::new(),
......@@ -271,21 +281,2159 @@ pub fn render_particles_2d(
271281 cache.entries.insert(key.clone(), sim);
272282 }
273283
274 let Some(cached) = cache.entries.get(&key) else {
284 let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0);
285 let particles_len = cache.entries.get(&key).map_or(0, |c| c.state.particles.len());
286 if particles_len == 0 {
275287 return out;
276 };
288 }
277289
278 let render_width = comp.eval_number(rnode, "Width", time, dims[0] as f64, expr).max(1.0);
279 rasterize_particles(
280 &mut out,
281 dims,
282 dims[0] as f64 / render_width,
283 comp,
284 &plan.emitter_nodes,
285 &cached.state.particles,
286 time,
287 expr,
288 sprites,
289 );
290 // Temporarily take `entries` out so `scratch_accum` and `scratch_cmds` can be borrowed mutably.
291 let entries = std::mem::take(&mut cache.entries);
292 if let Some(cached) = entries.get(&key) {
293 rasterize_particles(
294 &mut out,
295 &mut cache.scratch_accum,
296 &mut cache.scratch_cmds,
297 dims,
298 dims[0] as f64 / render_width,
299 comp,
300 &plan.emitter_nodes,
301 &cached.state.particles,
302 time,
303 expr,
304 sprites,
305 );
306 }
307 cache.entries = entries;
290308 out
291309}
310
311/// Per-frame particle emission, regions, forces, collisions, and simulation stepping.
312mod sim {
313 use std::collections::HashSet;
314
315 use model::{Comp, ExprEngine, Node};
316
317 use super::plan::ParticlePlan;
318 use super::{
319 MAX_PARTICLES, POINT_FORCE_SCALE, Particle, SimState, SplitMix64, TURBULENCE_SCALE,
320 VELOCITY_SCALE,
321 };
322
323 /// Advances the particle simulation by a single integer frame `frame`.
324 pub(super) fn step_simulation(
325 state: &mut SimState,
326 comp: &Comp,
327 plan: &ParticlePlan,
328 frame: i64,
329 expr: &ExprEngine,
330 ) {
331 let t = frame as f64;
332
333 // 1. Apply forces & kills to existing live particles, then integrate motion and age.
334 if !state.particles.is_empty() {
335 for (mod_id, scope) in &plan.modifiers {
336 let Some(node) = comp.nodes.get(mod_id.0) else {
337 continue;
338 };
339 apply_modifier(&mut state.particles, comp, node, scope, t, expr);
340 }
341
342 for p in &mut state.particles {
343 if !p.alive {
344 continue;
345 }
346 p.pos[0] += p.vel[0];
347 p.pos[1] += p.vel[1];
348 p.pos[2] += p.vel[2];
349 p.rot_z += p.spin_z;
350 p.age += 1.0;
351 if p.age >= p.lifespan {
352 p.alive = false;
353 }
354 }
355 state.particles.retain(|p| p.alive);
356 }
357
358 // 2. Emit new particles for `frame` (born with `age = 0.0` at their spawn region).
359 let first_new = state.particles.len();
360 for &(emitter_id, emitter_hash) in &plan.emitters {
361 if state.particles.len() >= MAX_PARTICLES {
362 break;
363 }
364 let Some(node) = comp.nodes.get(emitter_id.0) else {
365 continue;
366 };
367 emit_particles(state, comp, node, emitter_hash, frame, t, expr);
368 }
369
370 // A newborn is damped by friction and then integrated once on its birth frame; other forces
371 // only start acting next frame.
372 for (mod_id, scope) in &plan.modifiers {
373 let Some(node) = comp.nodes.get(mod_id.0) else {
374 continue;
375 };
376 if matches!(node.kind.as_str(), "pDrag" | "pFriction") {
377 apply_modifier(&mut state.particles[first_new..], comp, node, scope, t, expr);
378 }
379 }
380 for p in &mut state.particles[first_new..] {
381 for axis in 0..3 {
382 p.pos[axis] += p.vel[axis];
383 }
384 p.rot_z += p.spin_z;
385 }
386 }
387
388 fn emit_particles(
389 state: &mut SimState,
390 comp: &Comp,
391 node: &Node,
392 emitter_hash: u64,
393 frame: i64,
394 t: f64,
395 expr: &ExprEngine,
396 ) {
397 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
398 let mut rng = SplitMix64::from_parts(seed, frame, &node.name);
399
400 let number = comp.eval_number(node, "Number", t, 10.0, expr).max(0.0);
401 let number_var = comp
402 .eval_number(node, "NumberVariance", t, 0.0, expr)
403 .max(0.0);
404
405 let rate = (number + rng.signed() * number_var).max(0.0);
406 let accum = state.emit_accum.entry(emitter_hash).or_insert(0.0);
407 *accum += rate;
408 let mut emit_count = accum.floor() as usize;
409 *accum -= emit_count as f64;
410
411 if emit_count == 0 {
412 return;
413 }
414 let remaining_cap = MAX_PARTICLES.saturating_sub(state.particles.len());
415 if emit_count > remaining_cap {
416 emit_count = remaining_cap;
417 }
418
419 let lifespan_base = comp.eval_number(node, "Lifespan", t, 100.0, expr).max(1.0);
420 let lifespan_var = comp
421 .eval_number(node, "LifespanVariance", t, 0.0, expr)
422 .max(0.0);
423 let pos_var = comp
424 .eval_number(node, "PositionVariance", t, 0.0, expr)
425 .max(0.0);
426
427 let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr);
428 let vel_var = comp
429 .eval_number(node, "VelocityVariance", t, 0.0, expr)
430 .max(0.0);
431 let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr);
432 let angle_var = comp
433 .eval_number(node, "AngleVariance", t, 0.0, expr)
434 .max(0.0);
435 let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr);
436 let angle_z_var = comp
437 .eval_number(node, "AngleZVariance", t, 0.0, expr)
438 .max(0.0);
439
440 let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr);
441 let rot_z_var = comp
442 .eval_number(node, "RotationZVariance", t, 0.0, expr)
443 .max(0.0);
444 let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr);
445 let spin_z_var = comp
446 .eval_number(node, "SpinZVariance", t, 0.0, expr)
447 .max(0.0);
448
449 let base_r = comp.eval_number(node, "ParticleStyle.Red", t, 1.0, expr);
450 let base_g = comp.eval_number(node, "ParticleStyle.Green", t, 1.0, expr);
451 let base_b = comp.eval_number(node, "ParticleStyle.Blue", t, 1.0, expr);
452 let base_a = comp.eval_number(node, "ParticleStyle.Alpha", t, 1.0, expr);
453
454 let red_lo_off = comp.eval_number(node, "ParticleStyle.RedLow", t, 0.0, expr);
455 let red_hi_off = comp.eval_number(node, "ParticleStyle.RedHigh", t, 0.0, expr);
456 let green_lo_off = comp.eval_number(node, "ParticleStyle.GreenLow", t, 0.0, expr);
457 let green_hi_off = comp.eval_number(node, "ParticleStyle.GreenHigh", t, 0.0, expr);
458 let blue_lo_off = comp.eval_number(node, "ParticleStyle.BlueLow", t, 0.0, expr);
459 let blue_hi_off = comp.eval_number(node, "ParticleStyle.BlueHigh", t, 0.0, expr);
460 let alpha_lo_off = comp.eval_number(node, "ParticleStyle.AlphaLow", t, 0.0, expr);
461 let alpha_hi_off = comp.eval_number(node, "ParticleStyle.AlphaHigh", t, 0.0, expr);
462
463 let color_var = comp.eval_number(node, "ParticleStyle.ColorVariance", t, 0.0, expr) > 0.5
464 || red_lo_off.abs() > 1e-9
465 || red_hi_off.abs() > 1e-9
466 || green_lo_off.abs() > 1e-9
467 || green_hi_off.abs() > 1e-9
468 || blue_lo_off.abs() > 1e-9
469 || blue_hi_off.abs() > 1e-9
470 || alpha_lo_off.abs() > 1e-9
471 || alpha_hi_off.abs() > 1e-9;
472
473 let r_lo = (base_r + red_lo_off).clamp(0.0, 1.0);
474 let r_hi = (base_r + red_hi_off).clamp(0.0, 1.0);
475 let g_lo = (base_g + green_lo_off).clamp(0.0, 1.0);
476 let g_hi = (base_g + green_hi_off).clamp(0.0, 1.0);
477 let b_lo = (base_b + blue_lo_off).clamp(0.0, 1.0);
478 let b_hi = (base_b + blue_hi_off).clamp(0.0, 1.0);
479 let a_lo = (base_a + alpha_lo_off).clamp(0.0, 1.0);
480 let a_hi = (base_a + alpha_hi_off).clamp(0.0, 1.0);
481
482 // Fusion's ParticleStyle.Size defaults to 0.1 across all styles.
483 let size_base = comp
484 .eval_number(node, "ParticleStyle.Size", t, 0.1, expr)
485 .max(0.0);
486 let size_var = comp
487 .eval_number(node, "ParticleStyle.SizeVariance", t, 0.0, expr)
488 .max(0.0);
489
490 let region = RegionSpec::from_node(comp, node, t, expr);
491 state.particles.reserve(emit_count);
492
493 for _ in 0..emit_count {
494 let mut pos = region.sample(&mut rng);
495 if pos_var > 0.0 {
496 pos[0] += rng.signed() * pos_var;
497 pos[1] += rng.signed() * pos_var;
498 pos[2] += rng.signed() * pos_var;
499 }
500
501 let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE;
502 let ang = (angle_base + rng.signed() * angle_var).to_radians();
503 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();
504 let cos_z = ang_z.cos();
505 let vel = [
506 speed * ang.cos() * cos_z,
507 speed * ang.sin() * cos_z,
508 speed * ang_z.sin(),
509 ];
510
511 let rot_z = rot_z_base + rng.signed() * rot_z_var;
512 let spin_z = spin_z_base + rng.signed() * spin_z_var;
513 let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0);
514 let size = (size_base + rng.signed() * size_var).max(0.0);
515
516 let color = if color_var {
517 [
518 rng.range(r_lo, r_hi) as f32,
519 rng.range(g_lo, g_hi) as f32,
520 rng.range(b_lo, b_hi) as f32,
521 rng.range(a_lo, a_hi) as f32,
522 ]
523 } else {
524 [
525 base_r.clamp(0.0, 1.0) as f32,
526 base_g.clamp(0.0, 1.0) as f32,
527 base_b.clamp(0.0, 1.0) as f32,
528 base_a.clamp(0.0, 1.0) as f32,
529 ]
530 };
531
532 state.particles.push(Particle {
533 emitter_hash,
534 pos,
535 vel,
536 rot_z,
537 spin_z,
538 age: 0.0,
539 lifespan,
540 size,
541 color,
542 alive: true,
543 });
544 }
545 }
546
547 #[derive(Clone, Copy)]
548 pub(super) enum RegionSpec {
549 Point {
550 center: [f64; 3],
551 },
552 Rect {
553 center: [f64; 3],
554 width: f64,
555 height: f64,
556 },
557 Sphere {
558 center: [f64; 3],
559 radius: f64,
560 },
561 Cube {
562 center: [f64; 3],
563 width: f64,
564 height: f64,
565 depth: f64,
566 },
567 Line {
568 start: [f64; 3],
569 end: [f64; 3],
570 },
571 All,
572 }
573
574 impl RegionSpec {
575 pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
576 let region_name = node.static_str("Region").unwrap_or("SphereRgn");
577 match region_name {
578 "RectRgn" => Self::Rect {
579 center: [
580 comp.eval_number(node, "RectRgn.Translate.X", t, 0.0, expr),
581 comp.eval_number(node, "RectRgn.Translate.Y", t, 0.0, expr),
582 comp.eval_number(node, "RectRgn.Translate.Z", t, 0.0, expr),
583 ],
584 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
585 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
586 },
587 "SphereRgn" => Self::Sphere {
588 center: [
589 comp.eval_number(node, "SphereRgn.Translate.X", t, 0.0, expr),
590 comp.eval_number(node, "SphereRgn.Translate.Y", t, 0.0, expr),
591 comp.eval_number(node, "SphereRgn.Translate.Z", t, 0.0, expr),
592 ],
593 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.1, expr).abs() * 0.5,
594 },
595 "CubeRgn" => Self::Cube {
596 center: [
597 comp.eval_number(node, "CubeRgn.Translate.X", t, 0.0, expr),
598 comp.eval_number(node, "CubeRgn.Translate.Y", t, 0.0, expr),
599 comp.eval_number(node, "CubeRgn.Translate.Z", t, 0.0, expr),
600 ],
601 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
602 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
603 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
604 },
605 "LineRgn" => {
606 let tx = comp.eval_number(node, "LineRgn.Translate.X", t, 0.0, expr);
607 let ty = comp.eval_number(node, "LineRgn.Translate.Y", t, 0.0, expr);
608 let tz = comp.eval_number(node, "LineRgn.Translate.Z", t, 0.0, expr);
609 Self::Line {
610 start: [
611 tx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
612 ty + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
613 tz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
614 ],
615 end: [
616 tx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
617 ty + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
618 tz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
619 ],
620 }
621 }
622 "AllRgn" | "All" => Self::All,
623 _ => Self::Point {
624 center: [
625 comp.eval_number(node, "Point.Translate.X", t, 0.0, expr),
626 comp.eval_number(node, "Point.Translate.Y", t, 0.0, expr),
627 comp.eval_number(node, "Point.Translate.Z", t, 0.0, expr),
628 ],
629 },
630 }
631 }
632
633 fn sample(&self, rng: &mut SplitMix64) -> [f64; 3] {
634 match *self {
635 Self::Point { center } => center,
636 Self::Rect {
637 center,
638 width,
639 height,
640 } => [
641 center[0] + (rng.next_f64() - 0.5) * width,
642 center[1] + (rng.next_f64() - 0.5) * height,
643 center[2],
644 ],
645 Self::Sphere { center, radius } => {
646 let u = rng.next_f64();
647 let v = rng.next_f64();
648 let w = rng.next_f64();
649 let theta = u * std::f64::consts::TAU;
650 let cos_phi = 2.0 * v - 1.0;
651 let sin_phi = (1.0 - cos_phi * cos_phi).max(0.0).sqrt();
652 let r = radius * w.cbrt();
653 [
654 center[0] + r * sin_phi * theta.cos(),
655 center[1] + r * sin_phi * theta.sin(),
656 center[2] + r * cos_phi,
657 ]
658 }
659 Self::Cube {
660 center,
661 width,
662 height,
663 depth,
664 } => [
665 center[0] + (rng.next_f64() - 0.5) * width,
666 center[1] + (rng.next_f64() - 0.5) * height,
667 center[2] + (rng.next_f64() - 0.5) * depth,
668 ],
669 Self::Line { start, end } => {
670 let u = rng.next_f64();
671 [
672 start[0] + (end[0] - start[0]) * u,
673 start[1] + (end[1] - start[1]) * u,
674 start[2] + (end[2] - start[2]) * u,
675 ]
676 }
677 Self::All => [0.0, 0.0, 0.0],
678 }
679 }
680
681 fn contains(&self, p: [f64; 3]) -> bool {
682 match *self {
683 Self::All => true,
684 Self::Point { center } => {
685 let dx = p[0] - center[0];
686 let dy = p[1] - center[1];
687 let dz = p[2] - center[2];
688 dx * dx + dy * dy + dz * dz <= 1e-4
689 }
690 Self::Rect {
691 center,
692 width,
693 height,
694 } => {
695 (p[0] - center[0]).abs() <= width * 0.5
696 && (p[1] - center[1]).abs() <= height * 0.5
697 }
698 Self::Sphere { center, radius } => {
699 let dx = p[0] - center[0];
700 let dy = p[1] - center[1];
701 let dz = p[2] - center[2];
702 dx * dx + dy * dy + dz * dz <= radius * radius
703 }
704 Self::Cube {
705 center,
706 width,
707 height,
708 depth,
709 } => {
710 (p[0] - center[0]).abs() <= width * 0.5
711 && (p[1] - center[1]).abs() <= height * 0.5
712 && (p[2] - center[2]).abs() <= depth * 0.5
713 }
714 Self::Line { start, end } => {
715 let vx = end[0] - start[0];
716 let vy = end[1] - start[1];
717 let vz = end[2] - start[2];
718 let len_sq = vx * vx + vy * vy + vz * vz;
719 let u = if len_sq > 1e-9 {
720 (((p[0] - start[0]) * vx + (p[1] - start[1]) * vy + (p[2] - start[2]) * vz)
721 / len_sq)
722 .clamp(0.0, 1.0)
723 } else {
724 0.0
725 };
726 let cx = start[0] + vx * u;
727 let cy = start[1] + vy * u;
728 let cz = start[2] + vz * u;
729 let dx = p[0] - cx;
730 let dy = p[1] - cy;
731 let dz = p[2] - cz;
732 dx * dx + dy * dy + dz * dz <= 1e-3
733 }
734 }
735 }
736
737 /// Parses a `pBounce` region (supports `LineRgn`, `RectRgn`, `CubeRgn`, `SphereRgn`,
738 /// `MeshRegion`, and `Transform3DOp.Translate` fallback).
739 fn from_bounce_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
740 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", t, 0.0, expr);
741 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", t, 0.0, expr);
742 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", t, 0.0, expr);
743 match node.static_str("Region") {
744 Some("RectRgn") => Self::Rect {
745 center: [
746 comp.eval_number(node, "RectRgn.Translate.X", t, tx, expr),
747 comp.eval_number(node, "RectRgn.Translate.Y", t, ty, expr),
748 comp.eval_number(node, "RectRgn.Translate.Z", t, tz, expr),
749 ],
750 width: comp.eval_number(node, "RectRgn.Width", t, 0.1, expr).abs(),
751 height: comp.eval_number(node, "RectRgn.Height", t, 0.1, expr).abs(),
752 },
753 Some("SphereRgn") => Self::Sphere {
754 center: [
755 comp.eval_number(node, "SphereRgn.Translate.X", t, tx, expr),
756 comp.eval_number(node, "SphereRgn.Translate.Y", t, ty, expr),
757 comp.eval_number(node, "SphereRgn.Translate.Z", t, tz, expr),
758 ],
759 radius: comp.eval_number(node, "SphereRgn.Size", t, 0.5, expr).abs() * 0.5,
760 },
761 Some("CubeRgn") => Self::Cube {
762 center: [
763 comp.eval_number(node, "CubeRgn.Translate.X", t, tx, expr),
764 comp.eval_number(node, "CubeRgn.Translate.Y", t, ty, expr),
765 comp.eval_number(node, "CubeRgn.Translate.Z", t, tz, expr),
766 ],
767 width: comp.eval_number(node, "CubeRgn.Width", t, 0.1, expr).abs(),
768 height: comp.eval_number(node, "CubeRgn.Height", t, 0.1, expr).abs(),
769 depth: comp.eval_number(node, "CubeRgn.Depth", t, 0.1, expr).abs(),
770 },
771 Some("LineRgn") => {
772 let lx = comp.eval_number(node, "LineRgn.Translate.X", t, tx, expr);
773 let ly = comp.eval_number(node, "LineRgn.Translate.Y", t, ty, expr);
774 let lz = comp.eval_number(node, "LineRgn.Translate.Z", t, tz, expr);
775 Self::Line {
776 start: [
777 lx + comp.eval_number(node, "LineRgn.Start.X", t, -0.5, expr),
778 ly + comp.eval_number(node, "LineRgn.Start.Y", t, 0.0, expr),
779 lz + comp.eval_number(node, "LineRgn.Start.Z", t, 0.0, expr),
780 ],
781 end: [
782 lx + comp.eval_number(node, "LineRgn.End.X", t, 0.5, expr),
783 ly + comp.eval_number(node, "LineRgn.End.Y", t, 0.0, expr),
784 lz + comp.eval_number(node, "LineRgn.End.Z", t, 0.0, expr),
785 ],
786 }
787 }
788 Some("MeshRegion") | None => Self::Point { center: [tx, ty, tz] },
789 _ => Self::from_node(comp, node, t, expr),
790 }
791 }
792
793 /// Checks whether a particle stepping `pos -> pos + vel` collides with this bounce region.
794 /// Returns `(contact_pos, outward_unit_normal)` when a reflection should occur.
795 fn bounce_collision(&self, pos: [f64; 3], vel: [f64; 3]) -> Option<([f64; 3], [f64; 3])> {
796 let next = [pos[0] + vel[0], pos[1] + vel[1], pos[2] + vel[2]];
797 match *self {
798 Self::Line { start, end } => {
799 let sx = end[0] - start[0];
800 let sy = end[1] - start[1];
801 let len_sq = sx * sx + sy * sy;
802 let len = len_sq.sqrt();
803 if len < 1e-9 {
804 return None;
805 }
806 let mut n = [-sy / len, sx / len, 0.0];
807 let d0 = (pos[0] - start[0]) * n[0] + (pos[1] - start[1]) * n[1];
808 let d1 = (next[0] - start[0]) * n[0] + (next[1] - start[1]) * n[1];
809 let crosses = (d0 * d1 <= 0.0 && (d0.abs() > 1e-12 || d1.abs() > 1e-12))
810 || d1.abs() <= 1e-4;
811 if !crosses {
812 return None;
813 }
814 let alpha = if (d0 - d1).abs() > 1e-12 {
815 (d0 / (d0 - d1)).clamp(0.0, 1.0)
816 } else {
817 1.0
818 };
819 let hit = [
820 pos[0] + vel[0] * alpha,
821 pos[1] + vel[1] * alpha,
822 pos[2] + vel[2] * alpha,
823 ];
824 let u = ((hit[0] - start[0]) * sx + (hit[1] - start[1]) * sy) / len_sq;
825 if !(-1e-4..=1.0 + 1e-4).contains(&u) {
826 return None;
827 }
828 let vn = vel[0] * n[0] + vel[1] * n[1];
829 if vn > 0.0 {
830 n[0] = -n[0];
831 n[1] = -n[1];
832 }
833 if vel[0] * n[0] + vel[1] * n[1] >= -1e-12 {
834 return None;
835 }
836 Some(([hit[0] + n[0] * 1e-5, hit[1] + n[1] * 1e-5, hit[2]], n))
837 }
838 Self::Sphere { center, radius } => {
839 if radius < 1e-6 {
840 return None;
841 }
842 let dp = [pos[0] - center[0], pos[1] - center[1], pos[2] - center[2]];
843 let dn = [next[0] - center[0], next[1] - center[1], next[2] - center[2]];
844 let r_pos = (dp[0] * dp[0] + dp[1] * dp[1] + dp[2] * dp[2]).sqrt();
845 let r_next = (dn[0] * dn[0] + dn[1] * dn[1] + dn[2] * dn[2]).sqrt();
846 if r_pos > radius && r_next > radius {
847 return None;
848 }
849 let ref_v = if r_pos > 1e-9 {
850 dp
851 } else if r_next > 1e-9 {
852 dn
853 } else {
854 [0.0, 1.0, 0.0]
855 };
856 let r_len = (ref_v[0] * ref_v[0] + ref_v[1] * ref_v[1] + ref_v[2] * ref_v[2])
857 .sqrt()
858 .max(1e-9);
859 let mut n = [ref_v[0] / r_len, ref_v[1] / r_len, ref_v[2] / r_len];
860 if r_pos < radius && r_next >= radius {
861 n = [-n[0], -n[1], -n[2]];
862 let pushed = [
863 center[0] - n[0] * (radius - 1e-5).max(0.0),
864 center[1] - n[1] * (radius - 1e-5).max(0.0),
865 center[2] - n[2] * (radius - 1e-5).max(0.0),
866 ];
867 return Some((pushed, n));
868 }
869 let pushed = [
870 center[0] + n[0] * (radius + 1e-5),
871 center[1] + n[1] * (radius + 1e-5),
872 center[2] + n[2] * (radius + 1e-5),
873 ];
874 Some((pushed, n))
875 }
876 Self::Rect {
877 center,
878 width,
879 height,
880 } => {
881 let hx = width * 0.5;
882 let hy = height * 0.5;
883 if hy < 1e-6 {
884 let line = Self::Line {
885 start: [center[0] - hx, center[1], center[2]],
886 end: [center[0] + hx, center[1], center[2]],
887 };
888 return line.bounce_collision(pos, vel);
889 }
890 if hx < 1e-6 {
891 let line = Self::Line {
892 start: [center[0], center[1] - hy, center[2]],
893 end: [center[0], center[1] + hy, center[2]],
894 };
895 return line.bounce_collision(pos, vel);
896 }
897 bounce_aabb(pos, vel, center, [hx, hy, 1e6], false)
898 }
899 Self::Cube {
900 center,
901 width,
902 height,
903 depth,
904 } => bounce_aabb(pos, vel, center, [width * 0.5, height * 0.5, depth * 0.5], true),
905 Self::Point { center } => {
906 let cy = center[1];
907 let d0 = pos[1] - cy;
908 let d1 = next[1] - cy;
909 if d0 * d1 <= 0.0 || d1.abs() <= 1e-5 {
910 let ny = if vel[1] < 0.0 {
911 1.0
912 } else if vel[1] > 0.0 {
913 -1.0
914 } else {
915 return None;
916 };
917 let alpha = if (d0 - d1).abs() > 1e-12 {
918 (d0 / (d0 - d1)).clamp(0.0, 1.0)
919 } else {
920 1.0
921 };
922 let hit = [
923 pos[0] + vel[0] * alpha,
924 cy + ny * 1e-5,
925 pos[2] + vel[2] * alpha,
926 ];
927 return Some((hit, [0.0, ny, 0.0]));
928 }
929 None
930 }
931 Self::All => None,
932 }
933 }
934 }
935
936 /// Slab-method segment-vs-AABB bounce helper (2D when `check_z == false`, 3D when `check_z == true`).
937 fn bounce_aabb(
938 pos: [f64; 3],
939 vel: [f64; 3],
940 center: [f64; 3],
941 half: [f64; 3],
942 check_z: bool,
943 ) -> Option<([f64; 3], [f64; 3])> {
944 let axes = if check_z { 3 } else { 2 };
945 let mut inside_pos = true;
946 for a in 0..axes {
947 if (pos[a] - center[a]).abs() > half[a] {
948 inside_pos = false;
949 break;
950 }
951 }
952
953 if inside_pos {
954 let mut best_axis = 0usize;
955 let mut best_pen = f64::INFINITY;
956 let mut best_sign = 1.0f64;
957 for a in 0..axes {
958 let delta = pos[a] - center[a];
959 let pen = half[a] - delta.abs();
960 if pen < best_pen {
961 best_pen = pen;
962 best_axis = a;
963 best_sign = if delta >= 0.0 { 1.0 } else { -1.0 };
964 }
965 }
966 let mut n = [0.0; 3];
967 n[best_axis] = best_sign;
968 let mut pushed = pos;
969 pushed[best_axis] = center[best_axis] + best_sign * (half[best_axis] + 1e-5);
970 return Some((pushed, n));
971 }
972
973 let mut t_min = 0.0_f64;
974 let mut t_max = 1.0_f64;
975 let mut hit_axis = 0usize;
976 let mut hit_sign = 1.0_f64;
977
978 for a in 0..axes {
979 let min_b = center[a] - half[a];
980 let max_b = center[a] + half[a];
981 if vel[a].abs() < 1e-12 {
982 if pos[a] < min_b || pos[a] > max_b {
983 return None;
984 }
985 } else {
986 let inv = 1.0 / vel[a];
987 let mut t1 = (min_b - pos[a]) * inv;
988 let mut t2 = (max_b - pos[a]) * inv;
989 let mut s = -1.0;
990 if t1 > t2 {
991 std::mem::swap(&mut t1, &mut t2);
992 s = 1.0;
993 }
994 if t1 > t_min {
995 t_min = t1;
996 hit_axis = a;
997 hit_sign = s;
998 }
999 t_max = t_max.min(t2);
1000 if t_min > t_max {
1001 return None;
1002 }
1003 }
1004 }
1005
1006 let mut n = [0.0; 3];
1007 n[hit_axis] = hit_sign;
1008 let hit = [
1009 pos[0] + vel[0] * t_min + n[0] * 1e-5,
1010 pos[1] + vel[1] * t_min + n[1] * 1e-5,
1011 pos[2] + vel[2] * t_min + n[2] * 1e-5,
1012 ];
1013 Some((hit, n))
1014 }
1015
1016 fn apply_modifier(
1017 particles: &mut [Particle],
1018 comp: &Comp,
1019 node: &Node,
1020 scope: &HashSet<u64>,
1021 t: f64,
1022 expr: &ExprEngine,
1023 ) {
1024 match node.kind.as_str() {
1025 "pPointForce" => {
1026 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
1027 if strength.abs() < 1e-12 {
1028 return;
1029 }
1030 let power = comp.eval_number(node, "Power", t, 2.0, expr);
1031 let tx = comp.eval_number(node, "Translate.X", t, 0.0, expr);
1032 let ty = comp.eval_number(node, "Translate.Y", t, 0.0, expr);
1033 let tz = comp.eval_number(node, "Translate.Z", t, 0.0, expr);
1034
1035 for p in particles.iter_mut() {
1036 if !p.alive || !scope.contains(&p.emitter_hash) {
1037 continue;
1038 }
1039 let dx = tx - p.pos[0];
1040 let dy = ty - p.pos[1];
1041 let dz = tz - p.pos[2];
1042 let dist = (dx * dx + dy * dy + dz * dz).sqrt();
1043 if dist < 1e-7 {
1044 continue;
1045 }
1046 let falloff = dist.max(0.005).powf(power);
1047 let mag = (strength * POINT_FORCE_SCALE / falloff).clamp(-0.25, 0.25);
1048 let inv_d = 1.0 / dist;
1049 p.vel[0] += dx * inv_d * mag;
1050 p.vel[1] += dy * inv_d * mag;
1051 p.vel[2] += dz * inv_d * mag;
1052 }
1053 }
1054 "pDirectionalForce" => {
1055 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
1056 if strength.abs() < 1e-12 {
1057 return;
1058 }
1059 let dir = comp
1060 .eval_number(node, "Direction", t, -90.0, expr)
1061 .to_radians();
1062 let dir_z = comp
1063 .eval_number(node, "DirectionZ", t, 0.0, expr)
1064 .to_radians();
1065 let mag = strength * VELOCITY_SCALE * VELOCITY_SCALE;
1066 let ax = mag * dir.cos() * dir_z.cos();
1067 let ay = mag * dir.sin() * dir_z.cos();
1068 let az = mag * dir_z.sin();
1069
1070 for p in particles.iter_mut() {
1071 if !p.alive || !scope.contains(&p.emitter_hash) {
1072 continue;
1073 }
1074 p.vel[0] += ax;
1075 p.vel[1] += ay;
1076 p.vel[2] += az;
1077 }
1078 }
1079 "pDrag" | "pFriction" => {
1080 let vel_fric = if node.kind == "pFriction" || !node.inputs.contains_key("Drag") {
1081 comp.eval_number(node, "VelocityFriction", t, 0.05, expr)
1082 } else {
1083 comp.eval_number(node, "Drag", t, 0.05, expr)
1084 };
1085 let damp = (1.0 - vel_fric).clamp(0.0, 1.0);
1086 let spin_damp = if node.kind == "pFriction" || node.inputs.contains_key("SpinFriction") {
1087 (1.0 - comp.eval_number(node, "SpinFriction", t, 0.05, expr)).clamp(0.0, 1.0)
1088 } else {
1089 1.0
1090 };
1091 for p in particles.iter_mut() {
1092 if !p.alive || !scope.contains(&p.emitter_hash) {
1093 continue;
1094 }
1095 p.vel[0] *= damp;
1096 p.vel[1] *= damp;
1097 p.vel[2] *= damp;
1098 p.spin_z *= spin_damp;
1099 }
1100 }
1101 "pTurbulence" => {
1102 let sx = comp.eval_number(node, "XStrength", t, 0.1, expr);
1103 let sy = comp.eval_number(node, "YStrength", t, 0.1, expr);
1104 let sz = comp.eval_number(node, "ZStrength", t, 0.1, expr);
1105 if sx.abs() < 1e-12 && sy.abs() < 1e-12 && sz.abs() < 1e-12 {
1106 return;
1107 }
1108 let density = comp.eval_number(node, "Density", t, 10.0, expr).max(0.01);
1109 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as u64;
1110 let time_shift = t * 0.03;
1111
1112 for p in particles.iter_mut() {
1113 if !p.alive || !scope.contains(&p.emitter_hash) {
1114 continue;
1115 }
1116 let qx = p.pos[0] * density + time_shift;
1117 let qy = p.pos[1] * density - time_shift * 0.7;
1118 let qz = p.pos[2] * density;
1119 let nx = value_noise_3d(qx, qy, qz, seed);
1120 let ny =
1121 value_noise_3d(qx + 31.7, qy + 17.3, qz + 47.1, seed ^ 0x517C_C1B7_2722_0A95);
1122 let nz =
1123 value_noise_3d(qx - 19.4, qy + 53.9, qz - 11.2, seed ^ 0x9E37_79B9_7F4A_7C15);
1124 p.vel[0] += nx * sx * TURBULENCE_SCALE;
1125 p.vel[1] += ny * sy * TURBULENCE_SCALE;
1126 p.vel[2] += nz * sz * TURBULENCE_SCALE;
1127 }
1128 }
1129 "pKill" => {
1130 let region = if node.static_str("Region").is_some() {
1131 RegionSpec::from_node(comp, node, t, expr)
1132 } else {
1133 RegionSpec::All
1134 };
1135 let kill_outside = matches!(
1136 node.static_str("RegionMode"),
1137 Some("Outside") | Some("Leaving")
1138 );
1139 for p in particles.iter_mut() {
1140 if !p.alive || !scope.contains(&p.emitter_hash) {
1141 continue;
1142 }
1143 let inside = region.contains(p.pos);
1144 if (!kill_outside && inside) || (kill_outside && !inside) {
1145 p.alive = false;
1146 }
1147 }
1148 }
1149 "pBounce" => {
1150 let region = RegionSpec::from_bounce_node(comp, node, t, expr);
1151 let elasticity = comp.eval_number(node, "Elasticity", t, 1.0, expr).clamp(0.0, 2.0);
1152 let variance = comp.eval_number(node, "Variance", t, 0.0, expr).max(0.0);
1153 let friction = comp.eval_number(node, "Friction", t, 0.0, expr).clamp(0.0, 1.0);
1154 let roughness = comp.eval_number(node, "Roughness", t, 0.0, expr).max(0.0);
1155 let spin = comp.eval_number(node, "Spin", t, 0.0, expr);
1156 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
1157 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
1158
1159 for p in particles.iter_mut() {
1160 if !p.alive || !scope.contains(&p.emitter_hash) {
1161 continue;
1162 }
1163 let Some((pushed_pos, n)) = region.bounce_collision(p.pos, p.vel) else {
1164 continue;
1165 };
1166 let vn = p.vel[0] * n[0] + p.vel[1] * n[1] + p.vel[2] * n[2];
1167 if vn < 0.0 {
1168 let e = (elasticity * (1.0 + rng.signed() * variance)).clamp(0.0, 2.0);
1169 let t_damp = (1.0 - friction).clamp(0.0, 1.0);
1170 let vnx = vn * n[0];
1171 let vny = vn * n[1];
1172 let vnz = vn * n[2];
1173 let vtx = p.vel[0] - vnx;
1174 let vty = p.vel[1] - vny;
1175 let vtz = p.vel[2] - vnz;
1176 p.vel[0] = vtx * t_damp - vnx * e;
1177 p.vel[1] = vty * t_damp - vny * e;
1178 p.vel[2] = vtz * t_damp - vnz * e;
1179 if roughness > 1e-6 {
1180 let scatter = roughness * 0.01 * vn.abs();
1181 p.vel[0] += rng.signed() * scatter;
1182 p.vel[1] += rng.signed() * scatter;
1183 p.vel[2] += rng.signed() * scatter;
1184 }
1185 if spin.abs() > 1e-9 {
1186 p.spin_z += spin * (1.0 + 0.5 * rng.signed());
1187 }
1188 p.pos = pushed_pos;
1189 }
1190 }
1191 }
1192 _ => {}
1193 }
1194 }
1195
1196 /// Smooth deterministic 3D value noise in `[-1.0, 1.0]`.
1197 fn value_noise_3d(x: f64, y: f64, z: f64, seed: u64) -> f64 {
1198 let xi = x.floor() as i64;
1199 let yi = y.floor() as i64;
1200 let zi = z.floor() as i64;
1201 let xf = x - xi as f64;
1202 let yf = y - yi as f64;
1203 let zf = z - zi as f64;
1204
1205 let u = xf * xf * (3.0 - 2.0 * xf);
1206 let v = yf * yf * (3.0 - 2.0 * yf);
1207 let w = zf * zf * (3.0 - 2.0 * zf);
1208
1209 let n000 = lattice_hash(xi, yi, zi, seed);
1210 let n100 = lattice_hash(xi + 1, yi, zi, seed);
1211 let n010 = lattice_hash(xi, yi + 1, zi, seed);
1212 let n110 = lattice_hash(xi + 1, yi + 1, zi, seed);
1213 let n001 = lattice_hash(xi, yi, zi + 1, seed);
1214 let n101 = lattice_hash(xi + 1, yi, zi + 1, seed);
1215 let n011 = lattice_hash(xi, yi + 1, zi + 1, seed);
1216 let n111 = lattice_hash(xi + 1, yi + 1, zi + 1, seed);
1217
1218 let nx00 = n000 + (n100 - n000) * u;
1219 let nx10 = n010 + (n110 - n010) * u;
1220 let nx01 = n001 + (n101 - n001) * u;
1221 let nx11 = n011 + (n111 - n011) * u;
1222
1223 let nxy0 = nx00 + (nx10 - nx00) * v;
1224 let nxy1 = nx01 + (nx11 - nx01) * v;
1225
1226 nxy0 + (nxy1 - nxy0) * w
1227 }
1228
1229 #[inline]
1230 fn lattice_hash(x: i64, y: i64, z: i64, seed: u64) -> f64 {
1231 let mut h = seed
1232 ^ (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
1233 ^ (y as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9)
1234 ^ (z as u64).wrapping_mul(0x94D0_49BB_1331_11EB);
1235 h = (h ^ (h >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1236 h = (h ^ (h >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
1237 h ^= h >> 31;
1238 let unit = (h >> 11) as f64 * (1.0 / ((1u64 << 53) as f64));
1239 unit * 2.0 - 1.0
1240 }
1241}
1242
1243/// Optimized 2D particle rasterization (points, separable Gaussian blobs, NGons, and bitmap sprites).
1244mod raster {
1245 use std::collections::HashMap;
1246
1247 use model::{Comp, ExprEngine, Gradient, Node, NodeId};
1248
1249 use super::{
1250 BLOB_SIGMA_PER_SIZE, CAMERA_DISTANCE, Particle, ParticleStyleKind, SpriteImage,
1251 };
1252
1253 const INV_255: f32 = 1.0 / 255.0;
1254
1255 pub(super) struct DrawCmd {
1256 min_x: usize,
1257 max_x: usize,
1258 min_y: usize,
1259 max_y: usize,
1260 color: [f32; 4],
1261 shape: DrawShape,
1262 }
1263
1264 enum DrawShape {
1265 Point,
1266 Blob {
1267 cx: f64,
1268 cy: f64,
1269 inv_two_sigma_sq: f64,
1270 },
1271 NGon {
1272 cx: f64,
1273 cy: f64,
1274 inv_two_sigma_sq: f64,
1275 inv_half_period: f64,
1276 spike_period: f64,
1277 phase: f64,
1278 sharpness: f64,
1279 },
1280 Bitmap {
1281 emitter_idx: usize,
1282 cx: f64,
1283 cy: f64,
1284 draw_w: f64,
1285 draw_h: f64,
1286 rot_z_deg: f64,
1287 },
1288 }
1289
1290 struct EmitterRenderProps<'a> {
1291 emitter_hash: u64,
1292 style: ParticleStyleKind,
1293 /// Owned 1x1 tiny-background sprite, if applicable.
1294 tiny_sprite: Option<([f64; 2], SpriteImage)>,
1295 /// External sprite reference + nominal dimensions when not a tiny background.
1296 ext_sprite: Option<(&'a SpriteImage, [f64; 2])>,
1297 ngon_sides: f64,
1298 size_over_life: Option<&'a model::BezierSpline>,
1299 fade_in: f64,
1300 fade_out: f64,
1301 color_over_life: Option<Gradient>,
1302 }
1303
1304 impl<'a> EmitterRenderProps<'a> {
1305 #[inline]
1306 fn resolved_sprite(&self) -> Option<(&SpriteImage, [f64; 2])> {
1307 match &self.tiny_sprite {
1308 Some((nominal, sprite)) => Some((sprite, *nominal)),
1309 None => self.ext_sprite,
1310 }
1311 }
1312 }
1313
1314 fn collect_emitter_render_props<'a>(
1315 comp: &'a Comp,
1316 emitter_nodes: &HashMap<u64, NodeId>,
1317 time: f64,
1318 expr: &ExprEngine,
1319 sprites: &'a HashMap<NodeId, SpriteImage>,
1320 ) -> Vec<EmitterRenderProps<'a>> {
1321 let mut list = Vec::with_capacity(emitter_nodes.len());
1322 for (&emitter_hash, &emitter_id) in emitter_nodes {
1323 let Some(node) = comp.nodes.get(emitter_id.0) else {
1324 continue;
1325 };
1326 let style = match node.static_str("Style") {
1327 Some("ParticleStyleBitmap") => ParticleStyleKind::Bitmap,
1328 Some("ParticleStyleBlob") => ParticleStyleKind::Blob,
1329 Some("ParticleStyleNGon") => ParticleStyleKind::NGon,
1330 Some("ParticleStyleBrush") => ParticleStyleKind::Brush,
1331 _ => ParticleStyleKind::Point,
1332 };
1333 let size_over_life = node
1334 .inputs
1335 .get("ParticleStyle.SizeOverLife")
1336 .and_then(|b| b.source_op.as_deref())
1337 .and_then(|src| comp.splines.get(src));
1338 let fade_in = comp
1339 .eval_number(node, "ParticleStyle.FadeIn", time, 0.0, expr)
1340 .clamp(0.0, 1.0);
1341 let fade_out = comp
1342 .eval_number(node, "ParticleStyle.FadeOut", time, 1.0, expr)
1343 .clamp(0.0, 1.0);
1344 let color_over_life_on =
1345 comp.eval_number(node, "ParticleStyle.ColorOverLifeControls", time, 0.0, expr)
1346 > 0.5;
1347 let color_over_life = if color_over_life_on {
1348 comp.eval_gradient(node, "ParticleStyle.ColorOverLife", time)
1349 } else {
1350 None
1351 };
1352 let tiny_sprite = tiny_background_sprite(comp, node, time, expr);
1353 let ext_sprite = if tiny_sprite.is_none() && style == ParticleStyleKind::Bitmap {
1354 sprites
1355 .get(&emitter_id)
1356 .filter(|s| {
1357 s.size[0] > 0
1358 && s.size[1] > 0
1359 && s.rgba.len()
1360 >= (s.size[0] as usize)
1361 .saturating_mul(s.size[1] as usize)
1362 .saturating_mul(4)
1363 })
1364 .map(|s| (s, [s.size[0] as f64, s.size[1] as f64]))
1365 } else {
1366 None
1367 };
1368 list.push(EmitterRenderProps {
1369 emitter_hash,
1370 style,
1371 tiny_sprite,
1372 ext_sprite,
1373 ngon_sides: comp
1374 .eval_number(node, "ParticleStyleNGon.NGonSides", time, 5.0, expr)
1375 .round()
1376 .max(3.0),
1377 size_over_life,
1378 fade_in,
1379 fade_out,
1380 color_over_life,
1381 });
1382 }
1383 list
1384 }
1385
1386 /// Solid sprite for a `Background` tool narrower than 16 px.
1387 fn tiny_background_sprite(
1388 comp: &Comp,
1389 emitter: &Node,
1390 t: f64,
1391 expr: &ExprEngine,
1392 ) -> Option<([f64; 2], SpriteImage)> {
1393 let src = emitter
1394 .connected_node("ParticleStyleBitmap.DropToolsHere")
1395 .and_then(|name| comp.find_node(name))
1396 .map(|id| &comp.nodes[id.0])
1397 .filter(|n| n.kind == "Background")?;
1398 let w = comp.eval_number(src, "Width", t, 0.0, expr);
1399 let h = comp.eval_number(src, "Height", t, 0.0, expr);
1400 if !(w >= 1.0 && h >= 1.0 && (w < 16.0 || h < 16.0)) {
1401 return None;
1402 }
1403 let channel =
1404 |name: &str, default: f64| comp.eval_number(src, name, t, default, expr).clamp(0.0, 1.0);
1405 let a = channel("TopLeftAlpha", 1.0);
1406 let px = |c: f64| (c * a * 255.0 + 0.5) as u8;
1407 let rgba = vec![
1408 px(channel("TopLeftRed", 0.0)),
1409 px(channel("TopLeftGreen", 0.0)),
1410 px(channel("TopLeftBlue", 0.0)),
1411 (a * 255.0 + 0.5) as u8,
1412 ];
1413 Some(([w, h], SpriteImage { size: [1, 1], rgba }))
1414 }
1415
1416 /// Clamps a floating-point `[lo, hi]` interval to `[0, limit - 1]`, returning `None` if empty.
1417 #[inline]
1418 fn clip_bounds(lo: f64, hi: f64, limit: usize) -> Option<(usize, usize)> {
1419 if limit == 0 || !lo.is_finite() || !hi.is_finite() {
1420 return None;
1421 }
1422 let max_i = (limit - 1) as isize;
1423 let a = lo.floor() as isize;
1424 let b = hi.ceil() as isize;
1425 if b < 0 || a > max_i {
1426 return None;
1427 }
1428 let min_u = a.max(0) as usize;
1429 let max_u = b.min(max_i) as usize;
1430 (min_u <= max_u).then_some((min_u, max_u))
1431 }
1432
1433 #[allow(clippy::too_many_arguments)]
1434 pub(super) fn rasterize_particles(
1435 out: &mut [u8],
1436 scratch_accum: &mut Vec<f32>,
1437 scratch_cmds: &mut Vec<DrawCmd>,
1438 dims: [u32; 2],
1439 px_scale: f64,
1440 comp: &Comp,
1441 emitter_nodes: &HashMap<u64, NodeId>,
1442 particles: &[Particle],
1443 time: f64,
1444 expr: &ExprEngine,
1445 sprites: &HashMap<NodeId, SpriteImage>,
1446 ) {
1447 if particles.is_empty() {
1448 return;
1449 }
1450
1451 let w = dims[0] as usize;
1452 let h = dims[1] as usize;
1453 if w == 0 || h == 0 {
1454 return;
1455 }
1456 let w_f = w as f64;
1457 let h_f = h as f64;
1458
1459 let props_list = collect_emitter_render_props(comp, emitter_nodes, time, expr, sprites);
1460 if props_list.is_empty() {
1461 return;
1462 }
1463
1464 scratch_cmds.clear();
1465 if scratch_cmds.capacity() < particles.len() {
1466 scratch_cmds.reserve(particles.len() - scratch_cmds.capacity());
1467 }
1468
1469 let mut dirty_y0 = h;
1470 let mut dirty_y1 = 0usize;
1471 let mut last_hash = u64::MAX;
1472 let mut last_idx = usize::MAX;
1473
1474 for p in particles {
1475 if !p.alive {
1476 continue;
1477 }
1478 let props_idx = if p.emitter_hash == last_hash && last_idx < props_list.len() {
1479 last_idx
1480 } else {
1481 let Some(idx) = props_list.iter().position(|pr| pr.emitter_hash == p.emitter_hash)
1482 else {
1483 continue;
1484 };
1485 last_hash = p.emitter_hash;
1486 last_idx = idx;
1487 idx
1488 };
1489 let props = &props_list[props_idx];
1490
1491 let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0);
1492 let size_mult = props
1493 .size_over_life
1494 .map(|sp| (2.0 * sp.eval(life_frac)).max(0.0))
1495 .unwrap_or(1.0);
1496 let depth_scale = CAMERA_DISTANCE / (CAMERA_DISTANCE + p.pos[2]);
1497 if !(depth_scale > 0.0) {
1498 continue;
1499 }
1500 let size_world = p.size * size_mult * depth_scale;
1501 if size_world <= 1e-6 {
1502 continue;
1503 }
1504
1505 let mut fade = 1.0f64;
1506 if props.fade_in > 1e-6 && life_frac < props.fade_in {
1507 fade *= life_frac / props.fade_in;
1508 }
1509 if props.fade_out < 1.0 - 1e-6 && life_frac > props.fade_out {
1510 fade *= ((1.0 - life_frac) / (1.0 - props.fade_out)).max(0.0);
1511 }
1512
1513 let mut cr = p.color[0];
1514 let mut cg = p.color[1];
1515 let mut cb = p.color[2];
1516 let mut ca = p.color[3] * fade as f32;
1517 if let Some(grad) = &props.color_over_life {
1518 let g = grad.sample(life_frac);
1519 cr *= g[0];
1520 cg *= g[1];
1521 cb *= g[2];
1522 ca *= g[3];
1523 }
1524 ca = ca.clamp(0.0, 1.0);
1525 if ca <= 1e-4 {
1526 continue;
1527 }
1528
1529 let cx = (p.pos[0] * depth_scale + 0.5) * w_f;
1530 let cy = h_f * 0.5 - p.pos[1] * depth_scale * w_f;
1531
1532 if props.style == ParticleStyleKind::Bitmap {
1533 if let Some((_, nominal)) = props.resolved_sprite() {
1534 let draw_w = size_world * nominal[0] * px_scale;
1535 let draw_h = size_world * nominal[1] * px_scale;
1536 if draw_w < 0.5 || draw_h < 0.5 {
1537 continue;
1538 }
1539 let hw = draw_w * 0.5;
1540 let hh = draw_h * 0.5;
1541 let (rx, ry) = if p.rot_z.abs() <= 1e-6 {
1542 (hw + 1.0, hh + 1.0)
1543 } else {
1544 let theta = p.rot_z.to_radians();
1545 let ca_t = theta.cos().abs();
1546 let sa_t = theta.sin().abs();
1547 (hw * ca_t + hh * sa_t + 1.0, hw * sa_t + hh * ca_t + 1.0)
1548 };
1549 let Some((min_x, max_x)) = clip_bounds(cx - rx, cx + rx, w) else {
1550 continue;
1551 };
1552 let Some((min_y, max_y)) = clip_bounds(cy - ry, cy + ry, h) else {
1553 continue;
1554 };
1555 dirty_y0 = dirty_y0.min(min_y);
1556 dirty_y1 = dirty_y1.max(max_y + 1);
1557 scratch_cmds.push(DrawCmd {
1558 min_x,
1559 max_x,
1560 min_y,
1561 max_y,
1562 color: [cr, cg, cb, ca],
1563 shape: DrawShape::Bitmap {
1564 emitter_idx: props_idx,
1565 cx,
1566 cy,
1567 draw_w,
1568 draw_h,
1569 rot_z_deg: p.rot_z,
1570 },
1571 });
1572 continue;
1573 }
1574 }
1575
1576 match props.style {
1577 ParticleStyleKind::Point => {
1578 let ix = cx.floor() as isize;
1579 let iy = cy.floor() as isize;
1580 if ix < 0 || iy < 0 || ix >= w as isize || iy >= h as isize {
1581 continue;
1582 }
1583 let ux = ix as usize;
1584 let uy = iy as usize;
1585 dirty_y0 = dirty_y0.min(uy);
1586 dirty_y1 = dirty_y1.max(uy + 1);
1587 scratch_cmds.push(DrawCmd {
1588 min_x: ux,
1589 max_x: ux,
1590 min_y: uy,
1591 max_y: uy,
1592 color: [cr, cg, cb, ca],
1593 shape: DrawShape::Point,
1594 });
1595 }
1596 ParticleStyleKind::Blob | ParticleStyleKind::Bitmap => {
1597 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1598 if sigma <= 1e-6 {
1599 continue;
1600 }
1601 let inv_two_sigma_sq = 0.5 / (sigma * sigma);
1602 let bound = (4.0 * sigma).min((((ca as f64) * 1.0e5).ln().max(0.0) / inv_two_sigma_sq).sqrt());
1603 let Some((min_x, max_x)) = clip_bounds(cx - bound, cx + bound, w) else {
1604 continue;
1605 };
1606 let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else {
1607 continue;
1608 };
1609 dirty_y0 = dirty_y0.min(min_y);
1610 dirty_y1 = dirty_y1.max(max_y + 1);
1611 scratch_cmds.push(DrawCmd {
1612 min_x,
1613 max_x,
1614 min_y,
1615 max_y,
1616 color: [cr, cg, cb, ca],
1617 shape: DrawShape::Blob {
1618 cx,
1619 cy,
1620 inv_two_sigma_sq,
1621 },
1622 });
1623 }
1624 ParticleStyleKind::NGon => {
1625 let sigma = BLOB_SIGMA_PER_SIZE * size_world * px_scale;
1626 if sigma <= 1e-6 {
1627 continue;
1628 }
1629 let inv_two_sigma_sq = 0.5 / (sigma * sigma);
1630 let bound = (4.0 * sigma).min((((ca as f64) * 1.0e5).ln().max(0.0) / inv_two_sigma_sq).sqrt());
1631 let Some((min_x, max_x)) = clip_bounds(cx - bound, cx + bound, w) else {
1632 continue;
1633 };
1634 let Some((min_y, max_y)) = clip_bounds(cy - bound, cy + bound, h) else {
1635 continue;
1636 };
1637 let sides = props.ngon_sides;
1638 let spike_period = std::f64::consts::TAU / sides;
1639 let phase = std::f64::consts::FRAC_PI_2 + p.rot_z.to_radians();
1640 let sharpness = 4.5 * (3.0 / sides).powf(2.8);
1641 dirty_y0 = dirty_y0.min(min_y);
1642 dirty_y1 = dirty_y1.max(max_y + 1);
1643 scratch_cmds.push(DrawCmd {
1644 min_x,
1645 max_x,
1646 min_y,
1647 max_y,
1648 color: [cr, cg, cb, ca],
1649 shape: DrawShape::NGon {
1650 cx,
1651 cy,
1652 inv_two_sigma_sq,
1653 inv_half_period: 2.0 / spike_period,
1654 spike_period,
1655 phase,
1656 sharpness,
1657 },
1658 });
1659 }
1660 ParticleStyleKind::Brush => {}
1661 }
1662 }
1663
1664 if scratch_cmds.is_empty() || dirty_y0 >= dirty_y1 {
1665 return;
1666 }
1667
1668 let needed_floats = w * h * 4;
1669 if scratch_accum.len() < needed_floats {
1670 scratch_accum.resize(needed_floats, 0.0);
1671 }
1672
1673 rasterize_bands(
1674 out,
1675 &mut scratch_accum[..needed_floats],
1676 w,
1677 dirty_y0,
1678 dirty_y1,
1679 scratch_cmds,
1680 &props_list,
1681 );
1682 }
1683
1684 fn rasterize_bands(
1685 out: &mut [u8],
1686 accum: &mut [f32],
1687 w: usize,
1688 dirty_y0: usize,
1689 dirty_y1: usize,
1690 cmds: &[DrawCmd],
1691 props_list: &[EmitterRenderProps<'_>],
1692 ) {
1693 #[cfg(not(target_arch = "wasm32"))]
1694 {
1695 let dirty_rows = dirty_y1 - dirty_y0;
1696 let dirty_pixels = dirty_rows * w;
1697 if dirty_pixels >= 120_000 && dirty_rows >= 32 && cmds.len() >= 16 {
1698 let workers = std::thread::available_parallelism()
1699 .map(|n| n.get())
1700 .unwrap_or(1)
1701 .min(8)
1702 .min(dirty_rows / 16);
1703 if workers > 1 {
1704 let stride = w * 4;
1705 let rows_per_band = dirty_rows.div_ceil(workers);
1706 let accum_dirty = &mut accum[dirty_y0 * stride..dirty_y1 * stride];
1707 let out_dirty = &mut out[dirty_y0 * stride..dirty_y1 * stride];
1708 std::thread::scope(|scope| {
1709 let mut a_rest = accum_dirty;
1710 let mut o_rest = out_dirty;
1711 let mut band_y0 = dirty_y0;
1712 while band_y0 < dirty_y1 {
1713 let take_rows = rows_per_band.min(dirty_y1 - band_y0);
1714 let take_elems = take_rows * stride;
1715 let (a_band, a_next) = a_rest.split_at_mut(take_elems);
1716 let (o_band, o_next) = o_rest.split_at_mut(take_elems);
1717 a_rest = a_next;
1718 o_rest = o_next;
1719 let band_y1 = band_y0 + take_rows;
1720 scope.spawn(move || {
1721 rasterize_single_band(
1722 o_band,
1723 a_band,
1724 w,
1725 band_y0,
1726 band_y1,
1727 cmds,
1728 props_list,
1729 );
1730 });
1731 band_y0 = band_y1;
1732 }
1733 });
1734 return;
1735 }
1736 }
1737 }
1738
1739 let stride = w * 4;
1740 let start = dirty_y0 * stride;
1741 let end = dirty_y1 * stride;
1742 rasterize_single_band(
1743 &mut out[start..end],
1744 &mut accum[start..end],
1745 w,
1746 dirty_y0,
1747 dirty_y1,
1748 cmds,
1749 props_list,
1750 );
1751 }
1752
1753 fn rasterize_single_band(
1754 out_band: &mut [u8],
1755 accum_band: &mut [f32],
1756 w: usize,
1757 band_y0: usize,
1758 band_y1: usize,
1759 cmds: &[DrawCmd],
1760 props_list: &[EmitterRenderProps<'_>],
1761 ) {
1762 let stride = w * 4;
1763 let mut wx_heap: Vec<f32> = Vec::new();
1764 let mut wx_stack = [0.0f32; 64];
1765
1766 for cmd in cmds {
1767 if cmd.max_y < band_y0 || cmd.min_y >= band_y1 {
1768 continue;
1769 }
1770 let y_lo = cmd.min_y.max(band_y0);
1771 let y_hi = cmd.max_y.min(band_y1 - 1);
1772 let x_lo = cmd.min_x;
1773 let x_hi = cmd.max_x;
1774
1775 match cmd.shape {
1776 DrawShape::Point => {
1777 let pa = cmd.color[3];
1778 let off = (y_lo - band_y0) * stride + x_lo * 4;
1779 let dst = &mut accum_band[off..off + 4];
1780 if pa >= 1.0 - 1e-5 {
1781 dst[0] = cmd.color[0];
1782 dst[1] = cmd.color[1];
1783 dst[2] = cmd.color[2];
1784 dst[3] = 1.0;
1785 } else {
1786 let inv_a = 1.0 - pa;
1787 dst[0] = cmd.color[0] * pa + dst[0] * inv_a;
1788 dst[1] = cmd.color[1] * pa + dst[1] * inv_a;
1789 dst[2] = cmd.color[2] * pa + dst[2] * inv_a;
1790 dst[3] = pa + dst[3] * inv_a;
1791 }
1792 }
1793 DrawShape::Blob {
1794 cx,
1795 cy,
1796 inv_two_sigma_sq,
1797 } => {
1798 let span_x = x_hi - x_lo + 1;
1799 let wx: &mut [f32] = if span_x <= wx_stack.len() {
1800 &mut wx_stack[..span_x]
1801 } else {
1802 wx_heap.resize(span_x, 0.0);
1803 &mut wx_heap[..span_x]
1804 };
1805 for (i, w_slot) in wx.iter_mut().enumerate() {
1806 let dx = (x_lo + i) as f64 + 0.5 - cx;
1807 *w_slot = (-(dx * dx) * inv_two_sigma_sq).exp() as f32;
1808 }
1809
1810 let sa = cmd.color[3];
1811 let sr = cmd.color[0] * sa;
1812 let sg = cmd.color[1] * sa;
1813 let sb = cmd.color[2] * sa;
1814 let row_x_start = x_lo * 4;
1815 let row_x_end = (x_hi + 1) * 4;
1816
1817 for py in y_lo..=y_hi {
1818 let dy = py as f64 + 0.5 - cy;
1819 let wy = (-(dy * dy) * inv_two_sigma_sq).exp() as f32;
1820 let row_a = sa * wy;
1821 if row_a <= 1e-5 {
1822 continue;
1823 }
1824 let row_r = sr * wy;
1825 let row_g = sg * wy;
1826 let row_b = sb * wy;
1827 let row_off = (py - band_y0) * stride;
1828 let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end];
1829 for (dst, &gx) in row_pixels.chunks_exact_mut(4).zip(wx.iter()) {
1830 let pa = row_a * gx;
1831 if pa <= 1e-5 {
1832 continue;
1833 }
1834 let inv_a = 1.0 - pa;
1835 dst[0] = row_r * gx + dst[0] * inv_a;
1836 dst[1] = row_g * gx + dst[1] * inv_a;
1837 dst[2] = row_b * gx + dst[2] * inv_a;
1838 dst[3] = pa + dst[3] * inv_a;
1839 }
1840 }
1841 }
1842 DrawShape::NGon {
1843 cx,
1844 cy,
1845 inv_two_sigma_sq,
1846 inv_half_period,
1847 spike_period,
1848 phase,
1849 sharpness,
1850 } => {
1851 let span_x = x_hi - x_lo + 1;
1852 let wx: &mut [f32] = if span_x <= wx_stack.len() {
1853 &mut wx_stack[..span_x]
1854 } else {
1855 wx_heap.resize(span_x, 0.0);
1856 &mut wx_heap[..span_x]
1857 };
1858 for (i, w_slot) in wx.iter_mut().enumerate() {
1859 let dx = (x_lo + i) as f64 + 0.5 - cx;
1860 *w_slot = (-(dx * dx) * inv_two_sigma_sq).exp() as f32;
1861 }
1862
1863 let sa = cmd.color[3];
1864 let cr = cmd.color[0];
1865 let cg = cmd.color[1];
1866 let cb = cmd.color[2];
1867 let row_x_start = x_lo * 4;
1868 let row_x_end = (x_hi + 1) * 4;
1869
1870 for py in y_lo..=y_hi {
1871 let dy = py as f64 + 0.5 - cy;
1872 let wy = (-(dy * dy) * inv_two_sigma_sq).exp() as f32;
1873 let row_a = sa * wy;
1874 if row_a <= 1e-5 {
1875 continue;
1876 }
1877 let row_off = (py - band_y0) * stride;
1878 let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end];
1879 for (i, dst) in row_pixels.chunks_exact_mut(4).enumerate() {
1880 let env_a = row_a * wx[i];
1881 if env_a <= 1e-5 {
1882 continue;
1883 }
1884 let dx = (x_lo + i) as f64 + 0.5 - cx;
1885 let angle = (-dy).atan2(dx) - phase;
1886 let off = angle.rem_euclid(spike_period);
1887 let to_spike = off.min(spike_period - off);
1888 let shape_w = (1.0 - to_spike * inv_half_period).powf(sharpness) as f32;
1889 let pa = env_a * shape_w;
1890 if pa <= 1e-5 {
1891 continue;
1892 }
1893 let inv_a = 1.0 - pa;
1894 dst[0] = cr * pa + dst[0] * inv_a;
1895 dst[1] = cg * pa + dst[1] * inv_a;
1896 dst[2] = cb * pa + dst[2] * inv_a;
1897 dst[3] = pa + dst[3] * inv_a;
1898 }
1899 }
1900 }
1901 DrawShape::Bitmap {
1902 emitter_idx,
1903 cx,
1904 cy,
1905 draw_w,
1906 draw_h,
1907 rot_z_deg,
1908 } => {
1909 let Some((sprite, _)) = props_list[emitter_idx].resolved_sprite() else {
1910 continue;
1911 };
1912 draw_bitmap_band(
1913 accum_band,
1914 stride,
1915 band_y0,
1916 y_lo,
1917 y_hi,
1918 x_lo,
1919 x_hi,
1920 cx,
1921 cy,
1922 draw_w,
1923 draw_h,
1924 rot_z_deg,
1925 cmd.color,
1926 sprite,
1927 );
1928 }
1929 }
1930 }
1931
1932 // Pack premultiplied f32 -> u8 and simultaneously reset `accum_band` to 0.0
1933 // while the cache lines are hot so `scratch_accum` stays zeroed for the next frame.
1934 for (dst, src) in out_band.iter_mut().zip(accum_band.iter_mut()) {
1935 let v = *src;
1936 *src = 0.0;
1937 *dst = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
1938 }
1939 }
1940
1941 #[allow(clippy::too_many_arguments)]
1942 #[inline]
1943 fn draw_bitmap_band(
1944 accum_band: &mut [f32],
1945 stride: usize,
1946 band_y0: usize,
1947 y_lo: usize,
1948 y_hi: usize,
1949 x_lo: usize,
1950 x_hi: usize,
1951 cx: f64,
1952 cy: f64,
1953 draw_w: f64,
1954 draw_h: f64,
1955 rot_z_deg: f64,
1956 tint: [f32; 4],
1957 sprite: &SpriteImage,
1958 ) {
1959 let inv_dw = 1.0 / draw_w;
1960 let inv_dh = 1.0 / draw_h;
1961 let edge_u = inv_dw * 0.5;
1962 let edge_v = inv_dh * 0.5;
1963 let inv_2edge_u = 1.0 / (2.0 * edge_u);
1964 let inv_2edge_v = 1.0 / (2.0 * edge_v);
1965 let sw_i = sprite.size[0] as usize;
1966 let sh_i = sprite.size[1] as usize;
1967 let row_x_start = x_lo * 4;
1968 let row_x_end = (x_hi + 1) * 4;
1969
1970 // Fast path: axis-aligned (unrotated) sprite.
1971 if rot_z_deg.abs() <= 1e-6 {
1972 let u0 = (x_lo as f64 + 0.5 - cx) * inv_dw + 0.5;
1973 if sw_i == 1 && sh_i == 1 {
1974 let s0 = sprite.rgba[0] as f32 * INV_255 * tint[0] * tint[3];
1975 let s1 = sprite.rgba[1] as f32 * INV_255 * tint[1] * tint[3];
1976 let s2 = sprite.rgba[2] as f32 * INV_255 * tint[2] * tint[3];
1977 let s3 = sprite.rgba[3] as f32 * INV_255 * tint[3];
1978 if s3 <= 1e-5 {
1979 return;
1980 }
1981 for py in y_lo..=y_hi {
1982 let v = (py as f64 + 0.5 - cy) * inv_dh + 0.5;
1983 if v <= -edge_v || v >= 1.0 + edge_v {
1984 continue;
1985 }
1986 let cov_v = ((v + edge_v) * inv_2edge_v)
1987 .min((1.0 + edge_v - v) * inv_2edge_v)
1988 .clamp(0.0, 1.0);
1989 if cov_v <= 1e-4 {
1990 continue;
1991 }
1992 let cov_vf = cov_v as f32;
1993 let row_off = (py - band_y0) * stride;
1994 let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end];
1995 let mut u = u0;
1996 for dst in row_pixels.chunks_exact_mut(4) {
1997 if u > -edge_u && u < 1.0 + edge_u {
1998 let cov_u = ((u + edge_u) * inv_2edge_u)
1999 .min((1.0 + edge_u - u) * inv_2edge_u)
2000 .clamp(0.0, 1.0);
2001 let cov = cov_u as f32 * cov_vf;
2002 if cov > 1e-4 {
2003 let pa = s3 * cov;
2004 if pa > 1e-5 {
2005 let inv_a = 1.0 - pa;
2006 dst[0] = s0 * cov + dst[0] * inv_a;
2007 dst[1] = s1 * cov + dst[1] * inv_a;
2008 dst[2] = s2 * cov + dst[2] * inv_a;
2009 dst[3] = pa + dst[3] * inv_a;
2010 }
2011 }
2012 }
2013 u += inv_dw;
2014 }
2015 }
2016 return;
2017 }
2018
2019 let sw_f = sw_i as f64;
2020 let sh_f = sh_i as f64;
2021 let sw_max = (sw_i - 1) as f64;
2022 let sh_max = (sh_i - 1) as f64;
2023 let tr = tint[0] * INV_255;
2024 let tg = tint[1] * INV_255;
2025 let tb = tint[2] * INV_255;
2026 let ta = tint[3] * INV_255;
2027
2028 for py in y_lo..=y_hi {
2029 let v = (py as f64 + 0.5 - cy) * inv_dh + 0.5;
2030 if v <= -edge_v || v >= 1.0 + edge_v {
2031 continue;
2032 }
2033 let cov_v = ((v + edge_v) * inv_2edge_v)
2034 .min((1.0 + edge_v - v) * inv_2edge_v)
2035 .clamp(0.0, 1.0);
2036 if cov_v <= 1e-4 {
2037 continue;
2038 }
2039 let fy = (v.clamp(0.0, 1.0) * sh_f - 0.5).clamp(0.0, sh_max);
2040 let y0 = fy.floor() as usize;
2041 let y1 = (y0 + 1).min(sh_i - 1);
2042 let ty = (fy - y0 as f64) as f32;
2043 let one_minus_ty = 1.0 - ty;
2044 let row0 = y0 * sw_i;
2045 let row1 = y1 * sw_i;
2046 let cov_vf = cov_v as f32;
2047
2048 let row_off = (py - band_y0) * stride;
2049 let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end];
2050 let mut u = u0;
2051 for dst in row_pixels.chunks_exact_mut(4) {
2052 if u > -edge_u && u < 1.0 + edge_u {
2053 let cov_u = ((u + edge_u) * inv_2edge_u)
2054 .min((1.0 + edge_u - u) * inv_2edge_u)
2055 .clamp(0.0, 1.0);
2056 let cov = cov_u as f32 * cov_vf;
2057 if cov > 1e-4 {
2058 let fx = (u.clamp(0.0, 1.0) * sw_f - 0.5).clamp(0.0, sw_max);
2059 let x0 = fx.floor() as usize;
2060 let x1 = (x0 + 1).min(sw_i - 1);
2061 let tx = (fx - x0 as f64) as f32;
2062 let omt = 1.0 - tx;
2063
2064 let w00 = omt * one_minus_ty;
2065 let w10 = tx * one_minus_ty;
2066 let w01 = omt * ty;
2067 let w11 = tx * ty;
2068
2069 let i00 = (row0 + x0) * 4;
2070 let i10 = (row0 + x1) * 4;
2071 let i01 = (row1 + x0) * 4;
2072 let i11 = (row1 + x1) * 4;
2073
2074 let s_a = sprite.rgba[i00 + 3] as f32 * w00
2075 + sprite.rgba[i10 + 3] as f32 * w10
2076 + sprite.rgba[i01 + 3] as f32 * w01
2077 + sprite.rgba[i11 + 3] as f32 * w11;
2078 let pa = s_a * ta * cov;
2079 if pa > 1e-5 {
2080 let s_r = sprite.rgba[i00] as f32 * w00
2081 + sprite.rgba[i10] as f32 * w10
2082 + sprite.rgba[i01] as f32 * w01
2083 + sprite.rgba[i11] as f32 * w11;
2084 let s_g = sprite.rgba[i00 + 1] as f32 * w00
2085 + sprite.rgba[i10 + 1] as f32 * w10
2086 + sprite.rgba[i01 + 1] as f32 * w01
2087 + sprite.rgba[i11 + 1] as f32 * w11;
2088 let s_b = sprite.rgba[i00 + 2] as f32 * w00
2089 + sprite.rgba[i10 + 2] as f32 * w10
2090 + sprite.rgba[i01 + 2] as f32 * w01
2091 + sprite.rgba[i11 + 2] as f32 * w11;
2092 let inv_a = 1.0 - pa;
2093 dst[0] = s_r * (tr * cov * tint[3]) + dst[0] * inv_a;
2094 dst[1] = s_g * (tg * cov * tint[3]) + dst[1] * inv_a;
2095 dst[2] = s_b * (tb * cov * tint[3]) + dst[2] * inv_a;
2096 dst[3] = pa + dst[3] * inv_a;
2097 }
2098 }
2099 }
2100 u += inv_dw;
2101 }
2102 }
2103 return;
2104 }
2105
2106 // General rotated bitmap path with incremental scanline UV stepping.
2107 let theta = rot_z_deg.to_radians();
2108 let cos_t = theta.cos();
2109 let sin_t = theta.sin();
2110 let du_dx = cos_t * inv_dw;
2111 let dv_dx = sin_t * inv_dh;
2112 let dx0 = (x_lo as f64 + 0.5) - cx;
2113 let sw_f = sw_i as f64;
2114 let sh_f = sh_i as f64;
2115 let sw_max = (sw_i - 1) as f64;
2116 let sh_max = (sh_i - 1) as f64;
2117 let tr = tint[0] * tint[3] * INV_255;
2118 let tg = tint[1] * tint[3] * INV_255;
2119 let tb = tint[2] * tint[3] * INV_255;
2120 let ta = tint[3] * INV_255;
2121
2122 for py in y_lo..=y_hi {
2123 let dy = (py as f64 + 0.5) - cy;
2124 let mut u = (dx0 * cos_t - dy * sin_t) * inv_dw + 0.5;
2125 let mut v = (dx0 * sin_t + dy * cos_t) * inv_dh + 0.5;
2126 let row_off = (py - band_y0) * stride;
2127 let row_pixels = &mut accum_band[row_off + row_x_start..row_off + row_x_end];
2128
2129 for dst in row_pixels.chunks_exact_mut(4) {
2130 if u > -edge_u && u < 1.0 + edge_u && v > -edge_v && v < 1.0 + edge_v {
2131 let cov_u = ((u + edge_u) * inv_2edge_u)
2132 .min((1.0 + edge_u - u) * inv_2edge_u)
2133 .clamp(0.0, 1.0);
2134 let cov_v = ((v + edge_v) * inv_2edge_v)
2135 .min((1.0 + edge_v - v) * inv_2edge_v)
2136 .clamp(0.0, 1.0);
2137 let cov = (cov_u * cov_v) as f32;
2138 if cov > 1e-4 {
2139 let fx = (u.clamp(0.0, 1.0) * sw_f - 0.5).clamp(0.0, sw_max);
2140 let fy = (v.clamp(0.0, 1.0) * sh_f - 0.5).clamp(0.0, sh_max);
2141 let x0 = fx.floor() as usize;
2142 let y0 = fy.floor() as usize;
2143 let x1 = (x0 + 1).min(sw_i - 1);
2144 let y1 = (y0 + 1).min(sh_i - 1);
2145 let tx = (fx - x0 as f64) as f32;
2146 let ty = (fy - y0 as f64) as f32;
2147
2148 let w00 = (1.0 - tx) * (1.0 - ty);
2149 let w10 = tx * (1.0 - ty);
2150 let w01 = (1.0 - tx) * ty;
2151 let w11 = tx * ty;
2152
2153 let i00 = (y0 * sw_i + x0) * 4;
2154 let i10 = (y0 * sw_i + x1) * 4;
2155 let i01 = (y1 * sw_i + x0) * 4;
2156 let i11 = (y1 * sw_i + x1) * 4;
2157
2158 let s_a = sprite.rgba[i00 + 3] as f32 * w00
2159 + sprite.rgba[i10 + 3] as f32 * w10
2160 + sprite.rgba[i01 + 3] as f32 * w01
2161 + sprite.rgba[i11 + 3] as f32 * w11;
2162 let pa = s_a * ta * cov;
2163 if pa > 1e-5 {
2164 let s_r = sprite.rgba[i00] as f32 * w00
2165 + sprite.rgba[i10] as f32 * w10
2166 + sprite.rgba[i01] as f32 * w01
2167 + sprite.rgba[i11] as f32 * w11;
2168 let s_g = sprite.rgba[i00 + 1] as f32 * w00
2169 + sprite.rgba[i10 + 1] as f32 * w10
2170 + sprite.rgba[i01 + 1] as f32 * w01
2171 + sprite.rgba[i11 + 1] as f32 * w11;
2172 let s_b = sprite.rgba[i00 + 2] as f32 * w00
2173 + sprite.rgba[i10 + 2] as f32 * w10
2174 + sprite.rgba[i01 + 2] as f32 * w01
2175 + sprite.rgba[i11 + 2] as f32 * w11;
2176 let inv_a = 1.0 - pa;
2177 dst[0] = s_r * (tr * cov) + dst[0] * inv_a;
2178 dst[1] = s_g * (tg * cov) + dst[1] * inv_a;
2179 dst[2] = s_b * (tb * cov) + dst[2] * inv_a;
2180 dst[3] = pa + dst[3] * inv_a;
2181 }
2182 }
2183 }
2184 u += du_dx;
2185 v += dv_dx;
2186 }
2187 }
2188 }
2189}
2190
2191#[cfg(test)]
2192mod w26c_tests {
2193 use super::*;
2194
2195 #[test]
2196 fn default_size_is_one_tenth_and_pregenerate_frames_emits_preroll() {
2197 let comp_src = r#"
2198Composition {
2199 GlobalRange = { 0, 20 },
2200 RenderRange = { 0, 20 },
2201 Tools = {
2202 E = pEmitter {
2203 Inputs = {
2204 RandomSeed = Input { Value = 42, },
2205 Style = Input { Value = FuID { "ParticleStyleBlob" }, },
2206 Number = Input { Value = 10, },
2207 Velocity = Input { Value = 0.05, },
2208 },
2209 },
2210 R_default = pRender {
2211 Inputs = {
2212 Width = Input { Value = 256, },
2213 Height = Input { Value = 256, },
2214 Input = Input { SourceOp = "E", Source = "Output", },
2215 },
2216 },
2217 R_pre = pRender {
2218 Inputs = {
2219 Width = Input { Value = 256, },
2220 Height = Input { Value = 256, },
2221 PreGenerateFrames = Input { Value = 20, },
2222 Input = Input { SourceOp = "E", Source = "Output", },
2223 },
2224 },
2225 },
2226}
2227"#;
2228 let comp = Comp::from_fusion_str(comp_src).expect("parse comp");
2229 let expr = ExprEngine::new();
2230 let sprites = HashMap::new();
2231
2232 let mut cache = ParticleCache::default();
2233 let img_default = render_particles_2d(
2234 &mut cache,
2235 &comp,
2236 comp.node_by_name["R_default"],
2237 0.0,
2238 [256, 256],
2239 &expr,
2240 &sprites,
2241 );
2242 // Default Size = 0.1 produces compact ~0.33px-sigma blobs (~7 alpha mass for 10 blobs).
2243 let alpha_mass_default: f64 = img_default
2244 .chunks_exact(4)
2245 .map(|px| px[3] as f64 / 255.0)
2246 .sum();
2247 assert!(
2248 alpha_mass_default > 3.0 && alpha_mass_default < 15.0,
2249 "expected Size=0.1 alpha mass in (3, 15), got {alpha_mass_default}"
2250 );
2251 assert!(
2252 cache.scratch_accum.iter().all(|&x| x == 0.0),
2253 "scratch_accum must be zeroed after render"
2254 );
2255
2256 let img_pre = render_particles_2d(
2257 &mut cache,
2258 &comp,
2259 comp.node_by_name["R_pre"],
2260 0.0,
2261 [256, 256],
2262 &expr,
2263 &sprites,
2264 );
2265 let alpha_mass_pre: f64 = img_pre
2266 .chunks_exact(4)
2267 .map(|px| px[3] as f64 / 255.0)
2268 .sum();
2269 assert!(
2270 alpha_mass_pre > alpha_mass_default * 8.0,
2271 "PreGenerateFrames=20 should accumulate ~21x particles (default={alpha_mass_default}, pre={alpha_mass_pre})"
2272 );
2273 assert!(
2274 cache.scratch_accum.iter().all(|&x| x == 0.0),
2275 "scratch_accum must stay zeroed after PreGenerateFrames render"
2276 );
2277 }
2278
2279 #[test]
2280 fn scratch_buffer_reuse_and_parallel_band_determinism() {
2281 let comp_src = r#"
2282Composition {
2283 GlobalRange = { 0, 50 },
2284 RenderRange = { 0, 50 },
2285 Tools = {
2286 E_blob = pEmitter {
2287 Inputs = {
2288 RandomSeed = Input { Value = 11, },
2289 Style = Input { Value = FuID { "ParticleStyleBlob" }, },
2290 Number = Input { Value = 40, },
2291 Velocity = Input { Value = 0.4, },
2292 AngleVariance = Input { Value = 180, },
2293 ["ParticleStyle.Size"] = Input { Value = 0.6, },
2294 ["ParticleStyle.RedHigh"] = Input { Value = -0.5, },
2295 },
2296 },
2297 E_ngon = pEmitter {
2298 Inputs = {
2299 RandomSeed = Input { Value = 22, },
2300 Style = Input { Value = FuID { "ParticleStyleNGon" }, },
2301 Number = Input { Value = 25, },
2302 Velocity = Input { Value = 0.3, },
2303 AngleVariance = Input { Value = 180, },
2304 RotationZVariance = Input { Value = 180, },
2305 ["ParticleStyle.Size"] = Input { Value = 0.5, },
2306 },
2307 },
2308 E_bmp = pEmitter {
2309 Inputs = {
2310 RandomSeed = Input { Value = 33, },
2311 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
2312 Number = Input { Value = 25, },
2313 Velocity = Input { Value = 0.35, },
2314 AngleVariance = Input { Value = 180, },
2315 RotationZVariance = Input { Value = 45, },
2316 ["ParticleStyle.Size"] = Input { Value = 1.2, },
2317 },
2318 },
2319 M1 = pMerge {
2320 Inputs = {
2321 Input1 = Input { SourceOp = "E_blob", Source = "Output", },
2322 Input2 = Input { SourceOp = "E_ngon", Source = "Output", },
2323 },
2324 },
2325 M2 = pMerge {
2326 Inputs = {
2327 Input1 = Input { SourceOp = "M1", Source = "Output", },
2328 Input2 = Input { SourceOp = "E_bmp", Source = "Output", },
2329 },
2330 },
2331 R = pRender {
2332 Inputs = {
2333 Width = Input { Value = 640, },
2334 Height = Input { Value = 360, },
2335 Input = Input { SourceOp = "M2", Source = "Output", },
2336 },
2337 },
2338 },
2339}
2340"#;
2341 let comp = Comp::from_fusion_str(comp_src).expect("parse multi-style comp");
2342 let render_id = comp.node_by_name["R"];
2343 let bmp_id = comp.node_by_name["E_bmp"];
2344 let expr = ExprEngine::new();
2345 let mut sprites = HashMap::new();
2346 let mut sprite_rgba = vec![0u8; 8 * 8 * 4];
2347 for (i, px) in sprite_rgba.chunks_exact_mut(4).enumerate() {
2348 px[0] = ((i * 37) % 256) as u8;
2349 px[1] = 200;
2350 px[2] = 120;
2351 px[3] = 220;
2352 }
2353 sprites.insert(bmp_id, SpriteImage { size: [8, 8], rgba: sprite_rgba });
2354
2355 // Render at 640x360 (triggers parallel band rasterizer) twice with separate caches: must be bit-identical.
2356 let mut cache_a = ParticleCache::default();
2357 let mut cache_b = ParticleCache::default();
2358 let buf_a = render_particles_2d(&mut cache_a, &comp, render_id, 15.0, [640, 360], &expr, &sprites);
2359 let buf_b = render_particles_2d(&mut cache_b, &comp, render_id, 15.0, [640, 360], &expr, &sprites);
2360 assert_eq!(buf_a, buf_b, "multi-style 640x360 render must be bit-for-bit deterministic");
2361 assert!(buf_a.chunks_exact(4).any(|px| px[3] > 0));
2362 assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0));
2363
2364 // Reusing the same cache at smaller and larger resolutions must not leak stale scratch pixels.
2365 let small = render_particles_2d(&mut cache_a, &comp, render_id, 16.0, [120, 80], &expr, &sprites);
2366 let mut fresh_small = ParticleCache::default();
2367 let small_ref = render_particles_2d(&mut fresh_small, &comp, render_id, 16.0, [120, 80], &expr, &sprites);
2368 assert_eq!(small, small_ref);
2369
2370 let large = render_particles_2d(&mut cache_a, &comp, render_id, 17.0, [720, 405], &expr, &sprites);
2371 let mut fresh_large = ParticleCache::default();
2372 let large_ref = render_particles_2d(&mut fresh_large, &comp, render_id, 17.0, [720, 405], &expr, &sprites);
2373 assert_eq!(large, large_ref);
2374 assert!(cache_a.scratch_accum.iter().all(|&x| x == 0.0));
2375 }
2376
2377 #[test]
2378 fn fast_path_unrotated_and_1x1_bitmap_match_bounds_and_clipping() {
2379 let comp_src = r#"
2380Composition {
2381 GlobalRange = { 0, 10 },
2382 RenderRange = { 0, 10 },
2383 Tools = {
2384 EN = BezierSpline {
2385 KeyFrames = {
2386 [0] = { 1, Flags = { Linear = true } },
2387 [1] = { 0, Flags = { Linear = true } }
2388 }
2389 },
2390 BG1x1 = Background {
2391 Inputs = {
2392 Width = Input { Value = 4, },
2393 Height = Input { Value = 4, },
2394 TopLeftRed = Input { Value = 0.5, },
2395 TopLeftGreen = Input { Value = 0.25, },
2396 TopLeftBlue = Input { Value = 1.0, },
2397 TopLeftAlpha = Input { Value = 0.8, },
2398 },
2399 },
2400 E = pEmitter {
2401 Inputs = {
2402 Number = Input { SourceOp = "EN", Source = "Value", },
2403 Lifespan = Input { Value = 10, },
2404 ["SphereRgn.Size"] = Input { Value = 0, },
2405 ["SphereRgn.Translate.X"] = Input { Value = -0.49, },
2406 Style = Input { Value = FuID { "ParticleStyleBitmap" }, },
2407 ["ParticleStyleBitmap.DropToolsHere"] = Input { SourceOp = "BG1x1", Source = "Output", },
2408 ["ParticleStyle.Size"] = Input { Value = 2, },
2409 },
2410 },
2411 R = pRender {
2412 Inputs = {
2413 Width = Input { Value = 100, },
2414 Height = Input { Value = 100, },
2415 Input = Input { SourceOp = "E", Source = "Output", },
2416 },
2417 },
2418 },
2419}
2420"#;
2421 let comp = Comp::from_fusion_str(comp_src).expect("parse 1x1 bitmap comp");
2422 let mut cache = ParticleCache::default();
2423 let img = render_particles_2d(
2424 &mut cache,
2425 &comp,
2426 comp.node_by_name["R"],
2427 0.0,
2428 [100, 100],
2429 &ExprEngine::new(),
2430 &HashMap::new(),
2431 );
2432 // Particle centered at x = 1 px with 8 px width must clip cleanly at left edge (x=0) without wrapping.
2433 let lit_cols: Vec<usize> = (0..100)
2434 .filter(|&x| img[(50 * 100 + x) * 4 + 3] > 0)
2435 .collect();
2436 assert_eq!(lit_cols, vec![0, 1, 2, 3, 4]);
2437 assert_eq!(img[(50 * 100 + 99) * 4 + 3], 0, "must not wrap to right edge");
2438 }
2439}