Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : KA Maps Engine9// File : server/km-terrain/src/store.rs10// Module : server11// Repository : https://git.spboucher.ai/ka-maps-engine12// Created : 2026-12-0113// Last Modified : 2026-12-0114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687//! Lecture de la pyramide sur disque (`{racine}/{z}/{x}/{y}.ktr`) et altitude en un point.8889use crate::ktr::{self, Tile};90use std::collections::HashMap;91use std::path::{Path, PathBuf};92use std::sync::{Arc, Mutex};9394pub const MAX_LAT: f64 = 85.051_128_779_806_59;9596/// Position fractionnaire (x, y) dans la pyramide XYZ au zoom `z`.97pub fn lonlat_to_tile(lon: f64, lat: f64, z: u8) -> (f64, f64) {98 let n = (1u64 << z) as f64;99 let lat = lat.clamp(-MAX_LAT, MAX_LAT).to_radians();100 let x = (lon + 180.0) / 360.0 * n;101 let y = (1.0 - lat.tan().asinh() / std::f64::consts::PI) / 2.0 * n;102 (x, y)103}104105pub fn tile_path(root: &Path, z: u8, x: u32, y: u32) -> PathBuf {106 root.join(z.to_string()).join(x.to_string()).join(format!("{y}.ktr"))107}108109#[derive(Debug, Clone, Copy, PartialEq)]110pub struct Elevation {111 pub metres: f64,112 pub zoom: u8,113}114115/// Petit cache de tuiles décodées (éviction grossière : vidé quand il est plein).116pub struct DemStore {117 root: PathBuf,118 cap: usize,119 cache: Mutex<HashMap<(u8, u32, u32), Option<Arc<Tile>>>>,120}121122impl DemStore {123 pub fn new(root: impl Into<PathBuf>, cap: usize) -> Self {124 Self { root: root.into(), cap: cap.max(1), cache: Mutex::new(HashMap::new()) }125 }126127 pub fn root(&self) -> &Path {128 &self.root129 }130131 fn tile(&self, z: u8, x: u32, y: u32) -> Option<Arc<Tile>> {132 if let Some(t) = self.cache.lock().unwrap().get(&(z, x, y)) {133 return t.clone();134 }135 let t = std::fs::read(tile_path(&self.root, z, x, y))136 .ok()137 .and_then(|b| ktr::decode(&b).ok())138 .map(Arc::new);139 let mut c = self.cache.lock().unwrap();140 if c.len() >= self.cap {141 c.clear();142 }143 c.insert((z, x, y), t.clone());144 t145 }146147 /// Altitude interpolée, au zoom le plus fin disponible entre `zmax` et `zmin`.148 pub fn elevation(&self, lon: f64, lat: f64, zmax: u8, zmin: u8) -> Option<Elevation> {149 if !(lon.is_finite() && lat.is_finite()) || lat.abs() > MAX_LAT || lon.abs() > 180.0 {150 return None;151 }152 let mut z = zmax;153 loop {154 let n = 1u32 << z;155 let (fx, fy) = lonlat_to_tile(lon, lat, z);156 let x = (fx.floor() as i64).clamp(0, n as i64 - 1) as u32;157 let y = (fy.floor() as i64).clamp(0, n as i64 - 1) as u32;158 if let Some(t) = self.tile(z, x, y) {159 if let Some(m) = t.sample((fx - x as f64) * 256.0, (fy - y as f64) * 256.0) {160 return Some(Elevation { metres: m, zoom: z });161 }162 }163 if z == zmin {164 return None;165 }166 z -= 1;167 }168 }169}170171#[cfg(test)]172mod tests {173 use super::*;174175 #[test]176 fn tile_math() {177 let (x, y) = lonlat_to_tile(0.0, 0.0, 1);178 assert!((x - 1.0).abs() < 1e-12 && (y - 1.0).abs() < 1e-12);179 let (x, y) = lonlat_to_tile(-73.5878, 45.5048, 12);180 assert_eq!((x.floor() as u32, y.floor() as u32), (1210, 1465));181 let (_, y) = lonlat_to_tile(0.0, MAX_LAT, 3);182 assert!(y.abs() < 1e-9);183 }184185 #[test]186 fn elevation_from_disk_with_fallback() {187 let dir = std::env::temp_dir().join(format!("kmterrain-test-{}", std::process::id()));188 let _ = std::fs::remove_dir_all(&dir);189 // z3 seulement : tuile (2, 2) à 120,0 m partout190 let p = tile_path(&dir, 3, 2, 2);191 std::fs::create_dir_all(p.parent().unwrap()).unwrap();192 std::fs::write(&p, ktr::encode(&vec![1200i16; 257 * 257], 257, 0, 6)).unwrap();193 let s = DemStore::new(&dir, 4);194 let e = s.elevation(-73.6, 45.5, 5, 0).unwrap();195 assert_eq!(e, Elevation { metres: 120.0, zoom: 3 });196 assert!(s.elevation(100.0, -30.0, 5, 0).is_none());197 assert!(s.elevation(f64::NAN, 0.0, 5, 0).is_none());198 std::fs::remove_dir_all(&dir).unwrap();199 }200}201