relief: rt-core, rt-tiles (.rtt mmap, hauteur_colonne, remplir_colonne), rt-prep (GeoTIFF -> .rtt)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
8c928eb1bf
révision
9d47beb46b
11 fichiers modifiés
+794
Aucun fichier ne correspond à votre recherche
@@ -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"
|
||||
@@ -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::<usize>()
|
||||
}
|
||||
fn offset_canal(i: usize) -> usize {
|
||||
HEADER + CANAUX[..i].iter().map(|b| b * N).sum::<usize>()
|
||||
}
|
||||
|
||||
#[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<std::io::Error> 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<const K: usize>(m: &[u8], a: usize) -> [u8; K] {
|
||||
m[a..a + K].try_into().unwrap()
|
||||
}
|
||||
|
||||
impl Tile {
|
||||
pub fn open(path: &Path) -> Result<Tile, TileError> {
|
||||
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<HashMap<TileId, Option<Arc<Tile>>>>,
|
||||
}
|
||||
|
||||
impl TileStore {
|
||||
pub fn new(dir: PathBuf) -> Self {
|
||||
TileStore { dir, tiles: RwLock::new(HashMap::new()) }
|
||||
}
|
||||
|
||||
pub fn get(&self, id: TileId) -> Result<Arc<Tile>, 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<i32> {
|
||||
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<i32>, 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<ColumnSample> {
|
||||
(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<T: Send + Sync>() {}
|
||||
f::<TileStore>();
|
||||
}
|
||||
}
|
||||
Référencer dans un nouveau ticket
Bloquer un utilisateur