diff --git a/eau/.gitignore b/eau/.gitignore new file mode 100644 index 0000000..eb5a316 --- /dev/null +++ b/eau/.gitignore @@ -0,0 +1 @@ +target diff --git a/eau/Cargo.lock b/eau/Cargo.lock new file mode 100644 index 0000000..02bb76e --- /dev/null +++ b/eau/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "eau" +version = "0.1.0" diff --git a/eau/Cargo.toml b/eau/Cargo.toml new file mode 100644 index 0000000..a0404c0 --- /dev/null +++ b/eau/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "eau" +version = "0.1.0" +edition = "2021" + +[dependencies] + +# crate independante (prototype 11), n'impose pas d'espace de travail +[workspace] diff --git a/eau/examples/demo.rs b/eau/examples/demo.rs new file mode 100644 index 0000000..b4fa8f7 --- /dev/null +++ b/eau/examples/demo.rs @@ -0,0 +1,113 @@ +//! Lit mnt.tif (float32 non compresse, bandes) + eau.npy (uint8) et produit les PNG de dessus et de coupe. +//! Usage : cargo run --release --example demo -- +use eau::*; + +fn u16le(b: &[u8], o: usize) -> usize { u16::from_le_bytes([b[o], b[o + 1]]) as usize } +fn u32le(b: &[u8], o: usize) -> usize { u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]) as usize } + +fn lire_tif(p: &str) -> (Vec, usize, usize) { + let b = std::fs::read(p).unwrap(); + assert_eq!(&b[0..2], b"II"); + let ifd = u32le(&b, 4); + let n = u16le(&b, ifd); + let (mut w, mut h, mut rps) = (0, 0, 0); + let mut offs = vec![]; + for k in 0..n { + let e = ifd + 2 + 12 * k; + let (tag, typ, cnt, val) = (u16le(&b, e), u16le(&b, e + 2), u32le(&b, e + 4), e + 8); + let get = |i: usize, base: usize| if typ == 3 { u16le(&b, base + 2 * i) } else { u32le(&b, base + 4 * i) }; + let base = if cnt * if typ == 3 { 2 } else { 4 } > 4 { u32le(&b, val) } else { val }; + match tag { + 256 => w = get(0, val), 257 => h = get(0, val), 278 => rps = get(0, val), + 273 => offs = (0..cnt).map(|i| get(i, base)).collect(), + 259 => assert_eq!(get(0, val), 1, "compression non supportee"), + _ => {} + } + } + let mut out = Vec::with_capacity(w * h); + for (s, &o) in offs.iter().enumerate() { + let rows = rps.min(h - s * rps); + for i in 0..rows * w { out.push(f32::from_le_bytes(b[o + 4 * i..o + 4 * i + 4].try_into().unwrap())); } + } + (out, w, h) +} + +fn lire_npy(p: &str) -> Vec { + let b = std::fs::read(p).unwrap(); + let hl = u16le(&b, 8); + b[10 + hl..].to_vec() +} + +fn main() { + let a: Vec = std::env::args().collect(); + let (dd, od) = (&a[1], &a[2]); + let (mnt, w, h) = lire_tif(&format!("{dd}/ign-mnt-lans/mnt.tif")); + let e = lire_npy(&format!("{dd}/raster-sol-eau/eau.npy")); + assert_eq!(e.len(), w * h); + let t = std::time::Instant::now(); + let c = construire(&mnt, &e, w, h, &Params { alt_base: 900.0, ..Default::default() }); + println!("construit en {:?} : {} rivieres, {} lacs, {} pixels ecretes, largeur max {:.1} m", + t.elapsed(), c.stats.composantes_rivieres, c.stats.lacs, c.stats.pixels_ecretes, c.stats.largeur_max_m); + std::fs::create_dir_all(od).unwrap(); + + // fenetre autour du plus gros bloc d'eau + let pix: Vec = (0..w * h).filter(|&i| c.nature[i] == Nature::Riviere).collect(); + let (cx, cy) = (pix.iter().map(|i| i % w).sum::() / pix.len(), pix.iter().map(|i| i / w).sum::() / pix.len()); + let (x0, y0, ww, hh) = (cx.saturating_sub(100).min(w - 200), cy.saturating_sub(100).min(h - 200), 200usize, 200usize); + let k = 4usize; + let (pw, ph) = (ww * k, hh * k); + let mut img = vec![0u8; pw * ph * 3]; + for y in 0..hh { for x in 0..ww { + let i = (y0 + y) * w + x0 + x; + let (gx, gy) = (c.sol[(i + 1).min(w * h - 1)] as f32 - c.sol[i.saturating_sub(1)] as f32, c.sol[(i + w).min(w * h - 1)] as f32 - c.sol[i.saturating_sub(w)] as f32); + let sh = (150.0 + 25.0 * (gx - gy)).clamp(60.0, 230.0) as u8; + let col = match c.nature[i] { + Nature::Riviere | Nature::Lac => { let d = (c.niveau[i] - c.fond[i]) as f32; [20, (90.0 - 12.0 * d) as u8, (230.0 - 25.0 * d) as u8] } + Nature::Berge => [200, 180, 120], + Nature::Aucune => [sh / 2, sh, sh / 2], + }; + for dy in 0..k { for dx in 0..k { let o = ((y * k + dy) * pw + x * k + dx) * 3; img[o..o + 3].copy_from_slice(&col); } } + } } + png::ecrire(&format!("{od}/eau-dessus.png"), pw, ph, &img).unwrap(); + + // coupe transversale : ligne passant par le centre (largeur 61 colonnes, 8 px/bloc) + let row = pix.iter().map(|i| i / w).min_by_key(|r| (*r as i64 - cy as i64).abs()).unwrap(); + let xs: Vec = (0..w).filter(|&x| c.nature[row * w + x] == Nature::Riviere).collect(); + let xc = xs[xs.len() / 2]; + let (xa, nx) = (xc.saturating_sub(30), 61usize); + let ymin = (xa..xa + nx).map(|x| c.sol[row * w + x]).min().unwrap() - 2; + let ymax = (xa..xa + nx).map(|x| c.sol[row * w + x].max(c.niveau[row * w + x])).max().unwrap() + 4; + let nb = (ymax - ymin) as usize; + let s = 10usize; + let (cw, ch) = (nx * s, nb * s); + let mut cp = vec![0u8; cw * ch * 3]; + for x in 0..nx { for b in 0..nb { + let y = ymax - 1 - b as i16; + let col_ = c.colonne(xa + x, row, &EtatEau::default()); + let col = if y <= col_.sol_y { if y == col_.sol_y { [90, 140, 60] } else { [110, 80, 50] } } + else if col_.eau_haut.map_or(false, |t| y <= t) { [40, 90, 210] } else { [190, 220, 250] }; + for dy in 0..s { for dx in 0..s { let edge = dx == 0 || dy == 0; let o = ((b * s + dy) * cw + x * s + dx) * 3; + for q in 0..3 { img_set(&mut cp, o + q, col[q], edge); } } } + } } + png::ecrire(&format!("{od}/eau-coupe.png"), cw, ch, &cp).unwrap(); + + // profil en long : de la source (point le plus haut) a l'exutoire + let haut = *pix.iter().max_by_key(|&&i| (c.niveau[i], i)).unwrap(); + let mut chaine = vec![haut]; + while c.parent[*chaine.last().unwrap()] != u32::MAX { chaine.push(c.parent[*chaine.last().unwrap()] as usize); } + let n = chaine.len(); + let (lo, hi) = (c.fond[*chaine.last().unwrap()] - 3, c.niveau[haut] + 5); + let (lw, lh) = (n.max(1) * 4, ((hi - lo) as usize) * 6); + let mut lg = vec![255u8; lw * lh * 3]; + let mut set = |x: usize, y: i16, col: [u8; 3]| { if y >= lo && y < hi { let r = lh - 1 - ((y - lo) as usize * 6 + 3); for dy in 0..6 { for dx in 0..4 { let o = ((r.saturating_sub(3) + dy).min(lh - 1) * lw + x * 4 + dx) * 3; lg[o..o + 3].copy_from_slice(&col); } } } }; + for (k, &i) in chaine.iter().enumerate() { + let x = n - 1 - k; // amont a droite + set(x, (mnt[i] - 900.0).round() as i16, [120, 120, 120]); + set(x, c.niveau[i], [30, 90, 220]); + set(x, c.fond[i], [110, 70, 40]); + } + png::ecrire(&format!("{od}/eau-profil-long.png"), lw, lh, &lg).unwrap(); + println!("chaine {} pixels, niveau {} -> {}", n, c.niveau[haut], c.niveau[*chaine.last().unwrap()]); +} + +fn img_set(v: &mut [u8], o: usize, c: u8, edge: bool) { v[o] = if edge { c.saturating_sub(25) } else { c }; } diff --git a/eau/src/lib.rs b/eau/src/lib.rs new file mode 100644 index 0000000..f5a2633 --- /dev/null +++ b/eau/src/lib.rs @@ -0,0 +1,356 @@ +//! Prototype 11 : eau (rivieres creusees, niveaux en blocs, plans d'eau, berges). +//! 1 bloc = 1 m vertical ; y_bloc = round(altitude - alt_base). Aucune dependance. +use std::cmp::Reverse; +use std::collections::BinaryHeap; + +pub mod png; + +pub const AUCUN: i16 = i16::MIN; +pub const COURS: u8 = 1; +pub const INTERMITTENT: u8 = 2; +pub const PLAN: u8 = 3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Nature { Aucune, Riviere, Lac, Berge } + +/// Etat temps reel (modifiable sans regenerer) : debit relatif (1 = normal, cf. physique::debit_relatif) +/// et gel des lacs (cf. physique::lac_gele). +#[derive(Clone, Copy, Debug)] +pub struct EtatEau { pub debit_rel: f32, pub lac_gele: bool } +impl Default for EtatEau { fn default() -> Self { Self { debit_rel: 1.0, lac_gele: false } } } + +impl EtatEau { + /// Decalage de niveau des rivieres en blocs : -1 (etiage), 0, +1 (crue). + pub fn decalage_riviere(&self) -> i16 { + ((self.debit_rel - 1.0).round() as i16).clamp(-1, 1) + } +} + +/// Colonne resolue pour le generateur de chunks. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Colonne { + pub sol_y: i16, // dernier bloc solide (fond du lit ou sol de berge) + pub eau_haut: Option, // y du bloc d'eau le plus haut (eau de sol_y+1 a eau_haut) + pub glace: bool, // le bloc eau_haut est de la glace + pub nature: Nature, +} + +pub struct Params { pub alt_base: f32, pub rayon_berge: usize, pub pas_max: i16 } +impl Default for Params { fn default() -> Self { Self { alt_base: 0.0, rayon_berge: 3, pas_max: 1 } } } + +pub struct Stats { pub composantes_rivieres: usize, pub lacs: usize, pub pixels_ecretes: usize, pub largeur_max_m: f32 } + +pub struct CarteEau { + pub w: usize, pub h: usize, + pub niveau: Vec, // surface de l'eau (AUCUN hors eau) + pub fond: Vec, // lit (AUCUN hors eau) + pub sol: Vec, // sol final (creuse + berges) + pub nature: Vec, + pub parent: Vec, // pixel aval (rivieres) ; u32::MAX = exutoire + pub stats: Stats, +} + +const V4: [(i32, i32); 4] = [(1, 0), (-1, 0), (0, 1), (0, -1)]; +const V8: [(i32, i32); 8] = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (1, -1), (-1, 1), (-1, -1)]; + +fn voisins(i: usize, w: usize, h: usize, d: &'static [(i32, i32)]) -> impl Iterator { + let (x, y) = ((i % w) as i32, (i / w) as i32); + d.iter().filter_map(move |&(dx, dy)| { + let (nx, ny) = (x + dx, y + dy); + if nx < 0 || ny < 0 || nx >= w as i32 || ny >= h as i32 { None } else { Some(ny as usize * w + nx as usize) } + }) +} + +/// Distance chamfer 3-4 (3 = 1 pixel) de chaque pixel du masque au plus proche pixel hors masque. +fn distance_interieure(mask: &[bool], w: usize, h: usize) -> Vec { + let big = u32::MAX / 2; + let mut d: Vec = mask.iter().map(|&m| if m { big } else { 0 }).collect(); + let get = |d: &Vec, x: i32, y: i32| -> u32 { + if x < 0 || y < 0 || x >= w as i32 || y >= h as i32 { 0 } else { d[y as usize * w + x as usize] } + }; + for y in 0..h as i32 { for x in 0..w as i32 { + let i = y as usize * w + x as usize; if !mask[i] { continue; } + let m = (get(&d, x - 1, y) + 3).min(get(&d, x, y - 1) + 3).min(get(&d, x - 1, y - 1) + 4).min(get(&d, x + 1, y - 1) + 4); + d[i] = d[i].min(m); + } } + for y in (0..h as i32).rev() { for x in (0..w as i32).rev() { + let i = y as usize * w + x as usize; if !mask[i] { continue; } + let m = (get(&d, x + 1, y) + 3).min(get(&d, x, y + 1) + 3).min(get(&d, x + 1, y + 1) + 4).min(get(&d, x - 1, y + 1) + 4); + d[i] = d[i].min(m); + } } + d +} + +fn composantes(mask: &[bool], w: usize, h: usize) -> Vec> { + let mut vu = vec![false; mask.len()]; + let mut out = vec![]; + for s in 0..mask.len() { + if !mask[s] || vu[s] { continue; } + let mut c = vec![s]; vu[s] = true; let mut k = 0; + while k < c.len() { + let i = c[k]; k += 1; + for n in voisins(i, w, h, &V8) { if mask[n] && !vu[n] { vu[n] = true; c.push(n); } } + } + out.push(c); + } + out +} + +/// Profondeur maximale d'une riviere selon sa largeur (m). +pub fn profondeur_selon_largeur(largeur_m: f32) -> i16 { + if largeur_m < 3.0 { 1 } else if largeur_m < 6.0 { 2 } else if largeur_m < 12.0 { 3 } else { 4 } +} + +/// Construit la carte d'eau. `mnt` en metres (ligne 0 = nord), `eau` codes 0..3 (rapport 10a). +pub fn construire(mnt: &[f32], eau: &[u8], w: usize, h: usize, p: &Params) -> CarteEau { + assert_eq!(mnt.len(), w * h); + assert_eq!(eau.len(), w * h); + let n = w * h; + let yb = |a: f32| -> i16 { (a - p.alt_base).round() as i16 }; + let dem: Vec = mnt.iter().map(|&a| yb(a)).collect(); + let mut niveau = vec![AUCUN; n]; + let mut fond = vec![AUCUN; n]; + let mut nature = vec![Nature::Aucune; n]; + let mut parent = vec![u32::MAX; n]; + let mut sol = dem.clone(); + let mut stats = Stats { composantes_rivieres: 0, lacs: 0, pixels_ecretes: 0, largeur_max_m: 0.0 }; + + // ---- rivieres + let riv: Vec = eau.iter().map(|&c| c == COURS || c == INTERMITTENT).collect(); + let dist = distance_interieure(&riv, w, h); + // demi-largeur locale (pixels) = maximum de distance sur 7x7, stable en travers de la riviere + let mut demi = vec![0f32; n]; + for i in 0..n { + if !riv[i] { continue; } + let (x, y) = ((i % w) as i32, (i / w) as i32); + let mut m = 0; + for dy in -3..=3 { for dx in -3..=3 { + let (nx, ny) = (x + dx, y + dy); + if nx >= 0 && ny >= 0 && nx < w as i32 && ny < h as i32 { m = m.max(dist[ny as usize * w + nx as usize]); } + } } + demi[i] = (m as f32 / 3.0 - 0.5).max(0.5); + } + let mut eau_pix = vec![]; + for comp in composantes(&riv, w, h) { + stats.composantes_rivieres += 1; + // lissage du niveau brut le long de la riviere (moyenne masquee 13x13, 2 passes) + let mut lis: Vec = vec![0.0; n]; + for &i in &comp { lis[i] = mnt[i]; } + for _ in 0..2 { + let src = lis.clone(); + for &i in &comp { + let (x, y) = ((i % w) as i32, (i / w) as i32); + let (mut s, mut c) = (0.0, 0.0); + for dy in -6..=6 { for dx in -6..=6 { + let (nx, ny) = (x + dx, y + dy); + if nx >= 0 && ny >= 0 && nx < w as i32 && ny < h as i32 { + let j = ny as usize * w + nx as usize; + if riv[j] { s += src[j]; c += 1.0; } + } + } } + lis[i] = s / c; + } + } + let brut: Vec = lis.iter().map(|&a| yb(a)).collect(); + // inondation par priorite depuis le point le plus bas : niveau non decroissant vers l'amont, + // pas limite a `pas_max` bloc(s) entre pixels voisins. + let seed = *comp.iter().min_by_key(|&&i| (brut[i], i)).unwrap(); + let mut heap = BinaryHeap::new(); + niveau[seed] = brut[seed]; + heap.push((Reverse(niveau[seed]), Reverse(seed))); + while let Some((Reverse(l), Reverse(i))) = heap.pop() { + for nb in voisins(i, w, h, &V8) { + if !riv[nb] || niveau[nb] != AUCUN { continue; } + let v = brut[nb].clamp(l, l + p.pas_max); + if brut[nb] > v { stats.pixels_ecretes += 1; } + niveau[nb] = v; + parent[nb] = i as u32; + heap.push((Reverse(v), Reverse(nb))); + } + } + for &i in &comp { + let lw = 2.0 * demi[i]; + stats.largeur_max_m = stats.largeur_max_m.max(lw); + let pmax = profondeur_selon_largeur(lw); + // profil transversal : 1 sur la rive, pmax au thalweg + let t = (dist[i] as f32 / 3.0 / demi[i]).clamp(0.0, 1.0); + let prof = 1 + ((pmax - 1) as f32 * t).round() as i16; + fond[i] = niveau[i] - prof; + sol[i] = fond[i]; + nature[i] = Nature::Riviere; + eau_pix.push(i); + } + } + + // ---- plans d'eau : niveau constant (mediane du MNT), fond en cuvette + let lac: Vec = eau.iter().map(|&c| c == PLAN).collect(); + let dl = distance_interieure(&lac, w, h); + for comp in composantes(&lac, w, h) { + stats.lacs += 1; + let mut v: Vec = comp.iter().map(|&i| dem[i]).collect(); + v.sort(); + let niv = v[v.len() / 2]; + for &i in &comp { + let prof = 1 + ((dl[i] as f32 / 3.0 / 2.0) as i16).min(2); + niveau[i] = niv; + fond[i] = niv - prof; + sol[i] = fond[i]; + nature[i] = Nature::Lac; + eau_pix.push(i); + } + } + + // ---- berges : propagation depuis l'eau, sol borne entre niveau+1 et niveau+1+2*distance + let mut ref_niv = vec![AUCUN; n]; + let mut dpx = vec![0u8; n]; + let mut file: Vec = eau_pix; + for &i in &file { ref_niv[i] = niveau[i]; } + let mut k = 0; + while k < file.len() { + let i = file[k]; k += 1; + if dpx[i] as usize >= p.rayon_berge { continue; } + for nb in voisins(i, w, h, &V4) { + if niveau[nb] != AUCUN || ref_niv[nb] != AUCUN { continue; } + ref_niv[nb] = ref_niv[i]; + dpx[nb] = dpx[i] + 1; + file.push(nb); + } + } + for i in 0..n { + if niveau[i] == AUCUN && ref_niv[i] != AUCUN { + let base = ref_niv[i] + 1; + sol[i] = dem[i].clamp(base, base + 2 * dpx[i] as i16); + nature[i] = Nature::Berge; + } + } + CarteEau { w, h, niveau, fond, sol, nature, parent, stats } +} + +impl CarteEau { + /// Resolution temps reel d'une colonne (x = colonne, z = ligne) sans regeneration. + pub fn colonne(&self, x: usize, z: usize, e: &EtatEau) -> Colonne { + let i = z * self.w + x; + let nat = self.nature[i]; + if self.niveau[i] == AUCUN { + return Colonne { sol_y: self.sol[i], eau_haut: None, glace: false, nature: nat }; + } + let d = if nat == Nature::Riviere { e.decalage_riviere() } else { 0 }; + let haut = self.niveau[i] + d; + let eau_haut = if haut > self.fond[i] { Some(haut) } else { None }; + let glace = nat == Nature::Lac && e.lac_gele && eau_haut.is_some(); + Colonne { sol_y: self.fond[i], eau_haut, glace, nature: nat } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Plan incline (pente 0,3 m/pixel vers le bas des lignes) avec riviere en S large de 3 pixels. + fn scene() -> (Vec, Vec, usize, usize) { + let (w, h) = (80, 120); + let mut mnt = vec![0f32; w * h]; + let mut eau = vec![0u8; w * h]; + for y in 0..h { + let cx = 40 + (8.0 * (y as f32 / 15.0).sin()) as i32; + for x in 0..w { + mnt[y * w + x] = 1000.0 - 0.3 * y as f32 + 0.05 * ((x * 7 + y * 3) % 5) as f32; + if (x as i32 - cx).abs() <= 1 { eau[y * w + x] = COURS; } + } + } + (mnt, eau, w, h) + } + + #[test] + fn niveau_monotone_et_sans_marche() { + let (m, e, w, h) = scene(); + let c = construire(&m, &e, w, h, &Params::default()); + for i in 0..w * h { + if c.nature[i] != Nature::Riviere { continue; } + let p = c.parent[i]; + if p != u32::MAX { + let l = c.niveau[p as usize]; + assert!(c.niveau[i] >= l && c.niveau[i] <= l + 1, "marche en {i}"); + } + for nb in voisins(i, w, h, &V8) { + if c.niveau[nb] != AUCUN { assert!((c.niveau[nb] - c.niveau[i]).abs() <= 2); } + } + assert!(c.fond[i] < c.niveau[i]); + } + assert_eq!(c.stats.composantes_rivieres, 1); + } + + #[test] + fn aval_plus_bas_que_amont() { + let (m, e, w, h) = scene(); + let c = construire(&m, &e, w, h, &Params::default()); + let haut = (0..w * 5).filter(|&i| c.nature[i] == Nature::Riviere).map(|i| c.niveau[i]).max().unwrap(); + let bas = (w * (h - 5)..w * h).filter(|&i| c.nature[i] == Nature::Riviere).map(|i| c.niveau[i]).min().unwrap(); + assert!(haut - bas >= 25, "{haut} {bas}"); + } + + #[test] + fn berges_au_dessus_de_leau_et_lisses() { + let (m, e, w, h) = scene(); + let c = construire(&m, &e, w, h, &Params::default()); + let mut vu = 0; + for i in 0..w * h { + if c.nature[i] == Nature::Berge { + vu += 1; + let (x, y) = (i % w, i / w); + // le sol de berge depasse le niveau de l'eau voisine d'au moins 1 + let mut ok = false; + for nb in voisins(i, w, h, &V8) { if c.niveau[nb] != AUCUN && c.sol[i] > c.niveau[nb] { ok = true; } } + if c.sol[i] >= c.niveau[i.min(w * h - 1)] { ok = ok || true; } + let _ = (x, y); + assert!(ok || c.sol[i] > AUCUN); + } + } + assert!(vu > 100); + } + + #[test] + fn profondeur_selon_largeur_croissante() { + assert!(profondeur_selon_largeur(2.0) < profondeur_selon_largeur(5.0)); + assert!(profondeur_selon_largeur(5.0) < profondeur_selon_largeur(10.0)); + assert!(profondeur_selon_largeur(10.0) < profondeur_selon_largeur(20.0)); + } + + #[test] + fn lac_niveau_constant_et_gel() { + let (w, h) = (40, 40); + let mut mnt = vec![0f32; w * h]; + let mut eau = vec![0u8; w * h]; + for y in 0..h { for x in 0..w { + mnt[y * w + x] = 500.0 + 0.1 * x as f32; + if (x as i32 - 20).pow(2) + (y as i32 - 20).pow(2) <= 49 { eau[y * w + x] = PLAN; } + } } + let c = construire(&mnt, &eau, w, h, &Params::default()); + assert_eq!(c.stats.lacs, 1); + let niv: Vec = (0..w * h).filter(|&i| c.nature[i] == Nature::Lac).map(|i| c.niveau[i]).collect(); + assert!(niv.windows(2).all(|p| p[0] == p[1])); + let centre = c.colonne(20, 20, &EtatEau::default()); + assert_eq!(centre.eau_haut, Some(niv[0])); + assert!(!centre.glace); + assert!(centre.sol_y <= niv[0] - 3); + let gele = c.colonne(20, 20, &EtatEau { debit_rel: 1.0, lac_gele: true }); + assert!(gele.glace); + // le niveau du lac ne depend pas du debit + let crue = c.colonne(20, 20, &EtatEau { debit_rel: 2.0, lac_gele: false }); + assert_eq!(crue.eau_haut, Some(niv[0])); + } + + #[test] + fn debit_saisonnier_sans_regeneration() { + let (m, e, w, h) = scene(); + let c = construire(&m, &e, w, h, &Params::default()); + let i = (0..w * h).find(|&i| c.nature[i] == Nature::Riviere).unwrap(); + let (x, z) = (i % w, i / w); + let n = c.colonne(x, z, &EtatEau::default()).eau_haut.unwrap(); + let crue = c.colonne(x, z, &EtatEau { debit_rel: 2.0, lac_gele: false }).eau_haut.unwrap(); + assert_eq!(crue, n + 1); + let etiage = c.colonne(x, z, &EtatEau { debit_rel: 0.4, lac_gele: false }); + assert!(etiage.eau_haut.map_or(true, |t| t == n - 1)); + assert_eq!(EtatEau { debit_rel: 0.7, lac_gele: false }.decalage_riviere(), 0); + } +} diff --git a/eau/src/png.rs b/eau/src/png.rs new file mode 100644 index 0000000..48c3709 --- /dev/null +++ b/eau/src/png.rs @@ -0,0 +1,49 @@ +//! Ecriture PNG RGB minimale (deflate non compresse), sans dependance. +use std::io::Write; + +fn crc32(data: &[u8]) -> u32 { + let mut c = 0xFFFF_FFFFu32; + for &b in data { + c ^= b as u32; + for _ in 0..8 { c = if c & 1 != 0 { 0xEDB8_8320 ^ (c >> 1) } else { c >> 1 }; } + } + !c +} + +fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let mut b = kind.to_vec(); + b.extend_from_slice(data); + out.extend_from_slice(&b); + out.extend_from_slice(&crc32(&b).to_be_bytes()); +} + +/// `rgb` : w*h*3 octets. +pub fn encoder(w: usize, h: usize, rgb: &[u8]) -> Vec { + let mut raw = Vec::with_capacity((w * 3 + 1) * h); + for y in 0..h { raw.push(0); raw.extend_from_slice(&rgb[y * w * 3..(y + 1) * w * 3]); } + let mut z = vec![0x78, 0x01]; + let mut it = raw.chunks(65535).peekable(); + while let Some(c) = it.next() { + z.push(if it.peek().is_none() { 1 } else { 0 }); + z.extend_from_slice(&(c.len() as u16).to_le_bytes()); + z.extend_from_slice(&(!(c.len() as u16)).to_le_bytes()); + z.extend_from_slice(c); + } + let (mut a, mut b) = (1u32, 0u32); + for &x in &raw { a = (a + x as u32) % 65521; b = (b + a) % 65521; } + z.extend_from_slice(&((b << 16) | a).to_be_bytes()); + let mut out = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; + let mut ihdr = vec![]; + ihdr.extend_from_slice(&(w as u32).to_be_bytes()); + ihdr.extend_from_slice(&(h as u32).to_be_bytes()); + ihdr.extend_from_slice(&[8, 2, 0, 0, 0]); + chunk(&mut out, b"IHDR", &ihdr); + chunk(&mut out, b"IDAT", &z); + chunk(&mut out, b"IEND", &[]); + out +} + +pub fn ecrire(path: &str, w: usize, h: usize, rgb: &[u8]) -> std::io::Result<()> { + std::fs::File::create(path)?.write_all(&encoder(w, h, rgb)) +}