Skip to main content

qualia_core_db/domains/geospatial/
terrain_pipeline.rs

1//! DEM heightfield → terrain mesh → geodetically anchored scene coordinates (P1).
2
3use super::dem::{generate_terrain_mesh, TerrainMesh};
4use super::geodetic::{ecef_to_enu, lat_lon_alt_to_ecef};
5
6/// A terrain tile positioned at a geodetic anchor.
7#[derive(Debug, Clone)]
8pub struct GeodeticTerrainTile {
9    pub mesh: TerrainMesh,
10    /// Scene-space ENU origin for this tile (metres).
11    pub enu_origin: (f64, f64, f64),
12    /// Geodetic centre of the tile.
13    pub centre_lat: f64,
14    pub centre_lon: f64,
15    pub centre_alt_m: f64,
16}
17
18/// Build a terrain mesh from a heightfield and anchor it relative to a world origin.
19pub fn compile_terrain_tile(
20    heightfield: &[f32],
21    width: usize,
22    height: usize,
23    cell_size_m: f64,
24    centre_lat: f64,
25    centre_lon: f64,
26    centre_alt_m: f64,
27    world_origin_lat: f64,
28    world_origin_lon: f64,
29    world_origin_alt_m: f64,
30) -> GeodeticTerrainTile {
31    let mesh = generate_terrain_mesh(heightfield, width, height, cell_size_m);
32
33    let (cx, cy, cz) = lat_lon_alt_to_ecef(centre_lat, centre_lon, centre_alt_m);
34    let enu = ecef_to_enu(
35        cx,
36        cy,
37        cz,
38        world_origin_lat,
39        world_origin_lon,
40        world_origin_alt_m,
41    );
42
43    GeodeticTerrainTile {
44        mesh,
45        enu_origin: enu,
46        centre_lat,
47        centre_lon,
48        centre_alt_m,
49    }
50}
51
52use crate::container_10d::header::Container10dHeader;
53use crate::container_10d::integrity::seal_whole_file_crc32c;
54use crate::container_10d::mesh_section::{encode_mesh_section, encoded_len};
55use crate::container_10d::provenance_section::{encode_provenance_section, ProvenanceSidecar};
56use crate::container_10d::section::{encode_container, AlignmentTier, SectionInput, SectionType};
57use crate::render::assets::Mesh;
58use sha2::{Digest, Sha256};
59use std::time::{SystemTime, UNIX_EPOCH};
60
61/// Compiles a DEM heightfield into a native `.10d` QuantizedMesh tensor file,
62/// wrapping it with CBOR-LD provenance for full compliance.
63pub fn compile_and_encode_10d_tile(
64    heightfield: &[f32],
65    width: usize,
66    height: usize,
67    cell_size_m: f64,
68    source_bytes: Vec<u8>,
69    licence: String,
70    cbor_ld_metadata: Vec<u8>,
71) -> Result<Vec<u8>, String> {
72    compile_and_encode_10d_tile_with_media_type(
73        heightfield,
74        width,
75        height,
76        cell_size_m,
77        source_bytes,
78        "application/octet-stream".into(),
79        licence,
80        cbor_ld_metadata,
81    )
82}
83
84/// Compile and encode a georeferenced heightfield with an explicit source media type.
85pub fn compile_and_encode_10d_tile_with_media_type(
86    heightfield: &[f32],
87    width: usize,
88    height: usize,
89    cell_size_m: f64,
90    source_bytes: Vec<u8>,
91    source_media_type: String,
92    licence: String,
93    cbor_ld_metadata: Vec<u8>,
94) -> Result<Vec<u8>, String> {
95    validate_heightfield(heightfield, width, height, cell_size_m)?;
96
97    // 1. Generate standard TerrainMesh
98    let terrain = generate_terrain_mesh(heightfield, width, height, cell_size_m);
99
100    // 2. Convert to render::assets::Mesh
101    let mut triangles = Vec::with_capacity(terrain.indices.len() / 3);
102    for chunk in terrain.indices.chunks_exact(3) {
103        triangles.push([chunk[0], chunk[1], chunk[2]]);
104    }
105    let mut min = [f32::INFINITY; 3];
106    let mut max = [f32::NEG_INFINITY; 3];
107    for p in &terrain.vertices {
108        for i in 0..3 {
109            if p[i] < min[i] {
110                min[i] = p[i];
111            }
112            if p[i] > max[i] {
113                max[i] = p[i];
114            }
115        }
116    }
117    if terrain.vertices.is_empty() {
118        min = [0.0; 3];
119        max = [0.0; 3];
120    }
121
122    let render_mesh = Mesh {
123        positions: terrain.vertices,
124        triangles,
125        min,
126        max,
127    };
128
129    // 3. Encode QuantizedMesh Section
130    let mesh_need = encoded_len(render_mesh.positions.len(), render_mesh.triangles.len());
131    let mut mesh_payload = vec![0u8; mesh_need];
132    let mesh_size =
133        encode_mesh_section(&render_mesh, &mut mesh_payload).map_err(|e| e.to_string())?;
134    mesh_payload.truncate(mesh_size);
135
136    // 4. Build Provenance Sidecar
137    let now = SystemTime::now()
138        .duration_since(UNIX_EPOCH)
139        .map_err(|error| format!("system clock predates Unix epoch: {error}"))?
140        .as_secs();
141    let version_hash: [u8; 32] = Sha256::digest(&source_bytes).into();
142    let mut sidecar = ProvenanceSidecar::new(source_bytes, source_media_type, licence);
143    sidecar.semantic_metadata = cbor_ld_metadata;
144    sidecar.timestamp_epoch_s = now;
145    sidecar.version_hash = version_hash;
146
147    let sidecar_need = sidecar.source_bytes.len()
148        + sidecar.source_media_type.len()
149        + sidecar.licence.len()
150        + sidecar.vc.len()
151        + sidecar.semantic_metadata.len()
152        + 1024;
153    let mut sidecar_payload = vec![0u8; sidecar_need];
154    let sidecar_size =
155        encode_provenance_section(&sidecar, &mut sidecar_payload).map_err(|e| e.to_string())?;
156    sidecar_payload.truncate(sidecar_size);
157
158    // 5. Encode 10D Container
159    let h = Container10dHeader::proposed();
160    let inputs = [
161        SectionInput {
162            section_type: SectionType::QuantizedMesh,
163            alignment_tier: AlignmentTier::Word,
164            stride: 0,
165            element_count: 0,
166            payload: &mesh_payload,
167        },
168        SectionInput {
169            section_type: SectionType::ProvenanceSidecar,
170            alignment_tier: AlignmentTier::Word,
171            stride: 0,
172            element_count: 0,
173            payload: &sidecar_payload,
174        },
175    ];
176
177    // Allocate 10D container size plus header padding
178    let mut out = vec![0u8; mesh_size + sidecar_size + 1024];
179    let n = encode_container(&h, &inputs, &mut out).map_err(|e| e.to_string())?;
180    out.truncate(n);
181
182    seal_whole_file_crc32c(&mut out);
183
184    Ok(out)
185}
186
187fn validate_heightfield(
188    heightfield: &[f32],
189    width: usize,
190    height: usize,
191    cell_size_m: f64,
192) -> Result<(), String> {
193    let expected = width
194        .checked_mul(height)
195        .ok_or_else(|| "heightfield dimensions overflow".to_string())?;
196    if width < 2 || height < 2 || heightfield.len() != expected {
197        return Err(format!(
198            "heightfield needs at least 2x2 samples and exactly width*height values (got {} values for {width}x{height})",
199            heightfield.len()
200        ));
201    }
202    if !cell_size_m.is_finite() || cell_size_m <= 0.0 {
203        return Err("terrain cell size must be finite and greater than zero".into());
204    }
205    if heightfield.iter().any(|elevation| !elevation.is_finite()) {
206        return Err("heightfield contains a non-finite elevation sample".into());
207    }
208    Ok(())
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn terrain_tile_has_enu_origin() {
217        let heights = vec![0.0f32; 9];
218        let tile = compile_terrain_tile(
219            &heights, 3, 3, 10.0, -33.8688, 151.2093, 0.0, -33.8688, 151.2093, 0.0,
220        );
221        assert_eq!(tile.mesh.vertices.len(), 9);
222        assert!((tile.enu_origin.0).abs() < 1.0);
223        assert!((tile.enu_origin.1).abs() < 1.0);
224    }
225}