Skip to main content

sciart_core/
particles.rs

1//! Particle helpers shared by the particle-system scenes (SPEC-001 CORE-R28..R32,
2//! CORE-R54, CORE-R58).
3//!
4//! Everything here is allocation-free after construction and deterministic given the
5//! caller's RNG, so scenes stay inside the GEN-R8 frame budget and reproducible (GEN-R7).
6
7use std::f64::consts::TAU;
8
9use rand::Rng;
10
11use crate::trig::Trig;
12use crate::{Canvas, Glyph, Ink};
13
14/// A bounded, unordered set of live particles (CORE-R28).
15///
16/// Backed by one `Vec<P>` allocated up front. The logical `capacity` is tracked
17/// separately from the `Vec`'s so that shrinking never reallocates and a later grow
18/// back to the original size reuses the buffer.
19#[derive(Debug, Clone)]
20pub struct ParticlePool<P> {
21    items: Vec<P>,
22    capacity: usize,
23}
24
25/// An empty pool of capacity 0, the placeholder until a scene sizes it with
26/// [`ParticlePool::set_capacity`]; allocates nothing.
27impl<P> Default for ParticlePool<P> {
28    fn default() -> Self {
29        Self::with_capacity(0)
30    }
31}
32
33impl<P> ParticlePool<P> {
34    /// An empty pool that will hold at most `capacity` particles (CORE-R28).
35    pub fn with_capacity(capacity: usize) -> Self {
36        Self {
37            items: Vec::with_capacity(capacity),
38            capacity,
39        }
40    }
41
42    /// Add `p` if there is room; otherwise drop it and return `false` (CORE-R28).
43    ///
44    /// Rejecting instead of evicting keeps spawn cost O(1) and makes the particle
45    /// budget a hard cap that emitters can observe.
46    #[inline]
47    pub fn spawn(&mut self, p: P) -> bool {
48        if self.items.len() < self.capacity {
49            // Never reallocates: the buffer was reserved for `capacity` elements.
50            self.items.push(p);
51            true
52        } else {
53            false
54        }
55    }
56
57    /// Update every particle in place and drop those for which `f` returns `false`
58    /// (CORE-R28). Order is **not** preserved.
59    ///
60    /// Swap-remove compaction: a dead particle is replaced by the last one, which is
61    /// then visited at the same index. That is one pass, no shifting of the tail, and
62    /// no allocation — cheaper than `Vec::retain_mut` when many particles die at once,
63    /// and ordering is meaningless for particles anyway.
64    pub fn retain(&mut self, mut f: impl FnMut(&mut P) -> bool) {
65        let mut i = 0;
66        while i < self.items.len() {
67            if f(&mut self.items[i]) {
68                i += 1;
69            } else {
70                self.items.swap_remove(i);
71            }
72        }
73    }
74
75    #[inline]
76    pub fn len(&self) -> usize {
77        self.items.len()
78    }
79
80    #[inline]
81    pub fn is_empty(&self) -> bool {
82        self.items.is_empty()
83    }
84
85    /// Maximum number of live particles.
86    #[inline]
87    pub fn capacity(&self) -> usize {
88        self.capacity
89    }
90
91    pub fn iter(&self) -> std::slice::Iter<'_, P> {
92        self.items.iter()
93    }
94
95    pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, P> {
96        self.items.iter_mut()
97    }
98
99    /// Remove every particle, keeping the buffer.
100    pub fn clear(&mut self) {
101        self.items.clear();
102    }
103
104    /// Change the particle budget, e.g. on resize (CORE-R28).
105    ///
106    /// Shrinking truncates (which particles survive is unspecified) and keeps the
107    /// buffer; growing reserves exactly the extra room — the only allocating operation.
108    pub fn set_capacity(&mut self, capacity: usize) {
109        self.items.truncate(capacity);
110        // `reserve_exact` is relative to `len`, and is a no-op when the buffer is already big enough.
111        self.items.reserve_exact(capacity - self.items.len());
112        self.capacity = capacity;
113    }
114}
115
116impl<'a, P> IntoIterator for &'a ParticlePool<P> {
117    type Item = &'a P;
118    type IntoIter = std::slice::Iter<'a, P>;
119
120    fn into_iter(self) -> Self::IntoIter {
121        self.iter()
122    }
123}
124
125impl<'a, P> IntoIterator for &'a mut ParticlePool<P> {
126    type Item = &'a mut P;
127    type IntoIter = std::slice::IterMut<'a, P>;
128
129    fn into_iter(self) -> Self::IntoIter {
130        self.iter_mut()
131    }
132}
133
134/// Fixed-length history of the last `n` values, e.g. a comet tail (CORE-R29).
135///
136/// A ring buffer over a `Vec<T>` reserved once: while filling, values are appended;
137/// once full, `head` marks the oldest slot and each push overwrites it. `T: Copy`
138/// keeps overwrites trivially cheap and avoids needing `T: Default` for pre-fill.
139#[derive(Debug, Clone)]
140pub struct Trail<T: Copy> {
141    buf: Vec<T>,
142    head: usize,
143    capacity: usize,
144}
145
146impl<T: Copy> Trail<T> {
147    /// A trail remembering at most `n` values; `n = 0` keeps nothing (CORE-R29).
148    pub fn new(n: usize) -> Self {
149        Self {
150            buf: Vec::with_capacity(n),
151            head: 0,
152            capacity: n,
153        }
154    }
155
156    /// Append `v`, evicting the oldest value when full (CORE-R29).
157    #[inline]
158    pub fn push(&mut self, v: T) {
159        if self.buf.len() < self.capacity {
160            self.buf.push(v);
161        } else if self.capacity > 0 {
162            self.buf[self.head] = v;
163            self.head = (self.head + 1) % self.capacity;
164        }
165    }
166
167    /// Values from oldest to newest (CORE-R29).
168    pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + '_ {
169        let (newer, older) = self.buf.split_at(self.head);
170        older.iter().chain(newer)
171    }
172
173    /// The most recently pushed value, if any.
174    pub fn newest(&self) -> Option<T> {
175        self.iter().next_back().copied()
176    }
177
178    #[inline]
179    pub fn len(&self) -> usize {
180        self.buf.len()
181    }
182
183    #[inline]
184    pub fn is_empty(&self) -> bool {
185        self.buf.is_empty()
186    }
187
188    /// Maximum number of remembered values.
189    #[inline]
190    pub fn capacity(&self) -> usize {
191        self.capacity
192    }
193
194    pub fn clear(&mut self) {
195        self.buf.clear();
196        self.head = 0;
197    }
198}
199
200/// One Box–Muller draw: a pair of independent standard normal variates.
201///
202/// `1 - u` maps rand's `[0, 1)` onto `(0, 1]`, so `ln` never sees 0 and the radius is
203/// finite (at most `√(-2 ln 2⁻⁵³) ≈ 8.6`).
204#[inline]
205fn box_muller(rng: &mut impl Rng) -> (f64, f64) {
206    let u1 = 1.0 - rng.random::<f64>();
207    let u2 = rng.random::<f64>();
208    let r = (-2.0 * u1.ln()).sqrt();
209    let (s, c) = (TAU * u2).sin_cos_det();
210    (r * c, r * s)
211}
212
213/// Clean a standard deviation: non-finite ⇒ 0, negative ⇒ its magnitude.
214#[inline]
215fn clean_sd(sd: f64) -> f64 {
216    if sd.is_finite() { sd.abs() } else { 0.0 }
217}
218
219/// Map a non-finite result back to `fallback`, upholding the "always finite" contract.
220#[inline]
221fn finite_or(v: f64, fallback: f64) -> f64 {
222    if v.is_finite() { v } else { fallback }
223}
224
225/// A normal variate `N(mean, sd²)` (CORE-R30).
226///
227/// Always finite: non-finite `mean` is treated as 0, non-finite `sd` as 0, negative `sd`
228/// as `|sd|`, and overflow falls back to `mean`. `sd == 0` returns exactly `mean`.
229/// The RNG is advanced identically regardless of the parameters, so changing `sd` never
230/// shifts the rest of a scene's random stream.
231pub fn gaussian(rng: &mut impl Rng, mean: f64, sd: f64) -> f64 {
232    let (z, _) = box_muller(rng);
233    let mean = finite_or(mean, 0.0);
234    let sd = clean_sd(sd);
235    if sd == 0.0 {
236        return mean;
237    }
238    finite_or(mean + sd * z, mean)
239}
240
241/// An isotropic 2-D normal pair `(x, y)`, each `N(0, sd²)` (CORE-R30).
242///
243/// Uses both Box–Muller outputs, so it costs the same as one [`gaussian`] call.
244/// Same sanitising rules as [`gaussian`]; overflow collapses to `(0, 0)`.
245pub fn gaussian2(rng: &mut impl Rng, sd: f64) -> (f64, f64) {
246    let (zx, zy) = box_muller(rng);
247    let sd = clean_sd(sd);
248    if sd == 0.0 {
249        return (0.0, 0.0);
250    }
251    let (x, y) = (sd * zx, sd * zy);
252    if x.is_finite() && y.is_finite() {
253        (x, y)
254    } else {
255        (0.0, 0.0)
256    }
257}
258
259/// Valid Kepler inputs: finite `gm ≥ 0` and finite `r > 0`.
260#[inline]
261fn kepler_ok(gm: f64, r: f64) -> bool {
262    gm.is_finite() && gm >= 0.0 && r.is_finite() && r > 0.0
263}
264
265/// Circular-orbit speed `√(gm / r)` (CORE-R31); 0 for invalid input or overflow.
266pub fn kepler_speed(gm: f64, r: f64) -> f64 {
267    if !kepler_ok(gm, r) {
268        return 0.0;
269    }
270    finite_or((gm / r).sqrt(), 0.0)
271}
272
273/// Circular-orbit angular velocity `√(gm / r³)` (CORE-R31); 0 for invalid input or overflow.
274///
275/// Computed as `√(gm / r) / r` so `r³` never overflows/underflows on its own.
276pub fn kepler_omega(gm: f64, r: f64) -> f64 {
277    if !kepler_ok(gm, r) {
278        return 0.0;
279    }
280    finite_or((gm / r).sqrt() / r, 0.0)
281}
282
283/// Plot one glyph at fractional cell coordinates, rounded to the nearest cell (CORE-R32).
284///
285/// Bounds are checked in `f64` *before* casting, so NaN/∞/huge values are ignored
286/// rather than saturating into a valid-looking `i32` edge cell.
287#[inline]
288pub fn plot(canvas: &mut Canvas, x: f64, y: f64, glyph: Glyph, ink: Ink) {
289    let (x, y) = (x.round(), y.round());
290    let (w, h) = (
291        f64::from(canvas.size().width()),
292        f64::from(canvas.size().height()),
293    );
294    // Range checks are false for NaN, so this also filters non-finite input.
295    if (0.0..w).contains(&x) && (0.0..h).contains(&y) {
296        canvas.put(x as i32, y as i32, glyph, ink);
297    }
298}
299
300/// A uniform-grid cell list for fixed-radius neighbour queries (boids, molecular
301/// dynamics, SPH) over `[0, width) × [0, height)` (CORE-R54).
302///
303/// [`rebuild`](Self::rebuild) counting-sorts the point indices by bucket into one flat
304/// array (CSR layout: `starts[b]..starts[b + 1]` is bucket `b`), so a query reads a few
305/// contiguous runs instead of chasing per-bucket `Vec`s. With the bucket side at least
306/// the query radius, a query touches ≤ 9 buckets and the total cost is O(n) per frame
307/// instead of O(n²).
308#[derive(Debug, Clone)]
309pub struct SpatialHash {
310    nx: usize,
311    ny: usize,
312    /// Buckets per unit length along x and y.
313    inv_x: f64,
314    inv_y: f64,
315    /// `nx·ny + 1` prefix offsets into `order`.
316    starts: Vec<u32>,
317    /// Point indices grouped by bucket, ascending within each bucket.
318    order: Vec<u32>,
319    /// Bucket of each point, scratch for `rebuild`.
320    keys: Vec<u32>,
321}
322
323impl Default for SpatialHash {
324    /// A one-bucket unit square, the placeholder until a scene's first `resize`.
325    fn default() -> Self {
326        Self::new(1.0, 1.0, 1.0)
327    }
328}
329
330impl SpatialHash {
331    /// Upper bound on buckets per axis, so a tiny `cell` cannot allocate without bound.
332    pub const MAX_AXIS: usize = 1024;
333
334    /// A cell list over `[0, width) × [0, height)` with square buckets of side `cell`
335    /// (rounded so they tile the domain; at most [`MAX_AXIS`](Self::MAX_AXIS) per
336    /// axis). A non-finite or non-positive `width`/`height` is taken as 1, and such a
337    /// `cell` as the whole domain (one bucket).
338    pub fn new(width: f64, height: f64, cell: f64) -> Self {
339        let mut hash = Self {
340            nx: 1,
341            ny: 1,
342            inv_x: 1.0,
343            inv_y: 1.0,
344            starts: Vec::new(),
345            order: Vec::new(),
346            keys: Vec::new(),
347        };
348        hash.resize(width, height, cell);
349        hash
350    }
351
352    /// Change the domain and bucket size (see [`new`](Self::new)) and forget the
353    /// points; allocates only when the bucket count grows.
354    pub fn resize(&mut self, width: f64, height: f64, cell: f64) {
355        let positive = |v: f64| v.is_finite() && v > 0.0;
356        let width = if positive(width) { width } else { 1.0 };
357        let height = if positive(height) { height } else { 1.0 };
358        let cell = if positive(cell) {
359            cell
360        } else {
361            width.max(height)
362        };
363        // Saturating float→int cast, then the axis cap.
364        let buckets = |len: f64| ((len / cell).ceil() as usize).clamp(1, Self::MAX_AXIS);
365        (self.nx, self.ny) = (buckets(width), buckets(height));
366        self.inv_x = self.nx as f64 / width;
367        self.inv_y = self.ny as f64 / height;
368        self.starts.clear();
369        self.starts.resize(self.nx * self.ny + 1, 0);
370        self.order.clear();
371        self.keys.clear();
372    }
373
374    /// Bucket index along one axis: out-of-range values clamp to the border bucket, and
375    /// NaN goes to bucket 0.
376    #[inline]
377    fn axis(v: f64, inv: f64, n: usize) -> usize {
378        let b = (v * inv).floor();
379        // NaN (from a NaN coordinate) and negatives go to bucket 0; the cast saturates.
380        if b.is_nan() || b < 0.0 {
381            0
382        } else {
383            (b as usize).min(n - 1)
384        }
385    }
386
387    /// Re-bucket `points` (by index) in one counting sort: O(n + buckets), stable
388    /// within a bucket, allocation-free unless the point count grows. Points outside
389    /// the domain or non-finite clamp to the border bucket. Indices beyond `u32::MAX`
390    /// are ignored.
391    pub fn rebuild(&mut self, points: &[[f64; 2]]) {
392        let points = &points[..points.len().min(u32::MAX as usize)];
393        let nb = self.nx * self.ny;
394        self.starts.fill(0);
395        self.keys.clear();
396        for p in points {
397            let b = Self::axis(p[1], self.inv_y, self.ny) * self.nx
398                + Self::axis(p[0], self.inv_x, self.nx);
399            // b < nb ≤ MAX_AXIS², which fits in u32.
400            self.keys.push(b as u32);
401            self.starts[b + 1] += 1;
402        }
403        for b in 1..=nb {
404            self.starts[b] += self.starts[b - 1];
405        }
406        // Scatter: `starts[b]` serves as bucket b's write cursor, ending at the start
407        // of bucket b + 1; shifting right by one restores the offsets.
408        self.order.clear();
409        self.order.resize(points.len(), 0);
410        for (i, &b) in self.keys.iter().enumerate() {
411            let slot = &mut self.starts[b as usize];
412            self.order[*slot as usize] = i as u32;
413            *slot += 1;
414        }
415        self.starts.copy_within(0..nb, 1);
416        self.starts[0] = 0;
417    }
418
419    /// Number of points in the last [`rebuild`](Self::rebuild).
420    pub fn len(&self) -> usize {
421        self.order.len()
422    }
423
424    pub fn is_empty(&self) -> bool {
425        self.order.is_empty()
426    }
427
428    /// Call `f(i)` for every point index `i` whose point lies within distance `r` of
429    /// `p`, and possibly for others in the buckets the query disc overlaps, each exactly
430    /// once, bucket rows top to bottom and ascending index within a bucket. Callers
431    /// filter by exact distance. A non-finite `p` or a negative or NaN `r` visits
432    /// nothing; `r = ∞` visits every point.
433    #[inline]
434    pub fn for_each_within(&self, p: [f64; 2], r: f64, mut f: impl FnMut(usize)) {
435        if !(p[0].is_finite() && p[1].is_finite()) || r.is_nan() || r < 0.0 {
436            return;
437        }
438        let (x0, x1) = (
439            Self::axis(p[0] - r, self.inv_x, self.nx),
440            Self::axis(p[0] + r, self.inv_x, self.nx),
441        );
442        let (y0, y1) = (
443            Self::axis(p[1] - r, self.inv_y, self.ny),
444            Self::axis(p[1] + r, self.inv_y, self.ny),
445        );
446        for by in y0..=y1 {
447            // Buckets x0..=x1 of one row are adjacent, so their points are one run.
448            let row = by * self.nx;
449            let (lo, hi) = (self.starts[row + x0], self.starts[row + x1 + 1]);
450            for &i in &self.order[lo as usize..hi as usize] {
451                f(i as usize);
452            }
453        }
454    }
455}
456
457/// Inverse-transform sampling from a tabulated 1-D density (CORE-R58): radial profiles
458/// of orbitals, spectral line shapes, speed distributions.
459///
460/// [`build`](Self::build) integrates the density over `K` equal bins (midpoint rule)
461/// and stores `K` quantiles `F⁻¹(j / (K − 1))` of the resulting piecewise-linear CDF in
462/// an inline array, so it never allocates; [`sample`](Self::sample) interpolates them
463/// in O(1). Quantiles skip zero-density bins, though interpolation between two quantiles
464/// can cross a zero-density gap narrower than one quantile step.
465#[derive(Debug, Clone)]
466pub struct InverseCdf<const K: usize> {
467    a: f64,
468    b: f64,
469    /// Exactly uniform (constant or degenerate density): `sample` is `a + u·(b − a)`.
470    uniform: bool,
471    q: [f64; K],
472}
473
474impl<const K: usize> InverseCdf<K> {
475    /// Tabulate `density` (non-negative; negative or non-finite values count as 0) on
476    /// `[a, b]` (CORE-R58). Non-finite bounds are taken as 0 and reversed bounds are
477    /// swapped. A density that is zero or non-finite everywhere, a constant one, and
478    /// `K < 2` all give the exact uniform sampler.
479    pub fn build(a: f64, b: f64, mut density: impl FnMut(f64) -> f64) -> Self {
480        let clean = |v: f64| if v.is_finite() { v } else { 0.0 };
481        let (a, b) = (clean(a), clean(b));
482        let (a, b) = if b < a { (b, a) } else { (a, b) };
483        let mut s = Self {
484            a,
485            b,
486            uniform: true,
487            q: [0.0; K],
488        };
489        // An infinite span (a = −MAX, b = MAX) has no finite bins: stay uniform.
490        if K < 2 || a == b || !(b - a).is_finite() {
491            return s;
492        }
493        let h = (b - a) / K as f64;
494        // Bin masses first (at the bin midpoints), then their running sum in place.
495        let mut cdf = [0.0f64; K];
496        for (i, m) in cdf.iter_mut().enumerate() {
497            let v = density(a + (i as f64 + 0.5) * h);
498            *m = if v.is_finite() && v > 0.0 { v } else { 0.0 };
499        }
500        let max = cdf.iter().fold(0.0f64, |m, &v| m.max(v));
501        if max == 0.0 || cdf.iter().all(|&v| v == cdf[0]) {
502            return s;
503        }
504        // Scale by the max first so the running sum cannot overflow.
505        let mut acc = 0.0;
506        let mut last = 0;
507        for (i, m) in cdf.iter_mut().enumerate() {
508            if *m > 0.0 {
509                last = i;
510            }
511            acc += *m / max;
512            *m = acc;
513        }
514        for m in &mut cdf {
515            *m /= acc;
516        }
517        cdf[K - 1] = 1.0;
518
519        // Two-pointer inversion: quantile j lies in the first bin whose CDF exceeds
520        // u_j (never a zero-mass bin), linearly within it.
521        let mut i = 0;
522        for (j, q) in s.q.iter_mut().enumerate() {
523            let x = if j == K - 1 {
524                a + (last + 1) as f64 * h
525            } else {
526                let u = j as f64 / (K - 1) as f64;
527                while i < K - 1 && cdf[i] <= u {
528                    i += 1;
529                }
530                let lo = if i == 0 { 0.0 } else { cdf[i - 1] };
531                // cdf[i] > u ≥ lo, so the denominator is positive.
532                let frac = ((u - lo) / (cdf[i] - lo)).clamp(0.0, 1.0);
533                a + (i as f64 + frac) * h
534            };
535            *q = x.clamp(a, b);
536        }
537        s.uniform = false;
538        s
539    }
540
541    /// The sample for a uniform variate `u ∈ [0, 1]` (clamped, NaN ⇒ 0): monotone
542    /// non-decreasing in `u`, always in `[a, b]`, and exactly `a + u·(b − a)` for a
543    /// uniform density (CORE-R58).
544    #[inline]
545    pub fn sample(&self, u: f64) -> f64 {
546        let u = if u.is_nan() { 0.0 } else { u.clamp(0.0, 1.0) };
547        let x = if self.uniform {
548            let x = self.a + u * (self.b - self.a);
549            // Only an overflowing span gets here non-finite; blend the ends instead.
550            if x.is_finite() {
551                x
552            } else {
553                self.a * (1.0 - u) + self.b * u
554            }
555        } else {
556            let t = u * (K - 1) as f64;
557            let j = (t as usize).min(K - 2);
558            let f = t - j as f64;
559            self.q[j] + (self.q[j + 1] - self.q[j]) * f
560        };
561        x.clamp(self.a, self.b)
562    }
563}