#![cfg(test)]
use crate::na::{Point, Quaternion, SVector, Translation3, Unit, UnitQuaternion};
use crate::{Circle2, Iso2, Iso3};
use rand::distr::{Distribution, Uniform};
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use rand_distr::Normal;
use std::f64::consts::PI;
#[allow(clippy::large_enum_variant)]
enum RngSource {
Seeded(StdRng),
Thread,
}
pub struct RandomGeometry<const D: usize> {
rng: RngSource,
}
impl<const D: usize> Default for RandomGeometry<D> {
fn default() -> Self {
Self::new()
}
}
impl<const D: usize> RandomGeometry<D> {
pub fn new() -> Self {
Self {
rng: RngSource::Thread,
}
}
pub fn from_seed(seed: u64) -> Self {
Self {
rng: RngSource::Seeded(StdRng::seed_from_u64(seed)),
}
}
pub fn f64(&mut self, lo: f64, hi: f64) -> f64 {
let u = Uniform::new(lo, hi).unwrap();
match &mut self.rng {
RngSource::Seeded(r) => u.sample(r),
RngSource::Thread => u.sample(&mut rand::rng()),
}
}
pub fn f64_sym(&mut self, hi: f64) -> f64 {
self.f64(-hi, hi)
}
pub fn positive(&mut self, limit: f64) -> f64 {
self.f64(0.0, limit)
}
pub fn bool(&mut self) -> bool {
match &mut self.rng {
RngSource::Seeded(r) => r.random_bool(0.5),
RngSource::Thread => rand::rng().random_bool(0.5),
}
}
pub fn gaussian_f64(&mut self, mean: f64, std_dev: f64) -> f64 {
let n = Normal::new(mean, std_dev).unwrap();
match &mut self.rng {
RngSource::Seeded(r) => n.sample(r),
RngSource::Thread => n.sample(&mut rand::rng()),
}
}
pub fn angle_sym_pi(&mut self) -> f64 {
self.f64(-PI, PI)
}
pub fn angle_sym_2pi(&mut self) -> f64 {
self.f64(-2.0 * PI, 2.0 * PI)
}
pub fn angle_pos_2pi(&mut self) -> f64 {
self.f64(0.0, 2.0 * PI)
}
pub fn point(&mut self, limit: f64) -> Point<f64, D> {
let mut p = Point::origin();
for i in 0..D {
p[i] = self.f64(-limit, limit);
}
p
}
pub fn vector<const N: usize>(&mut self, limit: f64) -> SVector<f64, N> {
let mut v = SVector::zeros();
for i in 0..N {
v[i] = self.f64(-limit, limit);
}
v
}
pub fn gaussian_vector<const N: usize>(&mut self, std_dev: f64) -> SVector<f64, N> {
let mut v = SVector::zeros();
for i in 0..N {
v[i] = self.gaussian_f64(0.0, std_dev);
}
v
}
pub fn unit_vec(&mut self) -> Unit<SVector<f64, D>> {
loop {
let v: SVector<f64, D> = self.gaussian_vector(1.0);
if v.norm() > 1e-12 {
return Unit::new_normalize(v);
}
}
}
}
pub type RandomGeometry2 = RandomGeometry<2>;
pub type RandomGeometry3 = RandomGeometry<3>;
impl RandomGeometry2 {
pub fn iso2(&mut self, t: f64) -> Iso2 {
Iso2::new(self.vector(t), self.angle_sym_pi())
}
pub fn circle2(&mut self, center_limit: f64, r_min: f64, r_max: f64) -> Circle2 {
let c = self.point(center_limit);
let r = self.f64(r_min, r_max);
Circle2::new(c.x, c.y, r)
}
}
impl RandomGeometry3 {
pub fn iso3(&mut self, t: f64) -> Iso3 {
let translation = Translation3::from(self.vector::<3>(t));
let g = self.gaussian_vector::<4>(1.0);
let rotation = UnitQuaternion::new_normalize(Quaternion::new(g[0], g[1], g[2], g[3]));
Iso3::from_parts(translation, rotation)
}
}