From 9d47beb46b172c113d0685cc7b461caddd021411 Mon Sep 17 00:00:00 2001 From: Theo Gastinel Date: Fri, 30 Oct 2026 00:18:35 +0100 Subject: [PATCH] relief: rt-core, rt-tiles (.rtt mmap, hauteur_colonne, remplir_colonne), rt-prep (GeoTIFF -> .rtt) Co-Authored-By: Claude Opus 5.5 --- relief/.gitignore | 2 + relief/Cargo.lock | 117 +++++++++++++ relief/Cargo.toml | 3 + relief/rt-core/Cargo.toml | 5 + relief/rt-core/src/lib.rs | 97 +++++++++++ relief/rt-prep/Cargo.toml | 10 ++ relief/rt-prep/src/lib.rs | 161 ++++++++++++++++++ relief/rt-prep/src/main.rs | 60 +++++++ relief/rt-prep/tests/lans.rs | 20 +++ relief/rt-tiles/Cargo.toml | 10 ++ relief/rt-tiles/src/lib.rs | 309 +++++++++++++++++++++++++++++++++++ 11 files changed, 794 insertions(+) create mode 100644 relief/.gitignore create mode 100644 relief/Cargo.lock create mode 100644 relief/Cargo.toml create mode 100644 relief/rt-core/Cargo.toml create mode 100644 relief/rt-core/src/lib.rs create mode 100644 relief/rt-prep/Cargo.toml create mode 100644 relief/rt-prep/src/lib.rs create mode 100644 relief/rt-prep/src/main.rs create mode 100644 relief/rt-prep/tests/lans.rs create mode 100644 relief/rt-tiles/Cargo.toml create mode 100644 relief/rt-tiles/src/lib.rs diff --git a/relief/.gitignore b/relief/.gitignore new file mode 100644 index 0000000..079be03 --- /dev/null +++ b/relief/.gitignore @@ -0,0 +1,2 @@ +target/ +*.rtt diff --git a/relief/Cargo.lock b/relief/Cargo.lock new file mode 100644 index 0000000..34d6367 --- /dev/null +++ b/relief/Cargo.lock @@ -0,0 +1,117 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "jpeg-decoder" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5d4a7da358eff58addd2877a45865158f0d78c911d43a5784ceb7bbf52833b0" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "memmap2" +version = "0.9.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1219ed1b7f229ee7104d281dd01d6802fe28bb6e95d292942c4daacdeb798c0" +dependencies = [ + "libc", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "rt-core" +version = "0.1.0" + +[[package]] +name = "rt-prep" +version = "0.1.0" +dependencies = [ + "rt-core", + "rt-tiles", + "tiff", +] + +[[package]] +name = "rt-tiles" +version = "0.1.0" +dependencies = [ + "crc32fast", + "memmap2", + "rt-core", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "tiff" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba1310fcea54c6a9a4fd1aad794ecc02c31682f6bfbecdf460bf19533eed1e3e" +dependencies = [ + "flate2", + "jpeg-decoder", + "weezl", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/relief/Cargo.toml b/relief/Cargo.toml new file mode 100644 index 0000000..2ff1102 --- /dev/null +++ b/relief/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +resolver = "2" +members = ["rt-core", "rt-tiles", "rt-prep"] diff --git a/relief/rt-core/Cargo.toml b/relief/rt-core/Cargo.toml new file mode 100644 index 0000000..a50db61 --- /dev/null +++ b/relief/rt-core/Cargo.toml @@ -0,0 +1,5 @@ +[package] +name = "rt-core" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" diff --git a/relief/rt-core/src/lib.rs b/relief/rt-core/src/lib.rs new file mode 100644 index 0000000..e52e659 --- /dev/null +++ b/relief/rt-core/src/lib.rs @@ -0,0 +1,97 @@ +//! Types de base sans dépendance : repère Lambert 93 -> bloc, tuiles, hauteur du monde. + +/// Paramètres de la dimension haute (rapport 09). +/// Contrainte vanilla : min_y et height multiples de 16, height ∈ [16, 4064], +/// min_y ∈ [-2032, 2031], min_y + height ≤ 2032. +pub const DIM_MIN_Y: i32 = -1024; +pub const DIM_HEIGHT: i32 = 2400; + +pub const fn dimension_valide(min_y: i32, height: i32) -> bool { + min_y % 16 == 0 + && height % 16 == 0 + && height >= 16 + && height <= 4064 + && min_y >= -2032 + && min_y + height <= 2032 +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WorldOrigin { + pub l93_x: f64, + pub l93_y: f64, + pub alt_base_m: i32, +} + +impl WorldOrigin { + /// Coin nord-ouest du MNT de Lans (géoréférencement du GeoTIFF : 903000, 6451500). + pub const LANS: WorldOrigin = WorldOrigin { l93_x: 903_000.0, l93_y: 6_451_500.0, alt_base_m: 1000 }; + + /// Le nord Lambert (+Y) correspond au nord Minecraft (−Z). + pub fn l93_to_block(&self, x: f64, y: f64) -> (i32, i32) { + ((x - self.l93_x).floor() as i32, (self.l93_y - y).floor() as i32) + } + /// Centre du bloc. + pub fn block_to_l93(&self, bx: i32, bz: i32) -> (f64, f64) { + (self.l93_x + bx as f64 + 0.5, self.l93_y - bz as f64 - 0.5) + } + pub fn alt_to_y(&self, alt_m: f32) -> i32 { + alt_m.floor() as i32 - self.alt_base_m + } + /// Altitude (m) correspondant à ground_dm = 0. + pub fn alt_zero_dm(&self) -> i32 { + self.alt_base_m - 1000 + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub struct TileId { + pub tx: i32, + pub tz: i32, +} + +impl TileId { + pub const SIZE: i32 = 512; + pub fn of_block(bx: i32, bz: i32) -> Self { + TileId { tx: bx.div_euclid(Self::SIZE), tz: bz.div_euclid(Self::SIZE) } + } + pub fn of_chunk(cx: i32, cz: i32) -> Self { + TileId { tx: cx.div_euclid(32), tz: cz.div_euclid(32) } + } + pub fn file_name(&self) -> String { + format!("{}_{}.rtt", self.tx, self.tz) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dimension_retenue_valide() { + assert!(dimension_valide(DIM_MIN_Y, DIM_HEIGHT)); + assert!(!dimension_valide(0, 2432)); // 2432 > 2032 + assert!(!dimension_valide(-2032, 4080)); + assert!(dimension_valide(-2032, 4064)); + assert!(!dimension_valide(-1000, 2400)); // pas multiple de 16 + } + + #[test] + fn aller_retour_l93() { + let o = WorldOrigin::LANS; + let (bx, bz) = o.l93_to_block(903_430.2, 6_450_969.7); + assert_eq!((bx, bz), (430, 530)); + let (x, y) = o.block_to_l93(bx, bz); + assert!((x - 903_430.2).abs() <= 0.5 && (y - 6_450_969.7).abs() <= 0.5); + // nord = -z + assert!(o.l93_to_block(903_000.0, 6_451_600.0).1 < 0); + } + + #[test] + fn tuiles() { + assert_eq!(TileId::of_block(-1, 0), TileId { tx: -1, tz: 0 }); + assert_eq!(TileId::of_block(511, 512), TileId { tx: 0, tz: 1 }); + assert_eq!(TileId::of_chunk(-1, 31), TileId { tx: -1, tz: 0 }); + assert_eq!(TileId { tx: -2, tz: 3 }.file_name(), "-2_3.rtt"); + assert_eq!(WorldOrigin::LANS.alt_to_y(1020.4), 20); + } +} diff --git a/relief/rt-prep/Cargo.toml b/relief/rt-prep/Cargo.toml new file mode 100644 index 0000000..895da2d --- /dev/null +++ b/relief/rt-prep/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "rt-prep" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" + +[dependencies] +rt-core = { path = "../rt-core" } +rt-tiles = { path = "../rt-tiles" } +tiff = "0.9" diff --git a/relief/rt-prep/src/lib.rs b/relief/rt-prep/src/lib.rs new file mode 100644 index 0000000..8830feb --- /dev/null +++ b/relief/rt-prep/src/lib.rs @@ -0,0 +1,161 @@ +//! Conversion d'un MNT GeoTIFF (Lambert 93, float32, pas de 1 m) en tuiles `.rtt`. + +use rt_core::{TileId, WorldOrigin}; +use rt_tiles::{alt_to_dm, ColumnSample, TileWriter, BORDER, N, SIDE}; +use std::path::Path; + +/// Raster en mémoire, ligne 0 = bord nord (vérifié via le géoréférencement). +pub struct Mnt { + pub largeur: usize, + pub hauteur: usize, + /// Coin nord-ouest du pixel (0,0), en Lambert 93. + pub x0: f64, + pub y0: f64, + pub pas: f64, + pub nodata: Option, + pub valeurs: Vec, +} + +impl Mnt { + pub fn lire_geotiff(path: &Path) -> Result { + use tiff::decoder::{Decoder, DecodingResult}; + use tiff::tags::Tag; + let f = std::fs::File::open(path).map_err(|e| e.to_string())?; + let mut d = Decoder::new(std::io::BufReader::new(f)).map_err(|e| e.to_string())?; + let (w, h) = d.dimensions().map_err(|e| e.to_string())?; + // ModelPixelScaleTag (33550) et ModelTiepointTag (33922). + let scale = d.get_tag_f64_vec(Tag::from_u16_exhaustive(33550)).map_err(|e| format!("PixelScale: {e}"))?; + let tie = d.get_tag_f64_vec(Tag::from_u16_exhaustive(33922)).map_err(|e| format!("Tiepoint: {e}"))?; + let nodata = d + .get_tag_ascii_string(Tag::from_u16_exhaustive(42113)) + .ok() + .and_then(|s| s.trim_matches(char::from(0)).trim().parse::().ok()); + if scale.len() < 2 || tie.len() < 6 { + return Err("géoréférencement incomplet".into()); + } + if (scale[0] - scale[1]).abs() > 1e-9 || scale[0] <= 0.0 { + return Err(format!("pas non carré : {scale:?}")); + } + // Tiepoint (I,J,K,X,Y,Z) : pixel (I,J) -> (X,Y). Avec ScaleY > 0, la convention GeoTIFF + // est Y décroissant quand la ligne augmente : ligne 0 = nord. + let pas = scale[0]; + let x0 = tie[3] - tie[0] * pas; + let y0 = tie[4] + tie[1] * pas; + let valeurs = match d.read_image().map_err(|e| e.to_string())? { + DecodingResult::F32(v) => v, + DecodingResult::F64(v) => v.into_iter().map(|x| x as f32).collect(), + DecodingResult::I16(v) => v.into_iter().map(f32::from).collect(), + DecodingResult::U16(v) => v.into_iter().map(f32::from).collect(), + _ => return Err("type de pixel non géré".into()), + }; + Ok(Mnt { largeur: w as usize, hauteur: h as usize, x0, y0, pas, nodata, valeurs }) + } + + /// Altitude au point Lambert 93 (plus proche voisin), None hors emprise ou nodata. + pub fn altitude(&self, x: f64, y: f64) -> Option { + let c = ((x - self.x0) / self.pas).floor(); + let l = ((self.y0 - y) / self.pas).floor(); + if c < 0.0 || l < 0.0 || c >= self.largeur as f64 || l >= self.hauteur as f64 { + return None; + } + let v = self.valeurs[l as usize * self.largeur + c as usize]; + (Some(v) != self.nodata && v.is_finite() && v > -1000.0).then_some(v) + } + + /// Emprise en coordonnées bloc : (bx_min, bz_min, bx_max_excl, bz_max_excl). + pub fn emprise_blocs(&self, o: &WorldOrigin) -> (i32, i32, i32, i32) { + let (a, b) = o.l93_to_block(self.x0 + 0.5 * self.pas, self.y0 - 0.5 * self.pas); + let (c, d) = o.l93_to_block( + self.x0 + (self.largeur as f64 - 0.5) * self.pas, + self.y0 - (self.hauteur as f64 - 0.5) * self.pas, + ); + (a, b, c + 1, d + 1) + } +} + +/// Construit les colonnes 516×516 d'une tuile (bordure comprise). None si aucune donnée. +pub fn colonnes_tuile(mnt: &Mnt, o: &WorldOrigin, id: TileId) -> Option> { + let mut cols = vec![ColumnSample::default(); N]; + let mut n = 0usize; + for (i, c) in cols.iter_mut().enumerate() { + let lx = (i % SIDE) as i32 - BORDER; + let lz = (i / SIDE) as i32 - BORDER; + let (x, y) = o.block_to_l93(id.tx * TileId::SIZE + lx, id.tz * TileId::SIZE + lz); + if let Some(a) = mnt.altitude(x, y) { + c.ground_dm = alt_to_dm(a, o); + if (0..512).contains(&lx) && (0..512).contains(&lz) { + n += 1; + } + } + } + // Pente (Horn) sur les colonnes intérieures dont le voisinage est connu. + let g: Vec = cols.iter().map(|c| c.ground_dm as f32 / 10.0).collect(); + for lz in 1..SIDE - 1 { + for lx in 1..SIDE - 1 { + let at = |dx: isize, dz: isize| g[(lz as isize + dz) as usize * SIDE + (lx as isize + dx) as usize]; + if (-1..=1).any(|dz| (-1..=1).any(|dx| at(dx, dz) == 0.0)) { + continue; + } + let dzdx = ((at(1, -1) + 2.0 * at(1, 0) + at(1, 1)) - (at(-1, -1) + 2.0 * at(-1, 0) + at(-1, 1))) / 8.0; + let dzdz = ((at(-1, 1) + 2.0 * at(0, 1) + at(1, 1)) - (at(-1, -1) + 2.0 * at(0, -1) + at(1, -1))) / 8.0; + let pente = (dzdx.hypot(dzdz)).atan().to_degrees(); + cols[lz * SIDE + lx].slope_deg = pente.round().clamp(0.0, 90.0) as u8; + } + } + (n > 0).then_some(cols) +} + +/// Écrit toutes les tuiles couvertes par le MNT dans `out`. Renvoie les tuiles écrites. +pub fn construire(mnt: &Mnt, o: &WorldOrigin, out: &Path) -> Result, String> { + std::fs::create_dir_all(out).map_err(|e| e.to_string())?; + let (bx0, bz0, bx1, bz1) = mnt.emprise_blocs(o); + let a = TileId::of_block(bx0, bz0); + let b = TileId::of_block(bx1 - 1, bz1 - 1); + let mut faites = Vec::new(); + for tz in a.tz..=b.tz { + for tx in a.tx..=b.tx { + let id = TileId { tx, tz }; + if let Some(cols) = colonnes_tuile(mnt, o, id) { + TileWriter::write(&out.join(id.file_name()), id, o, &cols).map_err(|e| e.to_string())?; + faites.push(id); + } + } + } + Ok(faites) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// MNT synthétique 4×3 : altitude = 1000 + ligne*10 + colonne. + fn mini() -> Mnt { + Mnt { + largeur: 4, + hauteur: 3, + x0: 903_000.0, + y0: 6_451_500.0, + pas: 1.0, + nodata: Some(-99999.0), + valeurs: (0..12).map(|i| 1000.0 + (i / 4 * 10 + i % 4) as f32).collect(), + } + } + + #[test] + fn orientation_nord() { + let m = mini(); + // ligne 0 (nord) au plus grand Y + assert_eq!(m.altitude(903_000.5, 6_451_499.5), Some(1000.0)); + assert_eq!(m.altitude(903_003.5, 6_451_497.5), Some(1023.0)); + assert_eq!(m.altitude(903_000.5, 6_451_500.5), None); + let o = WorldOrigin::LANS; + assert_eq!(m.emprise_blocs(&o), (0, 0, 4, 3)); + let cols = colonnes_tuile(&m, &o, TileId { tx: 0, tz: 0 }).unwrap(); + let at = |lx: usize, lz: usize| cols[(lz + 2) * SIDE + lx + 2]; + // z=0 est le nord, z=2 le sud. + assert_eq!(at(0, 0).ground_y(&o), 0); + assert_eq!(at(3, 2).ground_y(&o), 23); + assert_eq!(at(4, 0).ground_dm, 0); + assert!(colonnes_tuile(&m, &o, TileId { tx: 1, tz: 0 }).is_none()); + } +} diff --git a/relief/rt-prep/src/main.rs b/relief/rt-prep/src/main.rs new file mode 100644 index 0000000..b3d000c --- /dev/null +++ b/relief/rt-prep/src/main.rs @@ -0,0 +1,60 @@ +//! rt-prep build --mnt --out [--origin X,Y] [--alt-base M] +//! rt-prep info + +use rt_core::WorldOrigin; +use std::path::PathBuf; + +fn main() { + if let Err(e) = run() { + eprintln!("erreur : {e}"); + std::process::exit(1); + } +} + +fn run() -> Result<(), String> { + let args: Vec = std::env::args().skip(1).collect(); + let opt = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned(); + match args.first().map(String::as_str) { + Some("build") => { + let mnt = PathBuf::from(opt("--mnt").ok_or("--mnt manquant")?); + let out = PathBuf::from(opt("--out").ok_or("--out manquant")?); + let mut o = WorldOrigin::LANS; + if let Some(s) = opt("--origin") { + let (x, y) = s.split_once(',').ok_or("--origin X,Y")?; + o.l93_x = x.parse().map_err(|_| "origin X")?; + o.l93_y = y.parse().map_err(|_| "origin Y")?; + } + if let Some(s) = opt("--alt-base") { + o.alt_base_m = s.parse().map_err(|_| "alt-base")?; + } + let m = rt_prep::Mnt::lire_geotiff(&mnt)?; + println!( + "MNT {}x{} pas {} m, coin NO ({}, {}), nodata {:?}, emprise blocs {:?}", + m.largeur, m.hauteur, m.pas, m.x0, m.y0, m.nodata, m.emprise_blocs(&o) + ); + let t = rt_prep::construire(&m, &o, &out)?; + println!("{} tuile(s) écrite(s) : {:?}", t.len(), t); + } + Some("info") => { + let p = PathBuf::from(args.get(1).ok_or("chemin manquant")?); + let t = rt_tiles::Tile::open(&p).map_err(|e| e.to_string())?; + let o = t.origin(); + let (mut mn, mut mx, mut n) = (i32::MAX, i32::MIN, 0); + for lz in 0..512 { + for lx in 0..512 { + let s = t.sample(lx, lz); + if s.ground_dm != 0 { + let y = s.ground_y(&o); + mn = mn.min(y); + mx = mx.max(y); + n += 1; + } + } + } + println!("tuile {:?}, origine {:?}, crc ok = {}", t.id(), o, t.verifier_crc()); + println!("{n} colonnes renseignées, y sol min {mn} max {mx} (alt {} à {} m)", mn + o.alt_base_m, mx + o.alt_base_m); + } + _ => return Err("usage : rt-prep build --mnt F --out D | rt-prep info F".into()), + } + Ok(()) +} diff --git a/relief/rt-prep/tests/lans.rs b/relief/rt-prep/tests/lans.rs new file mode 100644 index 0000000..4abafa1 --- /dev/null +++ b/relief/rt-prep/tests/lans.rs @@ -0,0 +1,20 @@ +//! Contrôle sur les vraies tuiles de Lans (ignoré si `donnees/tuiles-lans` est absent). +//! Valeurs de référence lues dans mnt.tif avec PIL (ligne, colonne). +use rt_tiles::TileStore; + +#[test] +fn hauteurs_reelles_lans() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../donnees/tuiles-lans"); + if !dir.join("0_0.rtt").exists() { + eprintln!("tuiles de Lans absentes : test sauté"); + return; + } + let s = TileStore::new(dir); + // (x = colonne, z = ligne) -> floor(alt) - 1000 + assert_eq!(s.hauteur_colonne(0, 0), Some(-14)); // 986,16 m, coin NO + assert_eq!(s.hauteur_colonne(700, 10), Some(10)); // 1010,65 m + assert_eq!(s.hauteur_colonne(100, 600), Some(3)); // 1003,97 m + assert_eq!(s.hauteur_colonne(999, 999), Some(41)); // 1041,90 m, coin SE + assert_eq!(s.hauteur_colonne(1000, 0), None); + assert_eq!(s.hauteur_colonne(0, -1), None); +} diff --git a/relief/rt-tiles/Cargo.toml b/relief/rt-tiles/Cargo.toml new file mode 100644 index 0000000..d5f9a10 --- /dev/null +++ b/relief/rt-tiles/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "rt-tiles" +version = "0.1.0" +edition = "2021" +license = "MIT OR Apache-2.0" + +[dependencies] +rt-core = { path = "../rt-core" } +memmap2 = "0.9" +crc32fast = "1.4" diff --git a/relief/rt-tiles/src/lib.rs b/relief/rt-tiles/src/lib.rs new file mode 100644 index 0000000..98a0b7d --- /dev/null +++ b/relief/rt-tiles/src/lib.rs @@ -0,0 +1,309 @@ +//! Format de tuile `.rtt` (rapport 07 §1.2) : en-tête 64 octets + canaux 516×516, +//! little-endian, ligne par ligne, z croissant vers le sud. + +use rt_core::{TileId, WorldOrigin}; +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; + +pub const BORDER: i32 = 2; +pub const SIDE: usize = 516; +pub const N: usize = SIDE * SIDE; +pub const HEADER: usize = 64; +pub const MAGIC: &[u8; 4] = b"RTT1"; +pub const VERSION: u16 = 1; +/// Octets par valeur de chaque canal, dans l'ordre : +/// ground_dm u16, canopy u8, landcover u8, forest u8, water_dm u16, geology u8, slope u8, aspect u8. +const CANAUX: [usize; 8] = [2, 1, 1, 1, 2, 1, 1, 1]; + +pub fn taille_fichier() -> usize { + HEADER + CANAUX.iter().map(|b| b * N).sum::() +} +fn offset_canal(i: usize) -> usize { + HEADER + CANAUX[..i].iter().map(|b| b * N).sum::() +} + +#[derive(Debug)] +pub enum TileError { + Missing, + Io(std::io::Error), + Format(String), +} +impl std::fmt::Display for TileError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + TileError::Missing => write!(f, "tuile absente"), + TileError::Io(e) => write!(f, "{e}"), + TileError::Format(s) => write!(f, "format: {s}"), + } + } +} +impl std::error::Error for TileError {} +impl From for TileError { + fn from(e: std::io::Error) -> Self { + if e.kind() == std::io::ErrorKind::NotFound { + TileError::Missing + } else { + TileError::Io(e) + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct ColumnSample { + /// Sol en décimètres au-dessus de `alt_base − 1000` m. 0 = pas de donnée. + pub ground_dm: u16, + pub canopy_halfm: u8, + pub landcover: u8, + pub forest: u8, + pub water_dm: u16, + pub geology: u8, + pub slope_deg: u8, + pub aspect: u8, +} +impl ColumnSample { + /// y du bloc solide le plus haut : floor(altitude) − alt_base. + pub fn ground_y(&self, o: &WorldOrigin) -> i32 { + (self.ground_dm / 10) as i32 + o.alt_zero_dm() - o.alt_base_m + } + pub fn ground_frac_dm(&self) -> u8 { + (self.ground_dm % 10) as u8 + } +} + +/// Altitude (m) -> `ground_dm` (arrondi au décimètre, borné à 1..=65535). +pub fn alt_to_dm(alt_m: f32, o: &WorldOrigin) -> u16 { + ((alt_m - o.alt_zero_dm() as f32) * 10.0) + .round() + .clamp(1.0, u16::MAX as f32) as u16 +} + +pub struct TileWriter; +impl TileWriter { + /// `cols` : 516×516 colonnes, index (lz+2)*516 + (lx+2). + pub fn write(path: &Path, id: TileId, o: &WorldOrigin, cols: &[ColumnSample]) -> Result<(), TileError> { + if cols.len() != N { + return Err(TileError::Format(format!("{} colonnes au lieu de {N}", cols.len()))); + } + let mut body = Vec::with_capacity(taille_fichier() - HEADER); + cols.iter().for_each(|c| body.extend_from_slice(&c.ground_dm.to_le_bytes())); + cols.iter().for_each(|c| body.push(c.canopy_halfm)); + cols.iter().for_each(|c| body.push(c.landcover)); + cols.iter().for_each(|c| body.push(c.forest)); + cols.iter().for_each(|c| body.extend_from_slice(&c.water_dm.to_le_bytes())); + cols.iter().for_each(|c| body.push(c.geology)); + cols.iter().for_each(|c| body.push(c.slope_deg)); + cols.iter().for_each(|c| body.push(c.aspect)); + let mut h = [0u8; HEADER]; + h[0..4].copy_from_slice(MAGIC); + h[4..6].copy_from_slice(&VERSION.to_le_bytes()); + h[6..10].copy_from_slice(&id.tx.to_le_bytes()); + h[10..14].copy_from_slice(&id.tz.to_le_bytes()); + h[14..22].copy_from_slice(&o.l93_x.to_le_bytes()); + h[22..30].copy_from_slice(&o.l93_y.to_le_bytes()); + h[30..34].copy_from_slice(&o.alt_base_m.to_le_bytes()); + h[34] = BORDER as u8; + h[35..39].copy_from_slice(&crc32fast::hash(&body).to_le_bytes()); + let mut all = h.to_vec(); + all.extend_from_slice(&body); + // Écriture atomique : une tuile mmapée n'est jamais réécrite en place. + let tmp = path.with_extension("rtt.tmp"); + std::fs::write(&tmp, all)?; + std::fs::rename(tmp, path)?; + Ok(()) + } +} + +pub struct Tile { + map: memmap2::Mmap, + id: TileId, + origin: WorldOrigin, +} + +fn le(m: &[u8], a: usize) -> [u8; K] { + m[a..a + K].try_into().unwrap() +} + +impl Tile { + pub fn open(path: &Path) -> Result { + let f = std::fs::File::open(path)?; + // SAFETY : lecture seule ; les tuiles sont écrites par fichier temporaire + rename, + // jamais modifiées en place. + let map = unsafe { memmap2::Mmap::map(&f)? }; + if map.len() != taille_fichier() || &map[0..4] != MAGIC { + return Err(TileError::Format("magic ou taille invalide".into())); + } + let v = u16::from_le_bytes(le(&map, 4)); + if v != VERSION { + return Err(TileError::Format(format!("version {v}"))); + } + let id = TileId { tx: i32::from_le_bytes(le(&map, 6)), tz: i32::from_le_bytes(le(&map, 10)) }; + let origin = WorldOrigin { + l93_x: f64::from_le_bytes(le(&map, 14)), + l93_y: f64::from_le_bytes(le(&map, 22)), + alt_base_m: i32::from_le_bytes(le(&map, 30)), + }; + Ok(Tile { map, id, origin }) + } + /// Vérifie le CRC (coûteux : pour `rt-prep info`, pas à chaque ouverture). + pub fn verifier_crc(&self) -> bool { + u32::from_le_bytes(le(&self.map, 35)) == crc32fast::hash(&self.map[HEADER..]) + } + pub fn id(&self) -> TileId { + self.id + } + pub fn origin(&self) -> WorldOrigin { + self.origin + } + + /// lx, lz ∈ -2..514 (bordure comprise). + pub fn sample(&self, lx: i32, lz: i32) -> ColumnSample { + assert!((-BORDER..512 + BORDER).contains(&lx) && (-BORDER..512 + BORDER).contains(&lz)); + let i = ((lz + BORDER) as usize) * SIDE + (lx + BORDER) as usize; + let m = &self.map; + let u16at = |c: usize| u16::from_le_bytes(le(m, offset_canal(c) + 2 * i)); + let u8at = |c: usize| m[offset_canal(c) + i]; + ColumnSample { + ground_dm: u16at(0), + canopy_halfm: u8at(1), + landcover: u8at(2), + forest: u8at(3), + water_dm: u16at(4), + geology: u8at(5), + slope_deg: u8at(6), + aspect: u8at(7), + } + } +} + +/// Cache de tuiles mmapées, partageable entre threads. +/// (Le LRU borné en octets et le prefetch rayon sont prévus au prototype 10.) +pub struct TileStore { + dir: PathBuf, + tiles: RwLock>>>, +} + +impl TileStore { + pub fn new(dir: PathBuf) -> Self { + TileStore { dir, tiles: RwLock::new(HashMap::new()) } + } + + pub fn get(&self, id: TileId) -> Result, TileError> { + if let Some(t) = self.tiles.read().unwrap().get(&id) { + return t.clone().ok_or(TileError::Missing); + } + let entry = match Tile::open(&self.dir.join(id.file_name())) { + Ok(t) => Some(Arc::new(t)), + Err(TileError::Missing) => None, + Err(e) => return Err(e), + }; + self.tiles.write().unwrap().insert(id, entry.clone()); + entry.ok_or(TileError::Missing) + } + + /// y du bloc solide le plus haut de la colonne (x, z), ou None hors données. + pub fn hauteur_colonne(&self, x: i32, z: i32) -> Option { + let id = TileId::of_block(x, z); + let t = self.get(id).ok()?; + let s = t.sample(x - id.tx * TileId::SIZE, z - id.tz * TileId::SIZE); + (s.ground_dm != 0).then(|| s.ground_y(&t.origin())) + } +} + +/// Bloc neutre (converti en `pumpkin_data::Block` dans rt-gen). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Bloc { + Air, + Pierre, + Terre, + Herbe, + Bedrock, +} + +pub const EPAISSEUR_TERRE: i32 = 3; + +/// Remplit `out` (index 0 = `min_y`) pour une colonne dont le sol est à `sol_y`. +/// Bedrock à min_y, pierre, 3 blocs de terre, herbe au sommet, air au-dessus. +pub fn remplir_colonne(sol_y: Option, min_y: i32, out: &mut [Bloc]) { + for (i, b) in out.iter_mut().enumerate() { + let y = min_y + i as i32; + *b = match sol_y { + None => Bloc::Air, + Some(s) if y > s => Bloc::Air, + Some(_) if y == min_y => Bloc::Bedrock, + Some(s) if y == s => Bloc::Herbe, + Some(s) if y >= s - EPAISSEUR_TERRE => Bloc::Terre, + Some(_) => Bloc::Pierre, + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn synth(o: &WorldOrigin) -> Vec { + (0..N) + .map(|i| { + let (lx, lz) = ((i % SIDE) as i32 - 2, (i / SIDE) as i32 - 2); + ColumnSample { + ground_dm: alt_to_dm(1000.0 + lx as f32 * 0.1 + lz as f32, o), + slope_deg: 7, + ..Default::default() + } + }) + .collect() + } + + #[test] + fn aller_retour_tuile() { + let o = WorldOrigin::LANS; + let dir = std::env::temp_dir().join("rt-tiles-test-1"); + std::fs::create_dir_all(&dir).unwrap(); + let id = TileId { tx: 0, tz: 0 }; + TileWriter::write(&dir.join(id.file_name()), id, &o, &synth(&o)).unwrap(); + let t = Tile::open(&dir.join(id.file_name())).unwrap(); + assert!(t.verifier_crc()); + assert_eq!(t.id(), id); + assert_eq!(t.origin(), o); + let s = t.sample(10, 20); + assert_eq!(s.ground_dm, 10210); + assert_eq!(s.ground_y(&o), 21); + assert_eq!(s.ground_frac_dm(), 0); + assert_eq!(s.slope_deg, 7); + assert_eq!(t.sample(-2, -2).ground_dm, alt_to_dm(997.8, &o)); + assert_eq!(t.sample(513, 513).ground_dm, alt_to_dm(1000.0 + 51.3 + 513.0, &o)); + + let store = TileStore::new(dir); + assert_eq!(store.hauteur_colonne(10, 20), Some(21)); + assert_eq!(store.hauteur_colonne(-1, 0), None); // tuile -1_0 absente + assert_eq!(store.hauteur_colonne(511, 0), Some(51)); + } + + #[test] + fn tuile_corrompue() { + let p = std::env::temp_dir().join("rt-tiles-bad.rtt"); + std::fs::write(&p, b"RTT1xxxx").unwrap(); + assert!(matches!(Tile::open(&p), Err(TileError::Format(_)))); + assert!(matches!(Tile::open(Path::new("n_existe_pas.rtt")), Err(TileError::Missing))); + } + + #[test] + fn colonne() { + let mut out = [Bloc::Air; 32]; + remplir_colonne(Some(20), 0, &mut out); + assert_eq!(out[0], Bloc::Bedrock); + assert_eq!(out[16], Bloc::Pierre); + assert_eq!(&out[17..20], &[Bloc::Terre; 3]); + assert_eq!(out[20], Bloc::Herbe); + assert_eq!(out[21], Bloc::Air); + remplir_colonne(None, 0, &mut out); + assert!(out.iter().all(|b| *b == Bloc::Air)); + } + + #[test] + fn store_send_sync() { + fn f() {} + f::(); + } +}