use std::f64::consts::TAU;
use rand::Rng;
use crate::trig::Trig;
use crate::{Canvas, Glyph, Ink};
#[derive(Debug, Clone)]
pub struct ParticlePool<P> {
items: Vec<P>,
capacity: usize,
}
impl<P> Default for ParticlePool<P> {
fn default() -> Self {
Self::with_capacity(0)
}
}
impl<P> ParticlePool<P> {
pub fn with_capacity(capacity: usize) -> Self {
Self {
items: Vec::with_capacity(capacity),
capacity,
}
}
#[inline]
pub fn spawn(&mut self, p: P) -> bool {
if self.items.len() < self.capacity {
self.items.push(p);
true
} else {
false
}
}
pub fn retain(&mut self, mut f: impl FnMut(&mut P) -> bool) {
let mut i = 0;
while i < self.items.len() {
if f(&mut self.items[i]) {
i += 1;
} else {
self.items.swap_remove(i);
}
}
}
#[inline]
pub fn len(&self) -> usize {
self.items.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
#[inline]
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn iter(&self) -> std::slice::Iter<'_, P> {
self.items.iter()
}
pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, P> {
self.items.iter_mut()
}
pub fn clear(&mut self) {
self.items.clear();
}
pub fn set_capacity(&mut self, capacity: usize) {
self.items.truncate(capacity);
self.items.reserve_exact(capacity - self.items.len());
self.capacity = capacity;
}
}
impl<'a, P> IntoIterator for &'a ParticlePool<P> {
type Item = &'a P;
type IntoIter = std::slice::Iter<'a, P>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, P> IntoIterator for &'a mut ParticlePool<P> {
type Item = &'a mut P;
type IntoIter = std::slice::IterMut<'a, P>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
#[derive(Debug, Clone)]
pub struct Trail<T: Copy> {
buf: Vec<T>,
head: usize,
capacity: usize,
}
impl<T: Copy> Trail<T> {
pub fn new(n: usize) -> Self {
Self {
buf: Vec::with_capacity(n),
head: 0,
capacity: n,
}
}
#[inline]
pub fn push(&mut self, v: T) {
if self.buf.len() < self.capacity {
self.buf.push(v);
} else if self.capacity > 0 {
self.buf[self.head] = v;
self.head = (self.head + 1) % self.capacity;
}
}
pub fn iter(&self) -> impl DoubleEndedIterator<Item = &T> + '_ {
let (newer, older) = self.buf.split_at(self.head);
older.iter().chain(newer)
}
pub fn newest(&self) -> Option<T> {
self.iter().next_back().copied()
}
#[inline]
pub fn len(&self) -> usize {
self.buf.len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.buf.is_empty()
}
#[inline]
pub fn capacity(&self) -> usize {
self.capacity
}
pub fn clear(&mut self) {
self.buf.clear();
self.head = 0;
}
}
#[inline]
fn box_muller(rng: &mut impl Rng) -> (f64, f64) {
let u1 = 1.0 - rng.random::<f64>();
let u2 = rng.random::<f64>();
let r = (-2.0 * u1.ln()).sqrt();
let (s, c) = (TAU * u2).sin_cos_det();
(r * c, r * s)
}
#[inline]
fn clean_sd(sd: f64) -> f64 {
if sd.is_finite() { sd.abs() } else { 0.0 }
}
#[inline]
fn finite_or(v: f64, fallback: f64) -> f64 {
if v.is_finite() { v } else { fallback }
}
pub fn gaussian(rng: &mut impl Rng, mean: f64, sd: f64) -> f64 {
let (z, _) = box_muller(rng);
let mean = finite_or(mean, 0.0);
let sd = clean_sd(sd);
if sd == 0.0 {
return mean;
}
finite_or(mean + sd * z, mean)
}
pub fn gaussian2(rng: &mut impl Rng, sd: f64) -> (f64, f64) {
let (zx, zy) = box_muller(rng);
let sd = clean_sd(sd);
if sd == 0.0 {
return (0.0, 0.0);
}
let (x, y) = (sd * zx, sd * zy);
if x.is_finite() && y.is_finite() {
(x, y)
} else {
(0.0, 0.0)
}
}
#[inline]
fn kepler_ok(gm: f64, r: f64) -> bool {
gm.is_finite() && gm >= 0.0 && r.is_finite() && r > 0.0
}
pub fn kepler_speed(gm: f64, r: f64) -> f64 {
if !kepler_ok(gm, r) {
return 0.0;
}
finite_or((gm / r).sqrt(), 0.0)
}
pub fn kepler_omega(gm: f64, r: f64) -> f64 {
if !kepler_ok(gm, r) {
return 0.0;
}
finite_or((gm / r).sqrt() / r, 0.0)
}
#[inline]
pub fn plot(canvas: &mut Canvas, x: f64, y: f64, glyph: Glyph, ink: Ink) {
let (x, y) = (x.round(), y.round());
let (w, h) = (
f64::from(canvas.size().width()),
f64::from(canvas.size().height()),
);
if (0.0..w).contains(&x) && (0.0..h).contains(&y) {
canvas.put(x as i32, y as i32, glyph, ink);
}
}
#[derive(Debug, Clone)]
pub struct SpatialHash {
nx: usize,
ny: usize,
inv_x: f64,
inv_y: f64,
starts: Vec<u32>,
order: Vec<u32>,
keys: Vec<u32>,
}
impl Default for SpatialHash {
fn default() -> Self {
Self::new(1.0, 1.0, 1.0)
}
}
impl SpatialHash {
pub const MAX_AXIS: usize = 1024;
pub fn new(width: f64, height: f64, cell: f64) -> Self {
let mut hash = Self {
nx: 1,
ny: 1,
inv_x: 1.0,
inv_y: 1.0,
starts: Vec::new(),
order: Vec::new(),
keys: Vec::new(),
};
hash.resize(width, height, cell);
hash
}
pub fn resize(&mut self, width: f64, height: f64, cell: f64) {
let positive = |v: f64| v.is_finite() && v > 0.0;
let width = if positive(width) { width } else { 1.0 };
let height = if positive(height) { height } else { 1.0 };
let cell = if positive(cell) {
cell
} else {
width.max(height)
};
let buckets = |len: f64| ((len / cell).ceil() as usize).clamp(1, Self::MAX_AXIS);
(self.nx, self.ny) = (buckets(width), buckets(height));
self.inv_x = self.nx as f64 / width;
self.inv_y = self.ny as f64 / height;
self.starts.clear();
self.starts.resize(self.nx * self.ny + 1, 0);
self.order.clear();
self.keys.clear();
}
#[inline]
fn axis(v: f64, inv: f64, n: usize) -> usize {
let b = (v * inv).floor();
if b.is_nan() || b < 0.0 {
0
} else {
(b as usize).min(n - 1)
}
}
pub fn rebuild(&mut self, points: &[[f64; 2]]) {
let points = &points[..points.len().min(u32::MAX as usize)];
let nb = self.nx * self.ny;
self.starts.fill(0);
self.keys.clear();
for p in points {
let b = Self::axis(p[1], self.inv_y, self.ny) * self.nx
+ Self::axis(p[0], self.inv_x, self.nx);
self.keys.push(b as u32);
self.starts[b + 1] += 1;
}
for b in 1..=nb {
self.starts[b] += self.starts[b - 1];
}
self.order.clear();
self.order.resize(points.len(), 0);
for (i, &b) in self.keys.iter().enumerate() {
let slot = &mut self.starts[b as usize];
self.order[*slot as usize] = i as u32;
*slot += 1;
}
self.starts.copy_within(0..nb, 1);
self.starts[0] = 0;
}
pub fn len(&self) -> usize {
self.order.len()
}
pub fn is_empty(&self) -> bool {
self.order.is_empty()
}
#[inline]
pub fn for_each_within(&self, p: [f64; 2], r: f64, mut f: impl FnMut(usize)) {
if !(p[0].is_finite() && p[1].is_finite()) || r.is_nan() || r < 0.0 {
return;
}
let (x0, x1) = (
Self::axis(p[0] - r, self.inv_x, self.nx),
Self::axis(p[0] + r, self.inv_x, self.nx),
);
let (y0, y1) = (
Self::axis(p[1] - r, self.inv_y, self.ny),
Self::axis(p[1] + r, self.inv_y, self.ny),
);
for by in y0..=y1 {
let row = by * self.nx;
let (lo, hi) = (self.starts[row + x0], self.starts[row + x1 + 1]);
for &i in &self.order[lo as usize..hi as usize] {
f(i as usize);
}
}
}
}
#[derive(Debug, Clone)]
pub struct InverseCdf<const K: usize> {
a: f64,
b: f64,
uniform: bool,
q: [f64; K],
}
impl<const K: usize> InverseCdf<K> {
pub fn build(a: f64, b: f64, mut density: impl FnMut(f64) -> f64) -> Self {
let clean = |v: f64| if v.is_finite() { v } else { 0.0 };
let (a, b) = (clean(a), clean(b));
let (a, b) = if b < a { (b, a) } else { (a, b) };
let mut s = Self {
a,
b,
uniform: true,
q: [0.0; K],
};
if K < 2 || a == b || !(b - a).is_finite() {
return s;
}
let h = (b - a) / K as f64;
let mut cdf = [0.0f64; K];
for (i, m) in cdf.iter_mut().enumerate() {
let v = density(a + (i as f64 + 0.5) * h);
*m = if v.is_finite() && v > 0.0 { v } else { 0.0 };
}
let max = cdf.iter().fold(0.0f64, |m, &v| m.max(v));
if max == 0.0 || cdf.iter().all(|&v| v == cdf[0]) {
return s;
}
let mut acc = 0.0;
let mut last = 0;
for (i, m) in cdf.iter_mut().enumerate() {
if *m > 0.0 {
last = i;
}
acc += *m / max;
*m = acc;
}
for m in &mut cdf {
*m /= acc;
}
cdf[K - 1] = 1.0;
let mut i = 0;
for (j, q) in s.q.iter_mut().enumerate() {
let x = if j == K - 1 {
a + (last + 1) as f64 * h
} else {
let u = j as f64 / (K - 1) as f64;
while i < K - 1 && cdf[i] <= u {
i += 1;
}
let lo = if i == 0 { 0.0 } else { cdf[i - 1] };
let frac = ((u - lo) / (cdf[i] - lo)).clamp(0.0, 1.0);
a + (i as f64 + frac) * h
};
*q = x.clamp(a, b);
}
s.uniform = false;
s
}
#[inline]
pub fn sample(&self, u: f64) -> f64 {
let u = if u.is_nan() { 0.0 } else { u.clamp(0.0, 1.0) };
let x = if self.uniform {
let x = self.a + u * (self.b - self.a);
if x.is_finite() {
x
} else {
self.a * (1.0 - u) + self.b * u
}
} else {
let t = u * (K - 1) as f64;
let j = (t as usize).min(K - 2);
let f = t - j as f64;
self.q[j] + (self.q[j + 1] - self.q[j]) * f
};
x.clamp(self.a, self.b)
}
}