use super::*;
#[must_use]
pub fn ray_sphere_intersect(origin: Vec3, dir: Vec3, radius: f32) -> Option<(f32, f32)> {
let b: f32 = origin.dot(dir);
let c: f32 = origin.length_sq() - radius * radius;
let disc: f32 = b * b - c;
if disc < 0.0 {
return None;
}
let root: f32 = disc.sqrt();
Some((-b - root, -b + root))
}
#[must_use]
pub fn rayleigh_phase(cos_theta: f32) -> f32 {
let mu: f32 = cos_theta.clamp(-1.0, 1.0);
(3.0 / (16.0 * PI)) * (1.0 + mu * mu)
}
#[must_use]
pub fn cornette_shanks_mie_phase(cos_theta: f32, g: f32) -> f32 {
let mu: f32 = cos_theta.clamp(-1.0, 1.0);
let cg: f32 = g.clamp(-0.95, 0.95);
let g2: f32 = cg * cg;
let num: f32 = 3.0 * (1.0 - g2) * (1.0 + mu * mu);
let base: f32 = (1.0 + g2 - 2.0 * cg * mu).max(1.0e-5);
let den: f32 = 8.0 * PI * (2.0 + g2) * base * base.sqrt();
num / den.max(1.0e-6)
}
#[must_use]
pub fn procedural_night_starfield(view_dir: Vec3, intensity: f32) -> Vec3 {
let dir: Vec3 = view_dir.normalize();
if dir.get_y() <= 0.02 || intensity <= 0.0 {
return Vec3::zero();
}
let grid: f32 = 160.0;
let cell_x: i32 = (dir.get_x() * grid).floor() as i32;
let cell_y: i32 = (dir.get_y() * grid).floor() as i32;
let cell_z: i32 = (dir.get_z() * grid).floor() as i32;
let h0: u32 = (cell_x.wrapping_mul(374_761_393) as u32)
^ (cell_y.wrapping_mul(668_265_263) as u32)
^ (cell_z.wrapping_mul(2_147_483_647) as u32);
let h1: u32 = (h0 ^ (h0 >> 13)).wrapping_mul(1_274_126_177);
let hash_u: u32 = h1 ^ (h1 >> 16);
let prob: f32 = (hash_u as f32) / (u32::MAX as f32);
if prob < 0.992 {
return Vec3::zero();
}
let star_mag: f32 = ((prob - 0.992) / 0.008).clamp(0.0, 1.0);
let brightness: f32 = star_mag * star_mag * intensity * dir.get_y().clamp(0.0, 1.0).sqrt();
let temp_hash: f32 = (((hash_u >> 8) & 0xFF) as f32) / 255.0;
let tint: Vec3 = Vec3::new(
0.75 + 0.25 * temp_hash,
0.84 + 0.14 * temp_hash,
1.0 - 0.25 * temp_hash,
);
tint.scale(brightness)
}
#[must_use]
pub fn solar_ephemeris_direction(
time_of_day_hours: f32,
latitude_deg: f32,
day_of_year: f32,
) -> Vec3 {
let hours: f32 = if time_of_day_hours.is_finite() {
time_of_day_hours.rem_euclid(24.0)
} else {
12.0
};
let lat_rad: f32 = if latitude_deg.is_finite() {
latitude_deg.clamp(-89.0, 89.0).to_radians()
} else {
35.0_f32.to_radians()
};
let doy: f32 = if day_of_year.is_finite() {
day_of_year.clamp(1.0, 365.0)
} else {
81.0
};
let declination: f32 = 23.44_f32.to_radians() * (TAU * (doy - 81.0) / 365.0).sin();
let hour_angle: f32 = ((hours - 12.0) * 15.0).to_radians();
let sin_lat: f32 = lat_rad.sin();
let cos_lat: f32 = lat_rad.cos();
let sin_dec: f32 = declination.sin();
let cos_dec: f32 = declination.cos();
let sin_h: f32 = hour_angle.sin();
let cos_h: f32 = hour_angle.cos();
let sun_up: f32 = (sin_lat * sin_dec + cos_lat * cos_dec * cos_h).clamp(-1.0, 1.0);
let sun_east: f32 = -cos_dec * sin_h;
let sun_south: f32 = cos_lat * sin_dec - sin_lat * cos_dec * cos_h;
Vec3::new(sun_east, sun_up, -sun_south).normalize()
}