use crate::core::{Mesh, Object3D};
use crate::geometries::SphereGeometry;
use crate::materials::{Material, RenderState};
use crate::math::{Color, Vector3};
use crate::ShaderMaterial;
use super::heightfield::Heightfield;
use super::sand::{Downwind, SandBed};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DuneShape {
pub wavelength: f32,
pub height: f32,
pub warp: f32,
pub flow: f32,
pub secondary: f32,
pub stretch: f32,
pub wind: Downwind,
pub shaping: f32,
pub seed: u64,
}
impl Default for DuneShape {
fn default() -> Self {
Self {
wavelength: 110.0,
height: 14.0,
warp: 0.4,
flow: 0.35,
secondary: 0.3,
stretch: 2.2,
wind: Downwind::PlusX,
shaping: 24.0,
seed: 7,
}
}
}
fn hash(x: i64, y: i64, seed: u64) -> f32 {
let mut h = (x as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15)
^ (y as u64).wrapping_mul(0xC2B2_AE3D_27D4_EB4F)
^ seed.wrapping_mul(0x1656_67B1_9E37_79F9);
h ^= h >> 31;
h = h.wrapping_mul(0xBF58_476D_1CE4_E5B9);
h ^= h >> 29;
(h >> 40) as f32 / (1u64 << 24) as f32
}
fn noise(x: f32, y: f32, period: [i64; 2], seed: u64) -> f32 {
let (ix, iy) = (x.floor() as i64, y.floor() as i64);
let (fx, fy) = (x - ix as f32, y - iy as f32);
let (ux, uy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));
let h = |i: i64, j: i64| hash(i.rem_euclid(period[0]), j.rem_euclid(period[1]), seed);
let a = h(ix, iy) + (h(ix + 1, iy) - h(ix, iy)) * ux;
let b = h(ix, iy + 1) + (h(ix + 1, iy + 1) - h(ix, iy + 1)) * ux;
a + (b - a) * uy
}
fn fbm(x: f32, y: f32, period: [i64; 2], seed: u64) -> f32 {
let mut s = 0.0;
let mut a = 0.5;
let mut f = 1.0;
for o in 0..3 {
s += a * noise(
x * f,
y * f,
[period[0] * f as i64, period[1] * f as i64],
seed + o,
);
a *= 0.5;
f *= 2.0;
}
s / 0.875
}
fn voronoi(x: f32, y: f32, period: [i64; 2], seed: u64) -> f32 {
let (ix, iy) = (x.floor() as i64, y.floor() as i64);
let mut best = f32::INFINITY;
for j in -1..=1 {
for i in -1..=1 {
let (cx, cy) = (ix + i, iy + j);
let (px, py) = (cx.rem_euclid(period[0]), cy.rem_euclid(period[1]));
let fx = cx as f32 + 0.1 + 0.8 * hash(px, py, seed);
let fy = cy as f32 + 0.1 + 0.8 * hash(px, py, seed ^ 0xabc);
best = best.min((fx - x).hypot(fy - y));
}
}
best
}
impl SandBed {
pub fn dunes(&mut self, shape: DuneShape) {
let f = &mut self.field;
let across_x = matches!(shape.wind, Downwind::PlusZ | Downwind::MinusZ);
let length = |cells: usize, along: bool| {
let extent = cells as f32 * f.cell;
let l = shape.wavelength.max(1.0) * if along { 1.0 } else { shape.stretch.max(0.2) };
((extent / l).round().max(1.0) as i64, extent)
};
let (px, ex) = length(f.nx, !across_x);
let (pz, ez) = length(f.nz, across_x);
let period = [px, pz];
let seed = shape.seed;
for j in 0..f.nz {
for i in 0..f.nx {
let x = (i as f32 + 0.5) * f.cell * px as f32 / ex;
let y = (j as f32 + 0.5) * f.cell * pz as f32 / ez;
let wx = (fbm(x, y, period, seed + 11) - 0.5) * 2.0 * shape.warp;
let wy = (fbm(x + 17.3, y + 5.1, period, seed + 13) - 0.5) * 2.0 * shape.warp;
let (qx, qy) = (x + wx, y + wy);
let f1 = (voronoi(qx, qy, period, seed) / 0.7).min(1.0);
let mut h = f1.powf(1.3);
h += (fbm(x * 2.0, y * 2.0, [period[0] * 2, period[1] * 2], seed + 21) - 0.5)
* shape.flow;
let f2 = (voronoi(
qx * 3.0,
qy * 3.0,
[period[0] * 3, period[1] * 3],
seed + 31,
) / 0.7)
.min(1.0);
h += f2.powf(1.3) * shape.secondary * 0.35;
let k = i + f.nx * j;
f.depth[k] = (h.max(0.0) + 0.05) * shape.height;
}
}
f.touch_all();
f.version += 1;
if shape.shaping > 0.0 {
let cells = f.nx * f.nz;
let saved = self.saltation;
self.saltation.slab = shape.height / 100.0;
self.saltation.hop = 2;
let total = (shape.shaping * cells as f32) as usize;
let rounds = 24;
for _ in 0..rounds {
self.carry(shape.wind, total / rounds);
self.settle_within(4 * cells);
}
self.saltation = saved;
}
for _ in 0..200 {
if self.field.relax(self.angle_of_repose, 64) <= 0.0 {
break;
}
}
}
}
pub fn crests(
field: &Heightfield,
downwind: Downwind,
steep: f32,
lift: f32,
limit: usize,
) -> Vec<Vector3> {
let (di, dj) = downwind.step();
let tan = steep.tan() * field.cell;
let mut out = Vec::new();
for j in 1..field.nz.saturating_sub(1) {
for i in 1..field.nx.saturating_sub(1) {
let at =
|a: i64, b: i64| field.surface((i as i64 + a) as usize, (j as i64 + b) as usize);
let h = at(0, 0);
if h - at(di, dj) > tan && h >= at(-di, -dj) - 0.02 * tan {
let [x, z] = field.cell_center(i, j);
out.push(Vector3::new(x, h + lift, z));
}
}
}
if out.len() > limit && limit > 0 {
let step = out.len() as f32 / limit as f32;
out = (0..limit)
.map(|k| out[(k as f32 * step) as usize])
.collect();
}
out
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DesertTime {
pub sun: Vector3,
pub sun_color: Color,
pub sun_intensity: f32,
pub sun_radius: f32,
pub zenith: Color,
pub horizon: Color,
pub haze: f32,
pub glow: f32,
pub sky_light: Color,
pub ground_light: Color,
pub sky_intensity: f32,
pub sand: Color,
pub shadow: Color,
pub stars: f32,
}
fn dir(azimuth_deg: f32, elevation_deg: f32) -> Vector3 {
let (a, e) = (azimuth_deg.to_radians(), elevation_deg.to_radians());
Vector3::new(a.cos() * e.cos(), e.sin(), a.sin() * e.cos())
}
impl DesertTime {
pub fn day() -> Self {
Self {
sun: dir(-30.0, 52.0),
sun_color: Color::new(1.0, 0.95, 0.88),
sun_intensity: 3.4,
sun_radius: 0.0047,
zenith: Color::new(0.10, 0.24, 0.62),
horizon: Color::new(0.62, 0.70, 0.80),
haze: 0.0016,
glow: 0.35,
sky_light: Color::new(0.45, 0.6, 0.9),
ground_light: Color::new(0.55, 0.38, 0.22),
sky_intensity: 0.9,
sand: Color::new(0.72, 0.42, 0.18),
shadow: Color::new(0.30, 0.20, 0.16),
stars: 0.0,
}
}
pub fn dawn() -> Self {
Self {
sun: dir(160.0, 9.0),
sun_color: Color::new(1.0, 0.72, 0.5),
sun_intensity: 2.6,
sun_radius: 0.0055,
zenith: Color::new(0.10, 0.16, 0.36),
horizon: Color::new(0.80, 0.62, 0.58),
haze: 0.0026,
glow: 0.7,
sky_light: Color::new(0.45, 0.48, 0.7),
ground_light: Color::new(0.5, 0.32, 0.22),
sky_intensity: 0.55,
sand: Color::new(0.70, 0.40, 0.20),
shadow: Color::new(0.20, 0.18, 0.30),
stars: 0.05,
}
}
pub fn sunset() -> Self {
Self {
sun: dir(15.0, 5.0),
sun_color: Color::new(1.0, 0.52, 0.22),
sun_intensity: 3.0,
sun_radius: 0.006,
zenith: Color::new(0.06, 0.09, 0.24),
horizon: Color::new(0.95, 0.48, 0.24),
haze: 0.0022,
glow: 0.9,
sky_light: Color::new(0.35, 0.32, 0.55),
ground_light: Color::new(0.45, 0.22, 0.10),
sky_intensity: 0.5,
sand: Color::new(0.74, 0.40, 0.16),
shadow: Color::new(0.16, 0.12, 0.26),
stars: 0.0,
}
}
pub fn night() -> Self {
Self {
sun: dir(-60.0, 38.0),
sun_color: Color::new(0.62, 0.72, 1.0),
sun_intensity: 0.32,
sun_radius: 0.0045,
zenith: Color::new(0.004, 0.007, 0.02),
horizon: Color::new(0.025, 0.035, 0.06),
haze: 0.0013,
glow: 0.5,
sky_light: Color::new(0.08, 0.11, 0.2),
ground_light: Color::new(0.03, 0.03, 0.04),
sky_intensity: 0.6,
sand: Color::new(0.55, 0.40, 0.26),
shadow: Color::new(0.03, 0.04, 0.08),
stars: 1.0,
}
}
pub fn all() -> [(&'static str, Self); 4] {
[
("dawn", Self::dawn()),
("day", Self::day()),
("sunset", Self::sunset()),
("night", Self::night()),
]
}
pub fn fog(&self) -> crate::scene::FogParams {
crate::scene::FogParams {
color: self.horizon,
density: self.haze,
mode: 2,
..crate::scene::FogParams::default()
}
}
pub fn sky_material(&self) -> Material {
let v = |c: Color| format!("vec3<f32>({:?}, {:?}, {:?})", c.r, c.g, c.b);
let s = self.sun.normalize();
let consts = format!(
"const SKY_SUN : vec3<f32> = vec3<f32>({:?}, {:?}, {:?});\n\
const SKY_SUN_COLOR : vec3<f32> = {};\n\
const SKY_ZENITH : vec3<f32> = {};\n\
const SKY_HORIZON : vec3<f32> = {};\n\
const SKY_GLOW : f32 = {:?};\n\
const SKY_DISC : f32 = {:?};\n\
const SKY_STARS : f32 = {:?};\n",
s.x,
s.y,
s.z,
v(Color::new(
self.sun_color.r * self.sun_intensity,
self.sun_color.g * self.sun_intensity,
self.sun_color.b * self.sun_intensity
)),
v(self.zenith),
v(self.horizon),
self.glow,
self.sun_radius,
self.stars,
);
Material::Shader(ShaderMaterial {
fragment: consts + SKY_WGSL,
side: 2,
render_state: RenderState {
depth_write: Some(false),
..RenderState::DEFAULT
},
fallback_color: self.horizon,
..Default::default()
})
}
}
pub fn sky_dome(time: &DesertTime, radius: f32) -> Object3D {
let mut o = Object3D::mesh(Mesh::new(
SphereGeometry::new(radius, 48, 24),
time.sky_material(),
));
o.cast_shadow = false;
o.receive_shadow = false;
o.render_order = -1000;
o.name = "sky".into();
o
}
pub(crate) const SKY_WGSL: &str = crate::wgsl!(
r#"
fn sky_hash(p : vec2<f32>) -> f32 {
var q = fract(p * vec2<f32>(127.31, 311.71));
q = q + vec2<f32>(dot(q, q + 19.19));
return fract(q.x * q.y);
}
@fragment
fn fs_main(in : VsOut) -> @location(0) vec4<f32> {
let d = normalize(in.world_pos - frame.camera_position.xyz);
let up = max(d.y, 0.0);
var col = mix(SKY_HORIZON, SKY_ZENITH, pow(up, 0.45));
let cs = dot(d, SKY_SUN);
// The haze toward the sun, strongest along the horizon.
col = col * (1.0 + SKY_GLOW * pow(max(cs, 0.0), 8.0) * (1.0 - up));
// The aureole: light scattered a little way off the sun by the haze's
// larger particles.
col = col + SKY_SUN_COLOR * (0.01 * pow(max(cs, 0.0), 400.0) + 0.04 * pow(max(cs, 0.0), 4000.0));
// The disc, gone below the horizon.
let disc = smoothstep(cos(SKY_DISC * 1.2), cos(SKY_DISC), cs);
col = col + SKY_SUN_COLOR * disc * 12.0 * smoothstep(-0.01, 0.01, d.y);
if (SKY_STARS > 0.0 && d.y > 0.0) {
// A star in one cell in a few hundred, by direction.
let a = vec2<f32>(atan2(d.z, d.x) * 180.0, asin(d.y) * 180.0);
let c = floor(a);
let h = sky_hash(c);
let f = fract(a) - vec2<f32>(sky_hash(c + 3.1), sky_hash(c + 7.7)) * 0.6 - 0.2;
let star = step(0.985, h) * smoothstep(0.12, 0.0, length(f)) * (h - 0.985) * 60.0;
col = col + vec3<f32>(0.8, 0.85, 1.0) * star * SKY_STARS * smoothstep(0.0, 0.15, d.y);
}
return vec4<f32>(framebuffer_encode(apply_tone_mapping(col)), 1.0);
}
"#
);