1//! Extended 2D particle modifiers & forces:
2//! - `pVortex`: tangential swirl + radial inward/outward vortex force
3//! - `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering
4//! - `pSpawn`: child particle spawning from living parents (capped at `MAX_PARTICLES`)
5//! - `pChangeStyle`: color/size/alpha/style modification over life or within a region
6//! - `pGradientForce`: spatial luminance-gradient force from a pre-sampled 64x64 image grid
7
8use std::collections::hash_map::DefaultHasher;
9use std::collections::{HashMap, HashSet};
10use std::hash::{Hash, Hasher};
11
12use model::{Comp, ExprEngine, Node, NodeId};
13
14use super::sim::RegionSpec;
15use super::{
16 MAX_PARTICLES, Particle, ParticleStyleKind, SplitMix64, SpriteImage, VELOCITY_SCALE,
17 stable_name_hash,
18};
19
20/// Resolution of the pre-sampled luminance gradient grid for `pGradientForce`.
21const GRAD_GRID_DIM: usize = 64;
22
23/// Maximum neighbors examined per particle in `pFlock` to guarantee O(N) worst-case runtime
24/// even when all particles coincide at a single point.
25const FLOCK_MAX_NEIGHBORS: usize = 32;
26
27/// Force scale constant for `pVortex` (render widths per frame^2 at unit strength and distance).
28const VORTEX_FORCE_SCALE: f64 = 1.0e-3;
29
30/// Pre-sampled 2D spatial luminance gradient field `[dL/du, dL/dv]` in Y-up particle coordinates.
31#[derive(Clone, Debug)]
32pub(super) struct GradientField {
33 w: usize,
34 h: usize,
35 aspect: f64,
36 /// Interleaved `[gx, gy]` per grid cell (row 0 = top of image, row `h-1` = bottom).
37 grads: Vec<[f32; 2]>,
38 pub(super) content_hash: u64,
39}
40
41impl GradientField {
42 pub(super) fn from_sprite(sprite: &SpriteImage, channel: &str) -> Option<Self> {
43 let sw = sprite.size[0] as usize;
44 let sh = sprite.size[1] as usize;
45 if sw == 0 || sh == 0 || sprite.rgba.len() < sw.saturating_mul(sh).saturating_mul(4) {
46 return None;
47 }
48 let gw = sw.min(GRAD_GRID_DIM).max(2);
49 let gh = sh.min(GRAD_GRID_DIM).max(2);
50
51 let sample_scalar = |px: &[u8]| -> f32 {
52 let r = px[0] as f32 / 255.0;
53 let g = px[1] as f32 / 255.0;
54 let b = px[2] as f32 / 255.0;
55 let a = px[3] as f32 / 255.0;
56 match channel {
57 "Red" | "R" => r,
58 "Green" | "G" => g,
59 "Blue" | "B" => b,
60 "Alpha" | "A" => a,
61 _ => 0.2126 * r + 0.7152 * g + 0.0722 * b,
62 }
63 };
64
65 // Downsample source image into `gw x gh` scalar luminance grid via box averaging.
66 let mut luma = vec![0.0_f32; gw * gh];
67 for gy in 0..gh {
68 let y0 = gy * sh / gh;
69 let y1 = ((gy + 1) * sh / gh).max(y0 + 1).min(sh);
70 for gx in 0..gw {
71 let x0 = gx * sw / gw;
72 let x1 = ((gx + 1) * sw / gw).max(x0 + 1).min(sw);
73 let mut sum = 0.0_f32;
74 let mut cnt = 0u32;
75 // Sample up to a 4x4 stride inside each bin so huge 4K inputs stay instant.
76 let step_y = ((y1 - y0) / 4).max(1);
77 let step_x = ((x1 - x0) / 4).max(1);
78 let mut sy = y0;
79 while sy < y1 {
80 let row = sy * sw;
81 let mut sx = x0;
82 while sx < x1 {
83 let off = (row + sx) * 4;
84 sum += sample_scalar(&sprite.rgba[off..off + 4]);
85 cnt += 1;
86 sx += step_x;
87 }
88 sy += step_y;
89 }
90 luma[gy * gw + gx] = if cnt > 0 { sum / cnt as f32 } else { 0.0 };
91 }
92 }
93
94 // Compute resolution-independent central differences: dL/du (+X right) and dL/dv (+Y up).
95 let mut grads = vec![[0.0_f32; 2]; gw * gh];
96 let mut hasher = DefaultHasher::new();
97 gw.hash(&mut hasher);
98 gh.hash(&mut hasher);
99 sw.hash(&mut hasher);
100 sh.hash(&mut hasher);
101 channel.hash(&mut hasher);
102
103 let scale_x = (gw.saturating_sub(1)) as f32;
104 let scale_y = (gh.saturating_sub(1)) as f32;
105 for gy in 0..gh {
106 let ym = gy.saturating_sub(1);
107 let yp = (gy + 1).min(gh - 1);
108 let dy_span = (yp - ym).max(1) as f32;
109 for gx in 0..gw {
110 let xm = gx.saturating_sub(1);
111 let xp = (gx + 1).min(gw - 1);
112 let dx_span = (xp - xm).max(1) as f32;
113
114 let dl_dx = (luma[gy * gw + xp] - luma[gy * gw + xm]) / dx_span * scale_x;
115 // Image row 0 is top (+Y in particle space), row gh-1 is bottom (-Y).
116 let dl_dy = (luma[ym * gw + gx] - luma[yp * gw + gx]) / dy_span * scale_y;
117 let g = [dl_dx, dl_dy];
118 grads[gy * gw + gx] = g;
119 g[0].to_bits().hash(&mut hasher);
120 g[1].to_bits().hash(&mut hasher);
121 }
122 }
123
124 Some(Self {
125 w: gw,
126 h: gh,
127 aspect: sw as f64 / sh as f64,
128 grads,
129 content_hash: hasher.finish(),
130 })
131 }
132
133 /// Bilinearly samples `[dL/du, dL/dv]` at particle world position `(px, py)`.
134 #[inline]
135 fn sample(&self, px: f64, py: f64) -> [f64; 2] {
136 let u = px + 0.5;
137 let v = 0.5 - py * self.aspect;
138 if !(-0.05..=1.05).contains(&u) || !(-0.05..=1.05).contains(&v) {
139 return [0.0, 0.0];
140 }
141 let fx = u.clamp(0.0, 1.0) * (self.w - 1) as f64;
142 let fy = v.clamp(0.0, 1.0) * (self.h - 1) as f64;
143 let x0 = (fx.floor() as usize).min(self.w - 1);
144 let y0 = (fy.floor() as usize).min(self.h - 1);
145 let x1 = (x0 + 1).min(self.w - 1);
146 let y1 = (y0 + 1).min(self.h - 1);
147 let tx = fx - x0 as f64;
148 let ty = fy - y0 as f64;
149
150 let g00 = self.grads[y0 * self.w + x0];
151 let g10 = self.grads[y0 * self.w + x1];
152 let g01 = self.grads[y1 * self.w + x0];
153 let g11 = self.grads[y1 * self.w + x1];
154
155 let gx0 = g00[0] as f64 + (g10[0] as f64 - g00[0] as f64) * tx;
156 let gx1 = g01[0] as f64 + (g11[0] as f64 - g01[0] as f64) * tx;
157 let gy0 = g00[1] as f64 + (g10[1] as f64 - g00[1] as f64) * tx;
158 let gy1 = g01[1] as f64 + (g11[1] as f64 - g01[1] as f64) * tx;
159 [gx0 + (gx1 - gx0) * ty, gy0 + (gy1 - gy0) * ty]
160 }
161}
162
163pub(super) fn build_gradient_fields(
164 comp: &Comp,
165 modifiers: &[(NodeId, HashSet<u64>)],
166 sprites: &HashMap<NodeId, SpriteImage>,
167) -> HashMap<NodeId, GradientField> {
168 let mut fields = HashMap::new();
169 for &(mod_id, _) in modifiers {
170 let Some(node) = comp.nodes.get(mod_id.0) else {
171 continue;
172 };
173 if node.kind != "pGradientForce" {
174 continue;
175 }
176 let Some(sprite) = sprites.get(&mod_id) else {
177 continue;
178 };
179 let channel = node.static_str("Channel").unwrap_or("Luma");
180 if let Some(field) = GradientField::from_sprite(sprite, channel) {
181 fields.insert(mod_id, field);
182 }
183 }
184 fields
185}
186
187pub(super) fn parse_particle_style(s: &str) -> Option<ParticleStyleKind> {
188 match s {
189 "ParticleStylePoint" | "Point" => Some(ParticleStyleKind::Point),
190 "ParticleStyleBlob" | "Blob" => Some(ParticleStyleKind::Blob),
191 "ParticleStyleNGon" | "NGon" => Some(ParticleStyleKind::NGon),
192 "ParticleStyleBitmap" | "Bitmap" => Some(ParticleStyleKind::Bitmap),
193 "ParticleStyleBrush" | "Brush" => Some(ParticleStyleKind::Brush),
194 _ => None,
195 }
196}
197
198pub(super) fn eval_first_num(
199 comp: &Comp,
200 node: &Node,
201 keys: &[&str],
202 t: f64,
203 default: f64,
204 expr: &ExprEngine,
205) -> f64 {
206 for &k in keys {
207 if node.inputs.contains_key(k) {
208 return comp.eval_number(node, k, t, default, expr);
209 }
210 }
211 default
212}
213
214/// Reads particle set bitmask from `Set1..=Set32` or integer `Set` (1..=32).
215pub(super) fn read_sets_mask(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Option<u32> {
216 let mut mask = 0u32;
217 let mut any_key = false;
218 if node.inputs.contains_key("Set") {
219 any_key = true;
220 let idx = comp.eval_number(node, "Set", t, 1.0, expr).round() as i32;
221 if (1..=32).contains(&idx) {
222 mask |= 1u32 << (idx - 1);
223 }
224 }
225 for key in node.inputs.keys() {
226 if let Some(rest) = key.strip_prefix("Set") {
227 if let Ok(idx) = rest.parse::<u32>() {
228 if (1..=32).contains(&idx) {
229 any_key = true;
230 if comp.eval_number(node, key, t, 0.0, expr) > 0.5 {
231 mask |= 1u32 << (idx - 1);
232 }
233 }
234 }
235 }
236 }
237 any_key.then_some(mask)
238}
239
240pub(super) struct ModifierFilter {
241 region: RegionSpec,
242 invert_region: bool,
243 probability: f64,
244 start_age: f64,
245 end_age: f64,
246 set_mask: Option<u32>,
247 dont_affect_sets: bool,
248}
249
250impl ModifierFilter {
251 pub(super) fn from_node(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine) -> Self {
252 Self::build(comp, node, t, expr, false)
253 }
254
255 pub(super) fn from_node_ignore_region(
256 comp: &Comp,
257 node: &Node,
258 t: f64,
259 expr: &ExprEngine,
260 ) -> Self {
261 Self::build(comp, node, t, expr, true)
262 }
263
264 fn build(comp: &Comp, node: &Node, t: f64, expr: &ExprEngine, ignore_region: bool) -> Self {
265 let region = if !ignore_region && node.static_str("Region").is_some() {
266 RegionSpec::from_node(comp, node, t, expr)
267 } else {
268 RegionSpec::All
269 };
270 let invert_region = matches!(node.static_str("RegionMode"), Some("Outside" | "Leaving"));
271 let probability = comp.eval_number(node, "Probability", t, 1.0, expr).clamp(0.0, 1.0);
272 let start_age = comp.eval_number(node, "StartAge", t, 0.0, expr).clamp(0.0, 1.0);
273 let end_age = comp.eval_number(node, "EndAge", t, 1.0, expr).clamp(0.0, 1.0);
274 let set_mask = if node.kind == "pSpawn" && !node.inputs.contains_key("SetMode") {
275 None
276 } else {
277 read_sets_mask(comp, node, t, expr)
278 };
279 let dont_affect_sets = matches!(node.static_str("SetMode"), Some("DontAffect" | "Don't Affect"));
280 Self {
281 region,
282 invert_region,
283 probability,
284 start_age,
285 end_age,
286 set_mask,
287 dont_affect_sets,
288 }
289 }
290
291 #[inline]
292 pub(super) fn matches(&self, p: &Particle, scope: &HashSet<u64>, rng: &mut SplitMix64) -> bool {
293 if !p.alive || !scope.contains(&p.emitter_hash) {
294 return false;
295 }
296 let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0);
297 if life_frac < self.start_age - 1e-9 || life_frac > self.end_age + 1e-9 {
298 return false;
299 }
300 if let Some(mask) = self.set_mask {
301 let hit = (p.sets & mask) != 0;
302 if (!self.dont_affect_sets && !hit) || (self.dont_affect_sets && hit) {
303 return false;
304 }
305 }
306 let inside = self.region.contains(p.pos);
307 if (!self.invert_region && !inside) || (self.invert_region && inside) {
308 return false;
309 }
310 if self.probability < 1.0 - 1e-9 && rng.next_f64() > self.probability {
311 return false;
312 }
313 true
314 }
315}
316
317/// Dispatches `pVortex`, `pFlock`, `pSpawn`, `pChangeStyle`, and `pGradientForce`.
318#[allow(clippy::too_many_arguments)]
319pub(super) fn apply_extended_modifier(
320 particles: &mut Vec<Particle>,
321 next_id: &mut u32,
322 comp: &Comp,
323 node: &Node,
324 mod_id: NodeId,
325 scope: &HashSet<u64>,
326 emitter_nodes: &HashMap<u64, NodeId>,
327 gradient_fields: &HashMap<NodeId, GradientField>,
328 sprites: &HashMap<NodeId, SpriteImage>,
329 t: f64,
330 expr: &ExprEngine,
331) {
332 match node.kind.as_str() {
333 "pVortex" => apply_vortex(particles, comp, node, scope, t, expr),
334 "pFlock" => apply_flock(particles, comp, node, scope, t, expr),
335 "pAvoid" => super::extra_forces::apply_avoid(particles, comp, node, scope, t, expr),
336 "pFollow" => super::extra_forces::apply_follow(particles, comp, node, scope, t, expr),
337 "pTangentForce" => {
338 super::extra_forces::apply_tangent_force(particles, comp, node, scope, t, expr)
339 }
340 "pCustom" => {
341 super::custom::apply_custom(particles, comp, node, scope, sprites.get(&mod_id), t, expr)
342 }
343 "pCustomForce" => super::custom::apply_custom_force(
344 particles,
345 comp,
346 node,
347 scope,
348 sprites.get(&mod_id),
349 t,
350 expr,
351 ),
352 "pSpawn" => apply_spawn(particles, next_id, comp, node, scope, emitter_nodes, t, expr),
353 "pChangeStyle" => apply_change_style(particles, comp, node, scope, t, expr),
354 "pGradientForce" => {
355 if let Some(field) = gradient_fields.get(&mod_id) {
356 apply_gradient_force(particles, comp, node, scope, field, t, expr);
357 }
358 }
359 _ => {}
360 }
361}
362
363/// `pVortex`: tangential swirl + radial spiral force around `Center` / `Translate`.
364fn apply_vortex(
365 particles: &mut [Particle],
366 comp: &Comp,
367 node: &Node,
368 scope: &HashSet<u64>,
369 t: f64,
370 expr: &ExprEngine,
371) {
372 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
373 if strength.abs() < 1e-12 {
374 return;
375 }
376 let power = comp.eval_number(node, "Power", t, 2.0, expr);
377 let angle = comp.eval_number(node, "Angle", t, 0.0, expr).to_radians();
378 let (sin_a, cos_a) = angle.sin_cos();
379
380 let center_pt = if node.inputs.contains_key("Center") {
381 comp.eval_point(node, "Center", t, [0.0, 0.0], expr)
382 } else {
383 [0.0, 0.0]
384 };
385 let cx = eval_first_num(comp, node, &["Translate.X", "Center.X"], t, center_pt[0], expr);
386 let cy = eval_first_num(comp, node, &["Translate.Y", "Center.Y"], t, center_pt[1], expr);
387
388 let filter = ModifierFilter::from_node(comp, node, t, expr);
389 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
390 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
391
392 for p in particles.iter_mut() {
393 if !filter.matches(p, scope, &mut rng) {
394 continue;
395 }
396 let rx = p.pos[0] - cx;
397 let ry = p.pos[1] - cy;
398 let dist = (rx * rx + ry * ry).sqrt();
399 if dist < 1e-7 {
400 continue;
401 }
402 let inv_d = 1.0 / dist;
403 let r_hat_x = rx * inv_d;
404 let r_hat_y = ry * inv_d;
405 // CCW tangential unit vector around center.
406 let t_hat_x = -r_hat_y;
407 let t_hat_y = r_hat_x;
408
409 // Angle = 0 => pure tangential swirl; positive Angle spirals inward; negative spirals outward.
410 let fx = t_hat_x * cos_a - r_hat_x * sin_a;
411 let fy = t_hat_y * cos_a - r_hat_y * sin_a;
412
413 let falloff = dist.max(0.02).powf(power);
414 let mag = (strength * VORTEX_FORCE_SCALE / falloff).clamp(-0.2, 0.2);
415 p.vel[0] += fx * mag;
416 p.vel[1] += fy * mag;
417 }
418}
419
420/// `pFlock`: O(N) spatial-hashed Boids cohesion, separation, and alignment steering.
421fn apply_flock(
422 particles: &mut [Particle],
423 comp: &Comp,
424 node: &Node,
425 scope: &HashSet<u64>,
426 t: f64,
427 expr: &ExprEngine,
428) {
429 let strength = comp.eval_number(node, "Strength", t, 1.0, expr);
430 if strength.abs() < 1e-12 {
431 return;
432 }
433 let cohesion = eval_first_num(comp, node, &["Cohesion", "AttractStrength", "CohesionStrength"], t, 0.1, expr);
434 let separation = eval_first_num(comp, node, &["Separation", "RepelStrength", "SeparationStrength"], t, 0.1, expr);
435 let alignment = eval_first_num(comp, node, &["Alignment", "AlignStrength", "AlignmentStrength"], t, 0.1, expr);
436 if cohesion.abs() < 1e-12 && separation.abs() < 1e-12 && alignment.abs() < 1e-12 {
437 return;
438 }
439
440 let radius = eval_first_num(comp, node, &["Radius", "InfluenceRadius", "Distance", "AttractDistance"], t, 0.15, expr)
441 .max(1e-4);
442 let sep_radius = eval_first_num(comp, node, &["RepelDistance", "SeparationRadius"], t, radius * 0.5, expr)
443 .clamp(1e-5, radius);
444 let radius_sq = radius * radius;
445 let inv_cell = 1.0 / radius.max(0.01);
446
447 let filter = ModifierFilter::from_node(comp, node, t, expr);
448 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
449 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
450
451 let mut active: Vec<usize> = Vec::new();
452 let mut grid: HashMap<(i32, i32), Vec<usize>> = HashMap::new();
453
454 for (idx, p) in particles.iter().enumerate() {
455 if !filter.matches(p, scope, &mut rng) {
456 continue;
457 }
458 active.push(idx);
459 let cx = (p.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32;
460 let cy = (p.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32;
461 grid.entry((cx, cy)).or_default().push(idx);
462 }
463
464 if active.len() < 2 {
465 return;
466 }
467
468 let mut deltas = vec![[0.0_f64; 3]; active.len()];
469 for (slot, &i) in active.iter().enumerate() {
470 let pi = &particles[i];
471 let cx = (pi.pos[0] * inv_cell).floor().clamp(-1e6, 1e6) as i32;
472 let cy = (pi.pos[1] * inv_cell).floor().clamp(-1e6, 1e6) as i32;
473
474 let mut sum_pos = [0.0_f64; 3];
475 let mut sum_vel = [0.0_f64; 3];
476 let mut sep_vec = [0.0_f64; 3];
477 let mut n_count = 0usize;
478 let mut sep_count = 0usize;
479 let mut inspected = 0usize;
480
481 'cells: for dy in -1..=1 {
482 for dx in -1..=1 {
483 let Some(bucket) = grid.get(&(cx + dx, cy + dy)) else {
484 continue;
485 };
486 for &j in bucket {
487 if j == i {
488 continue;
489 }
490 inspected += 1;
491 if inspected > FLOCK_MAX_NEIGHBORS {
492 break 'cells;
493 }
494 let pj = &particles[j];
495 let rx = pj.pos[0] - pi.pos[0];
496 let ry = pj.pos[1] - pi.pos[1];
497 let rz = pj.pos[2] - pi.pos[2];
498 let d2 = rx * rx + ry * ry + rz * rz;
499 if d2 >= radius_sq || d2 <= 1e-12 {
500 continue;
501 }
502 n_count += 1;
503 sum_pos[0] += pj.pos[0];
504 sum_pos[1] += pj.pos[1];
505 sum_pos[2] += pj.pos[2];
506 sum_vel[0] += pj.vel[0];
507 sum_vel[1] += pj.vel[1];
508 sum_vel[2] += pj.vel[2];
509
510 let d = d2.sqrt();
511 if d < sep_radius {
512 let weight = (1.0 - d / sep_radius) / d;
513 sep_vec[0] -= rx * weight;
514 sep_vec[1] -= ry * weight;
515 sep_vec[2] -= rz * weight;
516 sep_count += 1;
517 }
518 }
519 }
520 }
521
522 if n_count == 0 {
523 continue;
524 }
525 let inv_n = 1.0 / n_count as f64;
526 let mut acc = [0.0_f64; 3];
527 for a in 0..3 {
528 let coh = (sum_pos[a] * inv_n - pi.pos[a]) * cohesion * strength * 0.05;
529 let align = (sum_vel[a] * inv_n - pi.vel[a]) * alignment * strength * 0.2;
530 let sep = if sep_count > 0 {
531 (sep_vec[a] / sep_count as f64) * separation * strength * 0.02
532 } else {
533 0.0
534 };
535 acc[a] = coh + align + sep;
536 }
537 let mag = (acc[0] * acc[0] + acc[1] * acc[1] + acc[2] * acc[2]).sqrt();
538 const MAX_FLOCK_ACCEL: f64 = 0.05;
539 if mag > MAX_FLOCK_ACCEL {
540 let s = MAX_FLOCK_ACCEL / mag;
541 acc[0] *= s;
542 acc[1] *= s;
543 acc[2] *= s;
544 }
545 deltas[slot] = acc;
546 }
547
548 for (&i, acc) in active.iter().zip(deltas.iter()) {
549 particles[i].vel[0] += acc[0];
550 particles[i].vel[1] += acc[1];
551 particles[i].vel[2] += acc[2];
552 }
553}
554
555/// `pSpawn`: spawns child particles from living parent particles, respecting `MAX_PARTICLES`.
556#[allow(clippy::too_many_arguments)]
557fn apply_spawn(
558 particles: &mut Vec<Particle>,
559 next_id: &mut u32,
560 comp: &Comp,
561 node: &Node,
562 scope: &HashSet<u64>,
563 emitter_nodes: &HashMap<u64, NodeId>,
564 t: f64,
565 expr: &ExprEngine,
566) {
567 if particles.len() >= MAX_PARTICLES {
568 return;
569 }
570 let number = comp.eval_number(node, "Number", t, 1.0, expr).max(0.0);
571 let number_var = comp.eval_number(node, "NumberVariance", t, 0.0, expr).max(0.0);
572 if number <= 1e-9 && number_var <= 1e-9 {
573 return;
574 }
575
576 let lifespan_base = comp.eval_number(node, "Lifespan", t, 50.0, expr).max(1.0);
577 let lifespan_var = comp.eval_number(node, "LifespanVariance", t, 0.0, expr).max(0.0);
578 let vel_transfer = eval_first_num(comp, node, &["VelocityTransfer", "InheritVelocity"], t, 1.0, expr);
579 let vel_base = comp.eval_number(node, "Velocity", t, 0.0, expr);
580 let vel_var = comp.eval_number(node, "VelocityVariance", t, 0.0, expr).max(0.0);
581 let angle_base = comp.eval_number(node, "Angle", t, 0.0, expr);
582 let angle_var = comp.eval_number(node, "AngleVariance", t, 0.0, expr).max(0.0);
583 let angle_z_base = comp.eval_number(node, "AngleZ", t, 0.0, expr);
584 let angle_z_var = comp.eval_number(node, "AngleZVariance", t, 0.0, expr).max(0.0);
585 let pos_var = comp.eval_number(node, "PositionVariance", t, 0.0, expr).max(0.0);
586 let rot_z_base = comp.eval_number(node, "RotationZ", t, 0.0, expr);
587 let rot_z_var = comp.eval_number(node, "RotationZVariance", t, 0.0, expr).max(0.0);
588 let spin_z_base = comp.eval_number(node, "SpinZ", t, 0.0, expr);
589 let spin_z_var = comp.eval_number(node, "SpinZVariance", t, 0.0, expr).max(0.0);
590
591 let has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size");
592 let size_base = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0);
593 let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0);
594
595 let has_r = node.inputs.contains_key("ParticleStyle.Red") || node.inputs.contains_key("Red");
596 let has_g = node.inputs.contains_key("ParticleStyle.Green") || node.inputs.contains_key("Green");
597 let has_b = node.inputs.contains_key("ParticleStyle.Blue") || node.inputs.contains_key("Blue");
598 let has_a = node.inputs.contains_key("ParticleStyle.Alpha") || node.inputs.contains_key("Alpha");
599 let col_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
600 let col_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
601 let col_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
602 let col_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
603
604 let explicit_style = node.static_str("Style").and_then(parse_particle_style);
605 let ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") {
606 comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr)
607 .round()
608 .clamp(3.0, 64.0) as u8
609 } else {
610 0
611 };
612 let child_sets = read_sets_mask(comp, node, t, expr);
613 let spawn_hash = stable_name_hash(&node.name);
614 let has_spawn_bitmap = node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some();
615
616 let filter = ModifierFilter::from_node(comp, node, t, expr);
617 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
618 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
619
620 let remaining_cap = MAX_PARTICLES.saturating_sub(particles.len());
621 let mut spawned: Vec<Particle> = Vec::new();
622 let parent_count = particles.len();
623
624 for idx in 0..parent_count {
625 if spawned.len() >= remaining_cap {
626 break;
627 }
628 let parent = particles[idx];
629 if !filter.matches(&parent, scope, &mut rng) {
630 continue;
631 }
632
633 let rate = (number + rng.signed() * number_var).max(0.0);
634 let whole = rate.floor() as usize;
635 let frac = rate - whole as f64;
636 let count = whole + usize::from(frac > 1e-9 && rng.next_f64() < frac);
637 if count == 0 {
638 continue;
639 }
640
641 // Inherit parent's visual style when `pSpawn` does not explicitly specify `Style`.
642 let child_style = explicit_style.or(parent.style_override).or_else(|| {
643 emitter_nodes
644 .get(&parent.emitter_hash)
645 .and_then(|id| comp.nodes.get(id.0))
646 .and_then(|en| en.static_str("Style"))
647 .and_then(parse_particle_style)
648 });
649 let child_bitmap_owner = if has_spawn_bitmap {
650 spawn_hash
651 } else if explicit_style.is_none() {
652 if parent.bitmap_owner_hash != 0 {
653 parent.bitmap_owner_hash
654 } else {
655 parent.emitter_hash
656 }
657 } else {
658 0
659 };
660
661 for _ in 0..count {
662 if spawned.len() >= remaining_cap {
663 break;
664 }
665 let mut pos = parent.pos;
666 if pos_var > 0.0 {
667 pos[0] += rng.signed() * pos_var;
668 pos[1] += rng.signed() * pos_var;
669 pos[2] += rng.signed() * pos_var;
670 }
671 let speed = (vel_base + rng.signed() * vel_var) * VELOCITY_SCALE;
672 let ang = (angle_base + rng.signed() * angle_var).to_radians();
673 let ang_z = (angle_z_base + rng.signed() * angle_z_var).to_radians();
674 let cos_z = ang_z.cos();
675 let vel = [
676 parent.vel[0] * vel_transfer + speed * ang.cos() * cos_z,
677 parent.vel[1] * vel_transfer + speed * ang.sin() * cos_z,
678 parent.vel[2] * vel_transfer + speed * ang_z.sin(),
679 ];
680 let lifespan = (lifespan_base + rng.signed() * lifespan_var).max(1.0);
681 let size = if has_size {
682 (size_base + rng.signed() * size_var).max(0.0)
683 } else {
684 parent.size
685 };
686 let color = [
687 if has_r { col_r } else { parent.color[0] },
688 if has_g { col_g } else { parent.color[1] },
689 if has_b { col_b } else { parent.color[2] },
690 if has_a { col_a } else { parent.color[3] },
691 ];
692 let pid = *next_id;
693 *next_id = (*next_id).wrapping_add(1).max(1);
694 spawned.push(Particle {
695 emitter_hash: spawn_hash,
696 id: pid,
697 sets: child_sets.unwrap_or(parent.sets),
698 style_override: child_style,
699 ngon_sides_override: if ngon_sides >= 3 {
700 ngon_sides
701 } else {
702 parent.ngon_sides_override
703 },
704 bitmap_owner_hash: child_bitmap_owner,
705 pos,
706 vel,
707 rot_xy: [0.0, 0.0],
708 rot_z: rot_z_base + rng.signed() * rot_z_var,
709 spin_xy: [0.0, 0.0],
710 spin_z: spin_z_base + rng.signed() * spin_z_var,
711 age: 0.0,
712 lifespan,
713 size,
714 mass: parent.mass,
715 user: parent.user,
716 color,
717 alive: true,
718 });
719 }
720 }
721
722 particles.extend(spawned);
723}
724
725/// `pChangeStyle`: modifies particle color, alpha, size, and style over life or inside a region.
726fn apply_change_style(
727 particles: &mut [Particle],
728 comp: &Comp,
729 node: &Node,
730 scope: &HashSet<u64>,
731 t: f64,
732 expr: &ExprEngine,
733) {
734 let filter = ModifierFilter::from_node(comp, node, t, expr);
735 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
736 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
737
738 let has_r = node.inputs.contains_key("ParticleStyle.Red")
739 || node.inputs.contains_key("Red")
740 || node.inputs.contains_key("Color.R");
741 let has_g = node.inputs.contains_key("ParticleStyle.Green")
742 || node.inputs.contains_key("Green")
743 || node.inputs.contains_key("Color.G");
744 let has_b = node.inputs.contains_key("ParticleStyle.Blue")
745 || node.inputs.contains_key("Blue")
746 || node.inputs.contains_key("Color.B");
747 let has_a = node.inputs.contains_key("ParticleStyle.Alpha")
748 || node.inputs.contains_key("Alpha")
749 || node.inputs.contains_key("Color.A");
750
751 let new_r = eval_first_num(comp, node, &["ParticleStyle.Red", "Red", "Color.R"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
752 let new_g = eval_first_num(comp, node, &["ParticleStyle.Green", "Green", "Color.G"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
753 let new_b = eval_first_num(comp, node, &["ParticleStyle.Blue", "Blue", "Color.B"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
754 let new_a = eval_first_num(comp, node, &["ParticleStyle.Alpha", "Alpha", "Color.A"], t, 1.0, expr).clamp(0.0, 1.0) as f32;
755
756 let color_grad = comp
757 .eval_gradient(node, "ParticleStyle.ColorOverLife", t)
758 .or_else(|| comp.eval_gradient(node, "Color", t));
759
760 let has_size = node.inputs.contains_key("ParticleStyle.Size") || node.inputs.contains_key("Size");
761 let new_size = eval_first_num(comp, node, &["ParticleStyle.Size", "Size"], t, 0.1, expr).max(0.0);
762 let size_var = eval_first_num(comp, node, &["ParticleStyle.SizeVariance", "SizeVariance"], t, 0.0, expr).max(0.0);
763 let size_over_life = node
764 .inputs
765 .get("ParticleStyle.SizeOverLife")
766 .and_then(|b| b.source_op.as_deref())
767 .and_then(|src| comp.splines.get(src));
768
769 let new_style = node.static_str("Style").and_then(parse_particle_style);
770 let new_ngon_sides = if node.inputs.contains_key("ParticleStyleNGon.NGonSides") {
771 comp.eval_number(node, "ParticleStyleNGon.NGonSides", t, 5.0, expr)
772 .round()
773 .clamp(3.0, 64.0) as u8
774 } else {
775 0
776 };
777 let bitmap_owner = if node.connected_node("ParticleStyleBitmap.DropToolsHere").is_some() {
778 stable_name_hash(&node.name)
779 } else {
780 0
781 };
782
783 for p in particles.iter_mut() {
784 if !filter.matches(p, scope, &mut rng) {
785 continue;
786 }
787 let life_frac = (p.age / p.lifespan.max(1.0)).clamp(0.0, 1.0);
788 if has_r {
789 p.color[0] = new_r;
790 }
791 if has_g {
792 p.color[1] = new_g;
793 }
794 if has_b {
795 p.color[2] = new_b;
796 }
797 if has_a {
798 p.color[3] = new_a;
799 }
800 if let Some(ref grad) = color_grad {
801 let g = grad.sample(life_frac);
802 p.color[0] = g[0].clamp(0.0, 1.0);
803 p.color[1] = g[1].clamp(0.0, 1.0);
804 p.color[2] = g[2].clamp(0.0, 1.0);
805 p.color[3] = g[3].clamp(0.0, 1.0);
806 }
807 if has_size {
808 let mut s = (new_size + rng.signed() * size_var).max(0.0);
809 if let Some(sp) = size_over_life {
810 s *= (2.0 * sp.eval(life_frac)).max(0.0);
811 }
812 p.size = s;
813 } else if let Some(sp) = size_over_life {
814 p.size = (p.size * (2.0 * sp.eval(life_frac)).max(0.0)).max(0.0);
815 }
816 if let Some(st) = new_style {
817 p.style_override = Some(st);
818 if st == ParticleStyleKind::NGon && new_ngon_sides >= 3 {
819 p.ngon_sides_override = new_ngon_sides;
820 }
821 if st == ParticleStyleKind::Bitmap && bitmap_owner != 0 {
822 p.bitmap_owner_hash = bitmap_owner;
823 }
824 }
825 }
826}
827
828/// `pGradientForce`: accelerates particles along the spatial luminance gradient of its input image.
829fn apply_gradient_force(
830 particles: &mut [Particle],
831 comp: &Comp,
832 node: &Node,
833 scope: &HashSet<u64>,
834 field: &GradientField,
835 t: f64,
836 expr: &ExprEngine,
837) {
838 let strength = comp.eval_number(node, "Strength", t, 0.1, expr);
839 if strength.abs() < 1e-12 {
840 return;
841 }
842 let scale = strength * VELOCITY_SCALE * VELOCITY_SCALE;
843 let filter = ModifierFilter::from_node(comp, node, t, expr);
844 let seed = comp.eval_number(node, "RandomSeed", t, 0.0, expr).round() as i64;
845 let mut rng = SplitMix64::from_parts(seed, t.round() as i64, &node.name);
846
847 for p in particles.iter_mut() {
848 if !filter.matches(p, scope, &mut rng) {
849 continue;
850 }
851 let [gx, gy] = field.sample(p.pos[0], p.pos[1]);
852 p.vel[0] += (gx * scale).clamp(-0.1, 0.1);
853 p.vel[1] += (gy * scale).clamp(-0.1, 0.1);
854 }
855}