use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::textures::{Texture, TextureFormat, TextureWrap};
use crate::utils::png::decode_png;
use super::{generate_earth_maps, generate_starfield, HeightField, PlanetMaps};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MapSources {
pub loaded: Vec<String>,
pub generated: Vec<String>,
pub failed: Vec<(String, String)>,
}
impl MapSources {
pub fn any_loaded(&self) -> bool {
!self.loaded.is_empty()
}
}
#[derive(Debug, Clone)]
pub struct EarthTextures {
dir: PathBuf,
pub day: String,
pub night: String,
pub clouds: String,
pub elevation: String,
pub ice_cap: String,
pub ice_cap_band: (f32, f32),
pub fallback: bool,
pub fallback_width: u32,
pub relief: f32,
pub sea_level: f32,
pub sea_roughness: f32,
pub land_roughness: f32,
pub ice_roughness: f32,
pub moon_albedo: f32,
}
impl EarthTextures {
pub fn from_dir(dir: impl AsRef<Path>) -> Self {
Self {
dir: dir.as_ref().to_path_buf(),
day: "day.png".into(),
night: "night.png".into(),
clouds: "clouds.png".into(),
elevation: "elevation.4096.png".into(),
ice_cap: "ice_cap.png".into(),
ice_cap_band: (72.0, 82.0),
fallback: true,
fallback_width: 1024,
relief: 6.0,
sea_level: 0.25,
sea_roughness: 0.45,
land_roughness: 0.85,
ice_roughness: 0.35,
moon_albedo: 0.55,
}
}
pub fn strict(mut self) -> Self {
self.fallback = false;
self
}
pub fn fallback_width(mut self, width: u32) -> Self {
self.fallback_width = width;
self
}
pub fn relief(mut self, relief: f32) -> Self {
self.relief = relief.max(0.0);
self
}
pub fn sea_level(mut self, sea_level: f32) -> Self {
self.sea_level = sea_level.clamp(0.0, 1.0);
self
}
pub fn roughness(mut self, water: f32, land: f32) -> Self {
self.sea_roughness = water.clamp(0.0, 1.0);
self.land_roughness = land.clamp(0.0, 1.0);
self
}
pub fn sea_state(mut self, wind_m_s: f32) -> Self {
let mss = 0.003 + 0.00512 * wind_m_s.max(0.0);
self.sea_roughness = mss.sqrt().sqrt().clamp(0.0, 1.0);
self
}
pub fn load(&self) -> PlanetMaps {
self.load_reporting().0
}
pub fn load_reporting(&self) -> (PlanetMaps, MapSources) {
let mut src = MapSources::default();
let mut maps = PlanetMaps::new();
maps.albedo = self
.read_raw(&self.day, TextureFormat::Rgba8UnormSrgb, &mut src)
.map(|mut day| {
if !self.ice_cap.is_empty()
&& let Some(cap) =
self.read_raw(&self.ice_cap, TextureFormat::Rgba8UnormSrgb, &mut src)
{
let (from, to) = self.ice_cap_band;
super::blend_polar_cap(&mut day, &cap, from, to);
}
super::ease_poles(&mut day);
Arc::new(day)
});
maps.night = self
.read(&self.night, TextureFormat::Rgba8UnormSrgb, &mut src)
.map(Arc::new);
maps.clouds = self
.read(&self.clouds, TextureFormat::Rgba8UnormSrgb, &mut src)
.map(|grey| Arc::new(clouds_from_grey(&grey)));
if let Some(elev) = self.read(&self.elevation, TextureFormat::Rgba8Unorm, &mut src) {
let hf = HeightField::from_texture(&elev);
maps.normal = Some(Arc::new(hf.to_normal_map(self.relief)));
maps.roughness = Some(Arc::new(match maps.albedo.as_ref() {
Some(day) => hf.to_roughness_map_with_ice(
day,
self.sea_level,
self.sea_roughness,
self.land_roughness,
self.ice_roughness,
),
None => {
hf.to_roughness_map(self.sea_level, self.sea_roughness, self.land_roughness)
}
}));
maps.displacement = Some(Arc::new(hf.to_height_map(self.sea_level)));
}
if self.fallback && !maps.is_complete() {
let fallback_maps = generate_earth_maps(self.fallback_width);
let mut fill = |slot: &mut Option<Arc<Texture>>, from: Option<Arc<Texture>>, name| {
if slot.is_none() {
*slot = from;
src.generated.push(String::from(name));
}
};
fill(&mut maps.albedo, fallback_maps.albedo, "albedo");
fill(&mut maps.normal, fallback_maps.normal, "normal");
fill(&mut maps.roughness, fallback_maps.roughness, "roughness");
fill(&mut maps.night, fallback_maps.night, "night");
fill(&mut maps.clouds, fallback_maps.clouds, "clouds");
fill(
&mut maps.displacement,
fallback_maps.displacement,
"displacement",
);
}
(maps, src)
}
pub fn load_moon(&self) -> Option<PlanetMaps> {
self.load_moon_reporting().0
}
pub fn load_moon_reporting(&self) -> (Option<PlanetMaps>, MapSources) {
let mut src = MapSources::default();
let mut maps = PlanetMaps::new();
for name in ["sky/moon_color.png", "sky/moon_color_4k.png"] {
if let Some(t) = self.read(name, TextureFormat::Rgba8UnormSrgb, &mut src) {
maps.albedo = Some(Arc::new(scale_albedo(&t, self.moon_albedo)));
break;
}
}
if let Some(h) = self.read("sky/moon_height.png", TextureFormat::Rgba8Unorm, &mut src) {
let hf = HeightField::from_texture(&h);
maps.normal = Some(Arc::new(hf.to_normal_map(14.0 * hf.width as f32 / 5760.0)));
maps.displacement = Some(Arc::new(hf.to_height_map_normalized()));
}
((!maps.is_empty()).then_some(maps), src)
}
pub fn load_starfield(&self) -> Texture {
self.load_starfield_reporting().0
}
pub fn load_starfield_reporting(&self) -> (Texture, MapSources) {
let mut src = MapSources::default();
if let Some(t) = self.read(
"sky/starmap_4k.png",
TextureFormat::Rgba8UnormSrgb,
&mut src,
) {
return (t, src);
}
let exr = ["sky/starmap_8k.exr", "sky/starmap_4k.exr"]
.iter()
.map(|n| self.dir.join(n))
.find(|p| p.is_file())
.unwrap_or_else(|| self.dir.join("sky/starmap_4k.exr"));
if exr.is_file() {
match std::fs::read(&exr)
.map_err(|e| e.to_string())
.and_then(|b| {
crate::loaders::ExrLoader::parse_hdr(&b).map_err(|e| format!("{e:?}"))
}) {
Ok(mut t) => {
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::ClampToEdge;
src.loaded.push(
exr.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
);
return (t, src);
}
Err(e) => src.failed.push((exr.display().to_string(), e)),
}
}
src.generated.push("starfield".into());
let w = self.fallback_width;
(
generate_starfield(w, (w * w / 320).clamp(500, 200_000)),
src,
)
}
fn read(&self, name: &str, format: TextureFormat, src: &mut MapSources) -> Option<Texture> {
self.read_map(name, format, src, true)
}
fn read_raw(&self, name: &str, format: TextureFormat, src: &mut MapSources) -> Option<Texture> {
self.read_map(name, format, src, false)
}
fn read_map(
&self,
name: &str,
format: TextureFormat,
src: &mut MapSources,
ease: bool,
) -> Option<Texture> {
let path = self.dir.join(name);
if !path.is_file() {
return None;
}
let bytes = match std::fs::read(&path) {
Ok(b) => b,
Err(e) => {
src.failed.push((name.into(), e.to_string()));
return None;
}
};
match decode_png(&bytes) {
Ok(img) => {
src.loaded.push(name.into());
let mut t = Texture::new(img.width, img.height, format, img.rgba);
if ease {
super::ease_poles(&mut t);
}
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::ClampToEdge;
Some(t)
}
Err(e) => {
let hint = if e == "not a PNG" {
"not a PNG — rerun the fetch script with --png".to_string()
} else {
e
};
src.failed.push((name.into(), hint));
None
}
}
}
}
pub fn scale_albedo(src: &Texture, factor: f32) -> Texture {
let to_linear = |b: u8| {
let v = b as f32 / 255.0;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
let to_srgb = |v: f32| {
let v = v.clamp(0.0, 1.0);
let e = if v <= 0.0031308 {
v * 12.92
} else {
1.055 * v.powf(1.0 / 2.4) - 0.055
};
(e * 255.0).round() as u8
};
let mut data = src.data.as_ref().clone();
for px in data.as_chunks_mut::<4>().0 {
for c in px.iter_mut().take(3) {
*c = to_srgb(to_linear(*c) * factor);
}
}
let mut t = Texture::new(src.width, src.height, src.format, data);
t.wrap_s = src.wrap_s;
t.wrap_t = src.wrap_t;
t
}
pub fn clouds_from_grey(grey: &Texture) -> Texture {
let bpp = grey.bytes_per_pixel().max(1);
let texels = (grey.width as usize) * (grey.height as usize);
let mut data = vec![255u8; texels * 4];
for i in 0..texels {
let o = i * bpp;
let l = grey.data.get(o).copied().unwrap_or(0) as f32 / 255.0;
let a = ((l - 0.06) / 0.72).clamp(0.0, 1.0);
data[i * 4 + 3] = (a * 255.0) as u8;
}
let mut t = Texture::new(grey.width, grey.height, TextureFormat::Rgba8UnormSrgb, data);
t.wrap_s = TextureWrap::Repeat;
t.wrap_t = TextureWrap::ClampToEdge;
t
}
#[cfg(test)]
mod tests {
use super::*;
fn grey(width: u32, height: u32, level: u8) -> Texture {
let data = vec![level; (width * height * 4) as usize];
Texture::new(width, height, TextureFormat::Rgba8Unorm, data)
}
#[test]
fn sea_state_follows_cox_munk() {
let default_r = EarthTextures::from_dir(".").sea_roughness;
let mean_wind = EarthTextures::from_dir(".").sea_state(7.0).sea_roughness;
assert!(
(default_r - mean_wind).abs() < 0.02,
"the default {default_r} should be roughly the 7 m/s value {mean_wind}"
);
let mut last = 0.0;
for w in [0.0, 2.0, 7.0, 12.0, 20.0] {
let r = EarthTextures::from_dir(".").sea_state(w).sea_roughness;
assert!(
r > last,
"roughness should rise with wind: {w} m/s gave {r}"
);
last = r;
}
let calm = EarthTextures::from_dir(".").sea_state(0.0).sea_roughness;
assert!((calm - 0.2340).abs() < 0.001, "calm sea roughness {calm}");
let windy = EarthTextures::from_dir(".").sea_state(12.0).sea_roughness;
let mss = (windy * windy) * (windy * windy);
assert!((mss - (0.003 + 0.00512 * 12.0)).abs() < 1e-4);
}
#[test]
fn grey_clouds_become_white_with_alpha_cover() {
let clear = clouds_from_grey(&grey(4, 2, 0));
let thick = clouds_from_grey(&grey(4, 2, 255));
assert!(clear
.data
.as_chunks::<4>()
.0
.iter()
.all(|p| p[..3] == [255, 255, 255]));
assert!(thick
.data
.as_chunks::<4>()
.0
.iter()
.all(|p| p[..3] == [255, 255, 255]));
assert_eq!(clear.data[3], 0);
assert_eq!(thick.data[3], 255);
assert_eq!(thick.wrap_s, TextureWrap::Repeat);
assert_eq!(thick.wrap_t, TextureWrap::ClampToEdge);
}
#[test]
fn a_missing_directory_falls_back_to_a_whole_planet() {
let (maps, src) = EarthTextures::from_dir("/nonexistent/nasa")
.fallback_width(64)
.load_reporting();
assert!(maps.is_complete(), "the fallback has to cover every slot");
assert!(!src.any_loaded());
assert_eq!(src.generated.len(), 6);
assert!(maps.displacement.is_some(), "a height map is generated too");
assert!(src.failed.is_empty(), "absent is not the same as broken");
}
#[test]
fn strict_mode_leaves_the_gaps_open() {
let (maps, src) = EarthTextures::from_dir("/nonexistent/nasa")
.strict()
.load_reporting();
assert!(maps.is_empty());
assert!(src.generated.is_empty());
}
#[test]
fn a_file_that_is_not_a_png_is_reported_not_ignored() {
let dir = std::env::temp_dir().join("threers-planet-nasa-test");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("day.png"), b"\xff\xd8\xff\xe0 not really a png").unwrap();
let (_, src) = EarthTextures::from_dir(&dir)
.fallback_width(64)
.load_reporting();
let (name, why) = src.failed.first().expect("the bad file is reported");
assert_eq!(name, "day.png");
assert!(
why.contains("--png"),
"the message should say how to fix it: {why}"
);
assert!(src.generated.contains(&"albedo".to_string()));
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn real_files_are_loaded_and_derived_from() {
let dir = std::env::temp_dir().join("threers-planet-nasa-real");
std::fs::create_dir_all(&dir).unwrap();
let (w, h) = (16u32, 8u32);
let mut rgba = vec![255u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let v = if x < w / 2 { 20 } else { 200 };
let o = ((y * w + x) * 4) as usize;
rgba[o..o + 3].copy_from_slice(&[v, v, v]);
}
}
let png = crate::utils::png::encode_png(w, h, &rgba);
std::fs::write(dir.join("elevation.4096.png"), png).unwrap();
let (maps, src) = EarthTextures::from_dir(&dir)
.fallback_width(64)
.load_reporting();
assert_eq!(src.loaded, vec!["elevation.4096.png".to_string()]);
let rough = maps.roughness.as_ref().unwrap();
assert_eq!((rough.width, rough.height), (w, h));
assert_eq!(maps.normal.as_ref().unwrap().width, w);
let at = |x: u32| rough.data[(((h / 2) * w + x) * 4) as usize];
let cfg = EarthTextures::from_dir(&dir);
let expect = |r: f32| (r * 255.0) as u8;
assert_eq!(at(2), expect(cfg.sea_roughness), "ocean roughness");
assert_eq!(at(13), expect(cfg.land_roughness), "land roughness");
assert!(at(2) < at(13), "water has to be smoother than land");
let custom = EarthTextures::from_dir(&dir)
.fallback_width(64)
.roughness(0.05, 1.0)
.load();
let cr = custom.roughness.as_ref().unwrap();
assert_eq!(cr.data[(((h / 2) * w + 2) * 4) as usize], expect(0.05));
assert_eq!(maps.albedo.as_ref().unwrap().width, 64);
assert!(!src.generated.contains(&"normal".to_string()));
std::fs::remove_dir_all(&dir).ok();
}
}