mod maps;
#[cfg(not(target_arch = "wasm32"))]
mod nasa;
pub use maps::{
blackbody_rgb, blend_polar_cap, blend_polar_cap_in, direction, ease_poles,
equirect_to_cube_faces, fbm, generate_earth_maps, generate_starfield, ridged, value_noise,
HeightField, MapBuffer, PlanetMaps, CUBE_FACES,
};
#[cfg(not(target_arch = "wasm32"))]
pub use nasa::{clouds_from_grey, EarthTextures, MapSources};
use std::sync::Arc;
use crate::core::{Mesh, Object3D, ObjectId};
use crate::geometries::SphereGeometry;
use crate::materials::{AtmosphereMaterial, BasicMaterial, Material, StandardMaterial};
use crate::math::{Color, Quaternion, Vector3};
use crate::scene::Scene;
use crate::textures::Texture;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PlanetHandles {
pub surface: ObjectId,
pub clouds: Option<ObjectId>,
pub atmosphere: Option<ObjectId>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Atmosphere {
pub height: f32,
pub color: Color,
pub sunset_color: Color,
pub intensity: f32,
pub falloff: f32,
pub ozone: f32,
pub aurora: f32,
pub aurora_color: Color,
pub aurora_colatitude: f32,
}
impl Default for Atmosphere {
fn default() -> Self {
Self {
height: 0.045,
color: Color::new(0.30, 0.55, 1.0),
sunset_color: Color::new(1.0, 0.48, 0.20),
intensity: 2.6,
falloff: 2.3,
ozone: 0.9,
aurora: 0.0,
aurora_color: Color::new(0.25, 1.0, 0.45),
aurora_colatitude: 23.0,
}
}
}
impl Atmosphere {
pub fn earth() -> Self {
Self::default()
}
pub fn mars() -> Self {
Self {
height: 0.012,
color: Color::new(0.82, 0.55, 0.36),
sunset_color: Color::new(0.45, 0.55, 0.85), intensity: 1.2,
falloff: 2.4,
ozone: 0.0,
..Self::default()
}
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn sunset_color(mut self, color: Color) -> Self {
self.sunset_color = color;
self
}
pub fn height(mut self, height: f32) -> Self {
self.height = height.clamp(1e-4, 1.0);
self
}
pub fn intensity(mut self, intensity: f32) -> Self {
self.intensity = intensity.max(0.0);
self
}
pub fn falloff(mut self, falloff: f32) -> Self {
self.falloff = falloff.clamp(0.1, 32.0);
self
}
pub fn material(&self, radius: f32) -> AtmosphereMaterial {
AtmosphereMaterial::new(radius, radius * (1.0 + self.height))
.color(self.color)
.sunset_color(self.sunset_color)
.intensity(self.intensity)
.falloff(self.falloff)
.ozone(self.ozone)
.aurora(self.aurora, self.aurora_color, self.aurora_colatitude)
}
}
#[derive(Debug, Clone)]
pub struct Planet {
pub radius: f32,
pub position: Vector3,
pub maps: PlanetMaps,
pub segments: (usize, usize),
pub cloud_height: f32,
pub cloud_opacity: f32,
pub cloud_scatter: f32,
pub sun_angular_radius: f32,
pub atmosphere: Option<Atmosphere>,
pub night_intensity: f32,
pub color: Color,
pub roughness: f32,
pub displacement: f32,
pub displacement_bias: f32,
pub metalness: f32,
pub tilt: f32,
pub spin: f32,
}
impl Default for Planet {
fn default() -> Self {
Self::new(1.0)
}
}
impl Planet {
pub fn new(radius: f32) -> Self {
Self {
radius: radius.max(1e-4),
position: Vector3::ZERO,
maps: PlanetMaps::new(),
segments: (192, 96),
cloud_height: 0.012,
cloud_opacity: 0.96,
cloud_scatter: 0.35,
sun_angular_radius: 0.00465,
atmosphere: None,
night_intensity: 2.3,
color: Color::WHITE,
roughness: 1.0,
displacement: 0.0,
displacement_bias: 0.0,
metalness: 0.0,
tilt: 0.0,
spin: 0.0,
}
}
pub fn earth() -> Self {
Self {
atmosphere: Some(Atmosphere::earth()),
tilt: 23.44f32.to_radians(),
..Self::new(1.0)
}
}
pub fn moon() -> Self {
Self {
radius: 0.2727,
roughness: 0.95,
night_intensity: 0.0,
segments: (384, 192),
atmosphere: None,
..Self::new(0.2727)
}
}
pub fn maps(mut self, maps: PlanetMaps) -> Self {
self.maps = maps;
self
}
pub fn position(mut self, position: Vector3) -> Self {
self.position = position;
self
}
pub fn segments(mut self, longitude: usize, latitude: usize) -> Self {
self.segments = (longitude.max(8), latitude.max(4));
self
}
pub fn atmosphere(mut self, atmosphere: Option<Atmosphere>) -> Self {
self.atmosphere = atmosphere;
self
}
pub fn tilt_degrees(mut self, degrees: f32) -> Self {
self.tilt = degrees.to_radians();
self
}
pub fn spin_degrees(mut self, degrees: f32) -> Self {
self.spin = degrees.to_radians();
self
}
pub fn night_intensity(mut self, intensity: f32) -> Self {
self.night_intensity = intensity.max(0.0);
self
}
pub fn color(mut self, color: Color) -> Self {
self.color = color;
self
}
pub fn roughness(mut self, roughness: f32) -> Self {
self.roughness = roughness.clamp(0.0, 1.0);
self
}
pub fn displacement(mut self, world_units: f32) -> Self {
self.displacement = world_units.max(0.0);
self.displacement_bias = 0.0;
self
}
pub fn displacement_centered(mut self, world_units: f32) -> Self {
self.displacement = world_units.max(0.0);
self.displacement_bias = -self.displacement * 0.5;
self
}
pub fn displacement_bias(mut self, bias: f32) -> Self {
self.displacement_bias = bias;
self
}
fn orientation(&self) -> Quaternion {
Quaternion::from_euler_xyz(self.tilt, self.spin, 0.0)
}
fn surface_material(&self) -> StandardMaterial {
let mut m = StandardMaterial::new(self.color);
m.map = self.maps.albedo.clone();
m.normal_map = self.maps.normal.clone();
m.roughness_map = self.maps.roughness.clone();
m.roughness = self.roughness;
m.metalness = self.metalness;
if self.displacement > 0.0 {
m.displacement_map = self.maps.displacement.clone();
m.displacement_scale = self.displacement;
m.displacement_bias = self.displacement_bias;
}
if let Some(night) = self.maps.night.clone() {
m.emissive_map = Some(night);
m.emissive = Color::WHITE;
m.emissive_intensity = self.night_intensity;
m.emissive_night_side = 1.0;
}
m
}
pub fn add_to(&self, scene: &mut Scene) -> PlanetHandles {
let orientation = self.orientation();
let mut body = Object3D::mesh(Mesh::new(
SphereGeometry::new(self.radius, self.segments.0, self.segments.1),
Material::Standard(self.surface_material()),
));
body.position = self.position;
body.quaternion = orientation;
let surface = scene.add(body);
let clouds = self.maps.clouds.clone().map(|map| {
let mut m = StandardMaterial::new(Color::WHITE);
m.map = Some(map);
m.roughness = 0.95;
m.metalness = 0.0;
m.cloud_scatter = self.cloud_scatter;
m.cloud_anisotropy = 0.8;
m.sun_angular_radius = self.sun_angular_radius;
m.opacity = self.cloud_opacity.min(0.999);
let mut shell = Object3D::mesh(Mesh::new(
SphereGeometry::new(
self.radius * (1.0 + self.cloud_height),
self.segments.0 * 3 / 4,
self.segments.1 * 3 / 4,
),
Material::Standard(m),
));
shell.name = "clouds".into();
shell.position = self.position;
shell.quaternion = orientation;
scene.add(shell)
});
let atmosphere = self.atmosphere.map(|air| {
let mut shell = Object3D::mesh(Mesh::new(
SphereGeometry::new(self.radius * (1.0 + air.height), 128, 64),
Material::Atmosphere(air.material(self.radius)),
));
shell.name = "atmosphere".into();
shell.position = self.position;
scene.add(shell)
});
PlanetHandles {
surface,
clouds,
atmosphere,
}
}
}
#[derive(Clone)]
pub struct Starfield {
pub texture: Arc<Texture>,
pub radius: f32,
pub intensity: f32,
pub faces: Option<Vec<Arc<Texture>>>,
}
impl std::fmt::Debug for Starfield {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Starfield")
.field(
"texture",
&format!("{}x{}", self.texture.width, self.texture.height),
)
.field("radius", &self.radius)
.finish()
}
}
pub fn earthshine(
sun_direction: Vector3,
reflector: Vector3,
lit_body: Vector3,
reflector_radius: f32,
albedo: f32,
) -> (Vector3, f32) {
let to_sun = sun_direction.normalize();
let offset = lit_body - reflector;
let distance = offset.length().max(1e-6);
let to_body = offset * (1.0 / distance);
let phase = to_sun.dot(to_body).clamp(-1.0, 1.0);
let illuminated = 0.5 * (1.0 + phase);
let solid_angle = (reflector_radius / distance).powi(2);
let intensity = albedo.max(0.0) * illuminated * solid_angle;
(to_body, intensity)
}
pub fn tidal_lock_yaw(position: Vector3) -> f32 {
std::f32::consts::PI - position.z.atan2(position.x)
}
impl Starfield {
pub fn new(texture: Texture) -> Self {
Self {
texture: Arc::new(texture),
radius: 400.0,
intensity: 1.0,
faces: None,
}
}
pub fn procedural(width: u32) -> Self {
let count = (width as u64 * width as u64 / 320).clamp(500, 200_000) as u32;
Self::new(generate_starfield(width, count))
}
pub fn radius(mut self, radius: f32) -> Self {
self.radius = radius.max(1.0);
self
}
pub fn intensity(mut self, intensity: f32) -> Self {
self.intensity = intensity.max(0.0);
self
}
pub fn faceted(mut self, face_size: u32) -> Self {
let n = if face_size == 0 {
(self.texture.width / 4).clamp(64, 4096)
} else {
face_size
};
self.faces = Some(
equirect_to_cube_faces(&self.texture, n)
.into_iter()
.map(Arc::new)
.collect(),
);
self
}
pub fn add_to(&self, scene: &mut Scene) -> ObjectId {
if let Some(faces) = &self.faces
&& faces.len() == 6
{
return self.add_cube(scene, faces);
}
let mut m = BasicMaterial::new(Color::new(self.intensity, self.intensity, self.intensity));
m.map = Some(self.texture.clone());
m.side = 1;
let mut sky = Object3D::mesh(Mesh::new(
SphereGeometry::new(self.radius, 64, 32),
Material::Basic(m),
));
sky.name = "starfield".into();
scene.add(sky)
}
fn add_cube(&self, scene: &mut Scene, faces: &[Arc<Texture>]) -> ObjectId {
let r = self.radius;
let mut group = Object3D::group();
group.name = "starfield".into();
let root = scene.add(group);
for (face, (f, right, up)) in faces.iter().zip(CUBE_FACES.iter()) {
let corner = |x: f32, y: f32| {
[
(f[0] + x * right[0] + y * up[0]) * r,
(f[1] + x * right[1] + y * up[1]) * r,
(f[2] + x * right[2] + y * up[2]) * r,
]
};
let mut geom = crate::core::BufferGeometry::new();
let mut positions = Vec::with_capacity(12);
for (x, y) in [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] {
positions.extend_from_slice(&corner(x, y));
}
geom.set_attribute("position", crate::core::BufferAttribute::new(positions, 3));
geom.set_attribute(
"normal",
crate::core::BufferAttribute::new([-f[0], -f[1], -f[2]].repeat(4).to_vec(), 3),
);
geom.set_attribute(
"uv",
crate::core::BufferAttribute::new(vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0], 2),
);
geom.set_index(vec![0, 1, 2, 2, 1, 3]);
let mut m =
BasicMaterial::new(Color::new(self.intensity, self.intensity, self.intensity));
m.map = Some(face.clone());
m.side = 2;
let mut quad = Object3D::mesh(Mesh::new(geom, Material::Basic(m)));
quad.name = "starfield face".into();
scene.add_to(root, quad);
}
root
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn earth_defaults_are_earth_like() {
let earth = Planet::earth();
assert_eq!(earth.radius, 1.0);
assert!((earth.tilt.to_degrees() - 23.44).abs() < 1e-3);
let air = earth.atmosphere.expect("earth has air");
assert!(air.height > 0.0 && air.height < 0.1, "a thin shell");
assert_eq!(earth.metalness, 0.0);
}
#[test]
fn displacement_centres_only_when_asked() {
let up = Planet::earth().displacement(0.05);
assert_eq!(up.displacement, 0.05);
assert_eq!(
up.displacement_bias, 0.0,
"a sea-level map must not be shifted"
);
let mid = Planet::moon().displacement_centered(0.02);
assert_eq!(mid.displacement, 0.02);
assert!(
(mid.displacement_bias + 0.01).abs() < 1e-6,
"a centred map should sit half below the surface: {}",
mid.displacement_bias
);
}
#[test]
fn the_moon_is_airless_and_dark_at_night() {
let moon = Planet::moon();
assert!(moon.atmosphere.is_none());
assert_eq!(moon.night_intensity, 0.0, "no cities on the Moon");
assert!(moon.radius < Planet::earth().radius);
}
#[test]
fn adding_a_planet_creates_the_shells_it_has_maps_for() {
let mut scene = Scene::new();
let bare = Planet::earth().atmosphere(None).add_to(&mut scene);
assert!(bare.clouds.is_none(), "no cloud map, no cloud shell");
assert!(bare.atmosphere.is_none());
let full = Planet::earth()
.maps(generate_earth_maps(64))
.add_to(&mut scene);
assert!(full.clouds.is_some());
assert!(full.atmosphere.is_some());
assert!(scene.get(full.surface).is_some());
assert!(scene.get(full.clouds.unwrap()).is_some());
assert!(scene.get(full.atmosphere.unwrap()).is_some());
}
#[test]
fn the_shells_are_stacked_in_the_right_order() {
let earth = Planet::earth();
let air = earth.atmosphere.unwrap();
let cloud_r = earth.radius * (1.0 + earth.cloud_height);
let air_r = earth.radius * (1.0 + air.height);
assert!(
earth.radius < cloud_r && cloud_r < air_r,
"surface {} < clouds {cloud_r} < air {air_r}",
earth.radius
);
}
#[test]
fn the_cloud_shell_stays_on_the_alpha_pipeline() {
let mut scene = Scene::new();
let handles = Planet::earth()
.maps(generate_earth_maps(64))
.add_to(&mut scene);
let clouds = scene.get(handles.clouds.unwrap()).unwrap();
if let crate::ObjectKind::Mesh(mesh) = &clouds.kind {
assert!(mesh.material.transparent(), "clouds must be transparent");
assert!(mesh.material.opacity() < 1.0);
} else {
panic!("expected a mesh");
}
}
#[test]
fn the_atmosphere_material_spans_the_two_radii() {
let air = Atmosphere::earth().height(0.05);
let m = air.material(2.0);
assert_eq!(m.planet_radius, 2.0);
assert!((m.atmosphere_radius - 2.1).abs() < 1e-5);
assert!(m.thickness() > 0.0);
}
#[test]
fn a_starfield_is_unlit_and_inside_out() {
let mut scene = Scene::new();
let sky = Starfield::procedural(128).radius(250.0);
let id = sky.add_to(&mut scene);
let obj = scene.get(id).unwrap();
if let crate::ObjectKind::Mesh(mesh) = &obj.kind {
assert!(matches!(&*mesh.material, Material::Basic(_)));
assert_eq!(mesh.material.side(), 1);
} else {
panic!("expected a mesh");
}
}
#[test]
fn maps_are_optional_and_independent() {
let maps = PlanetMaps::new().albedo(generate_starfield(32, 10));
assert!(maps.albedo.is_some());
assert!(maps.clouds.is_none());
assert!(!maps.is_empty());
assert!(PlanetMaps::new().is_empty());
let mut scene = Scene::new();
let handles = Planet::new(1.0).add_to(&mut scene);
assert!(scene.get(handles.surface).is_some());
}
#[test]
fn night_map_is_confined_to_the_night_side() {
use crate::textures::{Texture, TextureFormat};
use std::sync::Arc;
let night = Arc::new(Texture::new(
1,
1,
TextureFormat::Rgba8UnormSrgb,
vec![255, 255, 255, 255],
));
let maps = PlanetMaps {
night: Some(night),
..Default::default()
};
let m = Planet::new(1.0).maps(maps).surface_material();
assert!(m.emissive_map.is_some(), "the night map should be bound");
assert_eq!(
m.emissive_night_side, 1.0,
"a planet's night map must be gated to the unlit hemisphere"
);
assert_eq!(
StandardMaterial::new(Color::WHITE).emissive_night_side,
0.0,
"the gate must be off unless a material asks for it"
);
assert_eq!(Planet::new(1.0).surface_material().emissive_night_side, 0.0);
}
}