Skip to main content

qualia_geospatial/
lib.rs

1//! QualiaDB Geospatial Engine (`qualia-geospatial`)
2//!
3//! Provides coordinate semantics, geodetic frames, hydro-enforced raster DEM compilation,
4//! Hilbert space-filling curve spatial indexing, OGC WFS/WMS vector and raster streaming,
5//! road/stream corridor generation, linguistic isogloss boundaries, and spatial asset manifests.
6
7pub mod corridor;
8pub mod frame;
9pub mod geotiff;
10pub mod hilbert;
11pub mod isogloss;
12pub mod manifest;
13pub mod raster_m64;
14pub mod wfs;
15pub mod wms_streamer;
16
17pub use corridor::{CorridorKind, HermiteCorridorSegment, SplineControlPoint};
18pub use frame::{
19    GeodeticCoord, GeodeticFrame, SRID_GDA2020, SRID_MGA_ZONE_55, SRID_MGA_ZONE_56,
20    SRID_WEB_MERCATOR, SRID_WGS84, VERTICAL_DATUM_AHD, VERTICAL_DATUM_ELLIPSOIDAL,
21};
22pub use geotiff::{
23    compile_raster_to_m64, compile_raster_to_m64_with_codec, decode_terrain_rgb_mm,
24    decode_terrarium_mm, encode_terrain_rgb, CompressionCodec, ElevationRaster, IngestionError,
25    CHUNK_CELL_COUNT, CHUNK_GRID_SIZE,
26};
27pub use hilbert::{hilbert_to_xy, xy_to_hilbert};
28pub use isogloss::{
29    DiachronicIsogloss, SonicToponymStreamer, SpatioTemporalLect, TimeFrequencyBox,
30};
31pub use manifest::SpatialAssetManifest;
32pub use wfs::{GeologicUnitRecord, GeologicVectorLayer};
33pub use wms_streamer::{
34    TextureArraySlot, TileCoordinate, WmsTileStreamer, MAX_CACHE_LAYERS, TILE_BYTES,
35    TILE_DIMENSION_PX,
36};
37
38#[cfg(test)]
39mod tests {
40    use super::*;
41    use qualia_core_db::q42::m64_matter::{
42        M64ChunkDirectoryEntry, M64Header, M64StrataColumnRecord, M64_MAGIC,
43    };
44
45    #[test]
46    fn test_geodetic_frame_projection_roundtrip() {
47        let frame = GeodeticFrame::default();
48        let target = GeodeticCoord {
49            latitude_deg: -35.795,
50            longitude_deg: 148.315,
51            elevation_ahd_mm: 520_000,
52        };
53
54        let (x_mm, y_mm, z_mm) = frame.project_to_local_mm(&target);
55        assert_eq!(z_mm, 520_000 - 350_000);
56
57        let (unproj_lat, unproj_lon) = frame.unproject_from_local_mm(x_mm, y_mm);
58        assert!((unproj_lat - target.latitude_deg).abs() < 1e-6);
59        assert!((unproj_lon - target.longitude_deg).abs() < 1e-6);
60
61        let dggs_hash = frame.to_dggs_cell_hash(&target, 12);
62        assert_ne!(dggs_hash, 0);
63    }
64
65    #[test]
66    fn test_hilbert_curve_roundtrip() {
67        for x in [0u32, 1, 15, 63, 127] {
68            for y in [0u32, 2, 31, 63, 127] {
69                let d = xy_to_hilbert(x, y, 8);
70                let (rx, ry) = hilbert_to_xy(d, 8);
71                assert_eq!(x, rx);
72                assert_eq!(y, ry);
73            }
74        }
75    }
76
77    #[test]
78    fn test_terrain_rgb_and_terrarium_elevation_roundtrip() {
79        for elev_m in [-400, 0, 350, 1250, 2228] {
80            let elev_mm = elev_m * 1000;
81            let rgb = encode_terrain_rgb(elev_mm);
82            let decoded_mm = decode_terrain_rgb_mm(rgb[0], rgb[1], rgb[2]);
83            assert!((decoded_mm - elev_mm).abs() <= 100);
84        }
85
86        let terrarium_mm = decode_terrarium_mm(128, 0, 0);
87        assert_eq!(terrarium_mm, 0);
88    }
89
90    #[test]
91    fn test_raster_to_m64_compilation() {
92        let frame = GeodeticFrame::default();
93        let width = 64;
94        let height = 64;
95        let elevations = vec![500_000; width * height];
96        let raster = ElevationRaster {
97            width,
98            height,
99            cell_size_mm: 30_000,
100            elevations_mm: &elevations,
101        };
102
103        let mut buffer = vec![0u8; 1_000_000];
104        let bytes_written =
105            compile_raster_to_m64(&raster, &frame, 1, &mut buffer).expect("compilation succeeds");
106
107        assert!(bytes_written > 0);
108
109        let header: &M64Header = bytemuck::from_bytes(&buffer[..std::mem::size_of::<M64Header>()]);
110        assert_eq!(header.magic, M64_MAGIC);
111        assert_eq!(header.chunk_count, 1);
112        assert!(header.validate().is_ok());
113
114        let dir_offset = std::mem::size_of::<M64Header>();
115        let dir_entry: &M64ChunkDirectoryEntry = bytemuck::from_bytes(
116            &buffer[dir_offset..dir_offset + std::mem::size_of::<M64ChunkDirectoryEntry>()],
117        );
118        assert_eq!(dir_entry.srid_geodetic_code, SRID_GDA2020);
119        assert_eq!(dir_entry.record_count, 4096);
120        assert!(dir_entry.validate().is_ok());
121
122        let payload_offset = dir_entry.byte_offset as usize;
123        let strata: &M64StrataColumnRecord = bytemuck::from_bytes(
124            &buffer[payload_offset..payload_offset + std::mem::size_of::<M64StrataColumnRecord>()],
125        );
126        assert_eq!(strata.surface_elevation_mm, 500_000);
127        assert!(strata.validate().is_ok());
128    }
129
130    #[test]
131    fn test_geologic_wfs_unit_code_resolution_and_bank1_recipes() {
132        let layer = GeologicVectorLayer::default();
133
134        assert_eq!(layer.resolve_unit_to_lut_index("Jmb"), Some(128));
135        assert_eq!(layer.resolve_unit_to_lut_index("Gda"), Some(129));
136        assert_eq!(layer.resolve_unit_to_lut_index("Unknown"), None);
137
138        let recipes = layer.compile_bank_1_recipes();
139        assert_eq!(recipes[0].bulk_density_kg_m3, 2850);
140        assert_eq!(recipes[1].bulk_density_kg_m3, 2680);
141        assert!(recipes[0].validate().is_ok());
142        assert!(recipes[1].validate().is_ok());
143    }
144
145    #[test]
146    fn test_wms_tile_streamer_lru_and_addressing() {
147        let mut streamer = WmsTileStreamer::default();
148        let coord1 = TileCoordinate {
149            zoom: 12,
150            x: 3820,
151            y: 2450,
152        };
153        let coord2 = TileCoordinate {
154            zoom: 12,
155            x: 3821,
156            y: 2450,
157        };
158
159        let slot1 = streamer.allocate_slot(&coord1);
160        let slot2 = streamer.allocate_slot(&coord2);
161        assert_ne!(slot1, slot2);
162
163        assert_eq!(streamer.lookup_tile(&coord1), Some(slot1));
164        assert_eq!(streamer.lookup_tile(&coord2), Some(slot2));
165    }
166
167    #[test]
168    fn test_hermite_corridor_conformer() {
169        let p0 = SplineControlPoint {
170            pos_xy_mm: [0.0, 0.0],
171            elevation_mm: 500_000,
172            tangent_xy: [1000.0, 0.0],
173        };
174        let p1 = SplineControlPoint {
175            pos_xy_mm: [1000.0, 0.0],
176            elevation_mm: 510_000,
177            tangent_xy: [1000.0, 0.0],
178        };
179
180        let road = HermiteCorridorSegment {
181            p0,
182            p1,
183            kind: CorridorKind::Road {
184                width_mm: 8000,
185                crown_height_mm: 150,
186            },
187        };
188        let mut road_col = M64StrataColumnRecord::default();
189        road_col.surface_elevation_mm = 505_000;
190        assert!(road.conform_strata_column(500.0, 0.0, &mut road_col));
191        assert_eq!(road_col.layer_compaction_pct[0], 240);
192        assert!(road_col.validate().is_ok());
193    }
194
195    #[test]
196    fn test_spatial_asset_manifest_ntriples() {
197        let manifest = SpatialAssetManifest::new_snowy_ga_dem(0x0123_4567_89AB_CDEF);
198        let ntriples = manifest.to_ntriples();
199        assert!(ntriples.contains("eco:SpatialAsset/AU-GA-DEM-Talbingo"));
200        assert!(ntriples.contains("https://creativecommons.org/licenses/by/4.0/"));
201        assert!(ntriples.contains("7844"));
202        assert!(ntriples.contains("Htj2kWavelet"));
203        assert!(ntriples.contains("POLYGON(("));
204        assert!(ntriples.contains("R84400123"));
205    }
206
207    #[test]
208    fn test_sonic_toponym_streamer_and_doppler() {
209        let frame = GeodeticFrame::default();
210        let sacred_site = GeodeticCoord {
211            latitude_deg: -35.78,
212            longitude_deg: 148.29,
213            elevation_ahd_mm: 350_000,
214        };
215
216        let tf_box = TimeFrequencyBox {
217            start_nanos: 0,
218            end_nanos: 4_000_000_000, // 4-second oral chant
219            min_freq_hz: 110.0,
220            max_freq_hz: 1200.0,
221            harmonic_mask: 0x1F,
222            _padding: 0,
223        };
224
225        let streamer = SonicToponymStreamer::new(
226            sacred_site,
227            tf_box,
228            0xCAFE_BABE,
229            85.0, // 85 dB SPL at 1m
230        );
231
232        // Listener 100m away
233        let listener_100m = GeodeticCoord {
234            latitude_deg: -35.7809,
235            longitude_deg: 148.29,
236            elevation_ahd_mm: 350_000,
237        };
238
239        let spl_100m = streamer.evaluate_listener_spl_db(&listener_100m, &frame);
240        // Inverse-square law: 20 * log10(100) = 40 dB attenuation -> ~45 dB
241        assert!(spl_100m > 40.0 && spl_100m < 50.0);
242
243        // Doppler shift: listener approaching at 34.3 m/s (~123 km/h, 0.1 Mach)
244        let approach_factor = streamer.evaluate_doppler_factor(
245            [0.0, 34.3, 0.0], // Heading north towards source
246            &listener_100m,
247            &frame,
248        );
249        // Pitch rises by ~10% (factor ~1.10)
250        assert!((approach_factor - 1.10).abs() < 0.02);
251    }
252}