Skip to main content

MercatorDem

Struct MercatorDem 

Source
pub struct MercatorDem { /* private fields */ }
Expand description

A contiguous rectangular block of decoded web-mercator (XYZ) DEM tiles, stitched into a single elevation grid and sampleable by longitude / latitude.

The stitched grid is row-major north → south, tiles_x * tile_size columns by tiles_y * tile_size rows. Sampling outside the block clamps to the nearest edge sample, so a halo that slightly overshoots the fetched coverage degrades gracefully rather than panicking — but for correct results the block should cover the target bounds (plus any halo).

Implementations§

Source§

impl MercatorDem

Source

pub fn new( zoom: u8, x0: u32, y0: u32, tiles_x: u32, tiles_y: u32, tile_size: u32, elev: Vec<f32>, ) -> Self

Wrap an already-stitched elevation block.

elev must be row-major north → south with (tiles_x*tile_size) * (tiles_y*tile_size) entries.

§Panics

Panics on a length mismatch, or if any tile dimension is zero.

Source

pub fn from_tiles<F>( zoom: u8, x0: u32, y0: u32, tiles_x: u32, tiles_y: u32, tile_size: u32, get_tile: F, ) -> Self
where F: FnMut(u8, u32, u32) -> Vec<f32>,

Build a block by pulling each XYZ tile through get_tile, which returns that tile’s decoded elevations (tile_size², row-major north → south). The closure is where you do your fetch + heightmap decode; for async callers, pre-fetch into a map and look it up here.

Tiles are requested in row-major order (x0, y0) … (x0+tiles_x-1, y0+tiles_y-1).

§Panics

Panics if any returned tile does not have exactly tile_size² samples.

Examples found in repository?
examples/reproject_terrain.rs (lines 57-64)
23fn main() {
24    let mut a = env::args().skip(1);
25    let tz: u8 = a.next().expect("tms_z").parse().unwrap();
26    let tx: u32 = a.next().expect("tms_x").parse().unwrap();
27    let ty: u32 = a.next().expect("tms_y").parse().unwrap();
28    let src_zoom: u8 = a.next().expect("src_zoom").parse().unwrap();
29    let tile_size: u32 = a.next().expect("tile_size").parse().unwrap();
30    let png_dir = PathBuf::from(a.next().expect("png_dir"));
31    let real = a.next();
32
33    // Target geodetic TMS tile.
34    let (w, s, e, n) = geodetic_tms::tile_to_bounds(tz, tx, ty);
35    let bounds = TileBounds::new(w, s, e, n);
36    let grid_size = tile_size + 1; // 2^n + 1
37    println!("target geodetic TMS z{tz}/{tx}/{ty}  bounds = [{w:.5}, {s:.5}, {e:.5}, {n:.5}]");
38
39    // Widen by ~one geodetic cell so the halo (buffer=1) stays in coverage.
40    let cell_lon = (e - w) / (grid_size - 1) as f64;
41    let cell_lat = (n - s) / (grid_size - 1) as f64;
42    let (x0, y0, ntx, nty) = MercatorDem::tiles_covering(
43        src_zoom,
44        w - cell_lon,
45        s - cell_lat,
46        e + cell_lon,
47        n + cell_lat,
48    );
49    println!(
50        "covering web-mercator z{src_zoom} tiles: x {x0}..{}  y {y0}..{}  ({} tiles, {tile_size}px)",
51        x0 + ntx - 1,
52        y0 + nty - 1,
53        ntx * nty
54    );
55
56    // Build the mercator DEM by reading each covering tile from disk.
57    let dem = MercatorDem::from_tiles(src_zoom, x0, y0, ntx, nty, tile_size, |z, x, y| {
58        let path = png_dir.join(format!("{z}_{x}_{y}.png"));
59        let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("missing tile {path:?}"));
60        let img = decode_image(&bytes).expect("decode png");
61        assert_eq!(img.width, tile_size);
62        assert_eq!(img.height, tile_size);
63        terrarium::decode(&img.rgb, img.width, img.height)
64    });
65
66    // Reproject onto the geodetic grid + a halo grid for seamless normals.
67    let grid = dem.geodetic_grid(&bounds, grid_size);
68    let buffered = dem.buffered_geodetic(&bounds, grid_size, 1);
69
70    let (gmin, gmax) = min_max(&grid);
71    println!("reprojected geodetic grid {grid_size}×{grid_size}: {gmin:.1} .. {gmax:.1} m");
72
73    let bytes = encode_terrain(
74        &grid,
75        grid_size,
76        &bounds,
77        &TerrainOptions {
78            max_error: 4.0,
79            compression_level: 6,
80            normals: NormalMode::BufferedGradient(buffered),
81            ..Default::default()
82        },
83    );
84    let mesh = DecodedMesh::decode(&bytes).expect("decode our output");
85    println!(
86        "ours: {} bytes (gzip), {} verts, {} tris, height {:.1}..{:.1} m, normals={}",
87        bytes.len(),
88        mesh.vertices.len(),
89        mesh.indices.len() / 3,
90        mesh.header.min_height,
91        mesh.header.max_height,
92        mesh.extensions.normals.is_some(),
93    );
94
95    if let Some(path) = real {
96        let raw = std::fs::read(&path).expect("read real .terrain");
97        let rm = DecodedMesh::decode(&raw).expect("decode real");
98        println!(
99            "real: {} bytes, {} verts, {} tris, height {:.1}..{:.1} m, normals={}  ({})",
100            raw.len(),
101            rm.vertices.len(),
102            rm.indices.len() / 3,
103            rm.header.min_height,
104            rm.header.max_height,
105            rm.extensions.normals.is_some(),
106            path,
107        );
108        println!(
109            "note: height offset vs real is expected — real is EGM2008 geoid-blended, ours is raw Terrarium (ellipsoidal)."
110        );
111    }
112
113    println!("\nOK ✅  web-mercator → geodetic-TMS reprojection produced valid .terrain");
114}
Source

pub fn tiles_covering( zoom: u8, west: f64, south: f64, east: f64, north: f64, ) -> (u32, u32, u32, u32)

Range of XYZ tiles at zoom covering a longitude/latitude box, returning (x0, y0, tiles_x, tiles_y).

Widen the box by your halo before calling if you intend to sample a buffer beyond the tile (e.g. for buffered_geodetic).

Examples found in repository?
examples/reproject_terrain.rs (lines 42-48)
23fn main() {
24    let mut a = env::args().skip(1);
25    let tz: u8 = a.next().expect("tms_z").parse().unwrap();
26    let tx: u32 = a.next().expect("tms_x").parse().unwrap();
27    let ty: u32 = a.next().expect("tms_y").parse().unwrap();
28    let src_zoom: u8 = a.next().expect("src_zoom").parse().unwrap();
29    let tile_size: u32 = a.next().expect("tile_size").parse().unwrap();
30    let png_dir = PathBuf::from(a.next().expect("png_dir"));
31    let real = a.next();
32
33    // Target geodetic TMS tile.
34    let (w, s, e, n) = geodetic_tms::tile_to_bounds(tz, tx, ty);
35    let bounds = TileBounds::new(w, s, e, n);
36    let grid_size = tile_size + 1; // 2^n + 1
37    println!("target geodetic TMS z{tz}/{tx}/{ty}  bounds = [{w:.5}, {s:.5}, {e:.5}, {n:.5}]");
38
39    // Widen by ~one geodetic cell so the halo (buffer=1) stays in coverage.
40    let cell_lon = (e - w) / (grid_size - 1) as f64;
41    let cell_lat = (n - s) / (grid_size - 1) as f64;
42    let (x0, y0, ntx, nty) = MercatorDem::tiles_covering(
43        src_zoom,
44        w - cell_lon,
45        s - cell_lat,
46        e + cell_lon,
47        n + cell_lat,
48    );
49    println!(
50        "covering web-mercator z{src_zoom} tiles: x {x0}..{}  y {y0}..{}  ({} tiles, {tile_size}px)",
51        x0 + ntx - 1,
52        y0 + nty - 1,
53        ntx * nty
54    );
55
56    // Build the mercator DEM by reading each covering tile from disk.
57    let dem = MercatorDem::from_tiles(src_zoom, x0, y0, ntx, nty, tile_size, |z, x, y| {
58        let path = png_dir.join(format!("{z}_{x}_{y}.png"));
59        let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("missing tile {path:?}"));
60        let img = decode_image(&bytes).expect("decode png");
61        assert_eq!(img.width, tile_size);
62        assert_eq!(img.height, tile_size);
63        terrarium::decode(&img.rgb, img.width, img.height)
64    });
65
66    // Reproject onto the geodetic grid + a halo grid for seamless normals.
67    let grid = dem.geodetic_grid(&bounds, grid_size);
68    let buffered = dem.buffered_geodetic(&bounds, grid_size, 1);
69
70    let (gmin, gmax) = min_max(&grid);
71    println!("reprojected geodetic grid {grid_size}×{grid_size}: {gmin:.1} .. {gmax:.1} m");
72
73    let bytes = encode_terrain(
74        &grid,
75        grid_size,
76        &bounds,
77        &TerrainOptions {
78            max_error: 4.0,
79            compression_level: 6,
80            normals: NormalMode::BufferedGradient(buffered),
81            ..Default::default()
82        },
83    );
84    let mesh = DecodedMesh::decode(&bytes).expect("decode our output");
85    println!(
86        "ours: {} bytes (gzip), {} verts, {} tris, height {:.1}..{:.1} m, normals={}",
87        bytes.len(),
88        mesh.vertices.len(),
89        mesh.indices.len() / 3,
90        mesh.header.min_height,
91        mesh.header.max_height,
92        mesh.extensions.normals.is_some(),
93    );
94
95    if let Some(path) = real {
96        let raw = std::fs::read(&path).expect("read real .terrain");
97        let rm = DecodedMesh::decode(&raw).expect("decode real");
98        println!(
99            "real: {} bytes, {} verts, {} tris, height {:.1}..{:.1} m, normals={}  ({})",
100            raw.len(),
101            rm.vertices.len(),
102            rm.indices.len() / 3,
103            rm.header.min_height,
104            rm.header.max_height,
105            rm.extensions.normals.is_some(),
106            path,
107        );
108        println!(
109            "note: height offset vs real is expected — real is EGM2008 geoid-blended, ours is raw Terrarium (ellipsoidal)."
110        );
111    }
112
113    println!("\nOK ✅  web-mercator → geodetic-TMS reprojection produced valid .terrain");
114}
Source

pub fn width_px(&self) -> u32

Stitched-grid width in pixels (tiles_x * tile_size).

Source

pub fn height_px(&self) -> u32

Stitched-grid height in pixels (tiles_y * tile_size).

Source

pub fn sample(&self, lon: f64, lat: f64) -> f32

Bilinearly sample the elevation at (lon, lat) in degrees.

Latitude is clamped to the web-mercator limit. Positions outside the fetched block clamp to the nearest edge sample. NaN samples (e.g. missing data filled by the caller) are tolerated: the interpolation falls back to any defined neighbour, returning NaN only if all four corners are NaN.

Source

pub fn geodetic_grid(&self, bounds: &TileBounds, grid_size: u32) -> Vec<f32>

Resample onto a geodetic grid_size × grid_size grid covering bounds, row-major north → south — ready for crate::terrain::encode_terrain.

§Panics

Panics if grid_size < 2.

Examples found in repository?
examples/reproject_terrain.rs (line 67)
23fn main() {
24    let mut a = env::args().skip(1);
25    let tz: u8 = a.next().expect("tms_z").parse().unwrap();
26    let tx: u32 = a.next().expect("tms_x").parse().unwrap();
27    let ty: u32 = a.next().expect("tms_y").parse().unwrap();
28    let src_zoom: u8 = a.next().expect("src_zoom").parse().unwrap();
29    let tile_size: u32 = a.next().expect("tile_size").parse().unwrap();
30    let png_dir = PathBuf::from(a.next().expect("png_dir"));
31    let real = a.next();
32
33    // Target geodetic TMS tile.
34    let (w, s, e, n) = geodetic_tms::tile_to_bounds(tz, tx, ty);
35    let bounds = TileBounds::new(w, s, e, n);
36    let grid_size = tile_size + 1; // 2^n + 1
37    println!("target geodetic TMS z{tz}/{tx}/{ty}  bounds = [{w:.5}, {s:.5}, {e:.5}, {n:.5}]");
38
39    // Widen by ~one geodetic cell so the halo (buffer=1) stays in coverage.
40    let cell_lon = (e - w) / (grid_size - 1) as f64;
41    let cell_lat = (n - s) / (grid_size - 1) as f64;
42    let (x0, y0, ntx, nty) = MercatorDem::tiles_covering(
43        src_zoom,
44        w - cell_lon,
45        s - cell_lat,
46        e + cell_lon,
47        n + cell_lat,
48    );
49    println!(
50        "covering web-mercator z{src_zoom} tiles: x {x0}..{}  y {y0}..{}  ({} tiles, {tile_size}px)",
51        x0 + ntx - 1,
52        y0 + nty - 1,
53        ntx * nty
54    );
55
56    // Build the mercator DEM by reading each covering tile from disk.
57    let dem = MercatorDem::from_tiles(src_zoom, x0, y0, ntx, nty, tile_size, |z, x, y| {
58        let path = png_dir.join(format!("{z}_{x}_{y}.png"));
59        let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("missing tile {path:?}"));
60        let img = decode_image(&bytes).expect("decode png");
61        assert_eq!(img.width, tile_size);
62        assert_eq!(img.height, tile_size);
63        terrarium::decode(&img.rgb, img.width, img.height)
64    });
65
66    // Reproject onto the geodetic grid + a halo grid for seamless normals.
67    let grid = dem.geodetic_grid(&bounds, grid_size);
68    let buffered = dem.buffered_geodetic(&bounds, grid_size, 1);
69
70    let (gmin, gmax) = min_max(&grid);
71    println!("reprojected geodetic grid {grid_size}×{grid_size}: {gmin:.1} .. {gmax:.1} m");
72
73    let bytes = encode_terrain(
74        &grid,
75        grid_size,
76        &bounds,
77        &TerrainOptions {
78            max_error: 4.0,
79            compression_level: 6,
80            normals: NormalMode::BufferedGradient(buffered),
81            ..Default::default()
82        },
83    );
84    let mesh = DecodedMesh::decode(&bytes).expect("decode our output");
85    println!(
86        "ours: {} bytes (gzip), {} verts, {} tris, height {:.1}..{:.1} m, normals={}",
87        bytes.len(),
88        mesh.vertices.len(),
89        mesh.indices.len() / 3,
90        mesh.header.min_height,
91        mesh.header.max_height,
92        mesh.extensions.normals.is_some(),
93    );
94
95    if let Some(path) = real {
96        let raw = std::fs::read(&path).expect("read real .terrain");
97        let rm = DecodedMesh::decode(&raw).expect("decode real");
98        println!(
99            "real: {} bytes, {} verts, {} tris, height {:.1}..{:.1} m, normals={}  ({})",
100            raw.len(),
101            rm.vertices.len(),
102            rm.indices.len() / 3,
103            rm.header.min_height,
104            rm.header.max_height,
105            rm.extensions.normals.is_some(),
106            path,
107        );
108        println!(
109            "note: height offset vs real is expected — real is EGM2008 geoid-blended, ours is raw Terrarium (ellipsoidal)."
110        );
111    }
112
113    println!("\nOK ✅  web-mercator → geodetic-TMS reprojection produced valid .terrain");
114}
Source

pub fn buffered_geodetic( &self, bounds: &TileBounds, tile_grid_size: u32, buffer: u32, ) -> BufferedElevations

Resample onto a halo-extended geodetic grid — a BufferedElevations for crate::terrain::NormalMode::BufferedGradient.

The inner tile_grid_size × tile_grid_size block matches geodetic_grid; the surrounding buffer-cell strip is sampled from the neighbour area (so make sure this MercatorDem was built to cover bounds widened by the halo).

§Panics

Panics if tile_grid_size < 2.

Examples found in repository?
examples/reproject_terrain.rs (line 68)
23fn main() {
24    let mut a = env::args().skip(1);
25    let tz: u8 = a.next().expect("tms_z").parse().unwrap();
26    let tx: u32 = a.next().expect("tms_x").parse().unwrap();
27    let ty: u32 = a.next().expect("tms_y").parse().unwrap();
28    let src_zoom: u8 = a.next().expect("src_zoom").parse().unwrap();
29    let tile_size: u32 = a.next().expect("tile_size").parse().unwrap();
30    let png_dir = PathBuf::from(a.next().expect("png_dir"));
31    let real = a.next();
32
33    // Target geodetic TMS tile.
34    let (w, s, e, n) = geodetic_tms::tile_to_bounds(tz, tx, ty);
35    let bounds = TileBounds::new(w, s, e, n);
36    let grid_size = tile_size + 1; // 2^n + 1
37    println!("target geodetic TMS z{tz}/{tx}/{ty}  bounds = [{w:.5}, {s:.5}, {e:.5}, {n:.5}]");
38
39    // Widen by ~one geodetic cell so the halo (buffer=1) stays in coverage.
40    let cell_lon = (e - w) / (grid_size - 1) as f64;
41    let cell_lat = (n - s) / (grid_size - 1) as f64;
42    let (x0, y0, ntx, nty) = MercatorDem::tiles_covering(
43        src_zoom,
44        w - cell_lon,
45        s - cell_lat,
46        e + cell_lon,
47        n + cell_lat,
48    );
49    println!(
50        "covering web-mercator z{src_zoom} tiles: x {x0}..{}  y {y0}..{}  ({} tiles, {tile_size}px)",
51        x0 + ntx - 1,
52        y0 + nty - 1,
53        ntx * nty
54    );
55
56    // Build the mercator DEM by reading each covering tile from disk.
57    let dem = MercatorDem::from_tiles(src_zoom, x0, y0, ntx, nty, tile_size, |z, x, y| {
58        let path = png_dir.join(format!("{z}_{x}_{y}.png"));
59        let bytes = std::fs::read(&path).unwrap_or_else(|_| panic!("missing tile {path:?}"));
60        let img = decode_image(&bytes).expect("decode png");
61        assert_eq!(img.width, tile_size);
62        assert_eq!(img.height, tile_size);
63        terrarium::decode(&img.rgb, img.width, img.height)
64    });
65
66    // Reproject onto the geodetic grid + a halo grid for seamless normals.
67    let grid = dem.geodetic_grid(&bounds, grid_size);
68    let buffered = dem.buffered_geodetic(&bounds, grid_size, 1);
69
70    let (gmin, gmax) = min_max(&grid);
71    println!("reprojected geodetic grid {grid_size}×{grid_size}: {gmin:.1} .. {gmax:.1} m");
72
73    let bytes = encode_terrain(
74        &grid,
75        grid_size,
76        &bounds,
77        &TerrainOptions {
78            max_error: 4.0,
79            compression_level: 6,
80            normals: NormalMode::BufferedGradient(buffered),
81            ..Default::default()
82        },
83    );
84    let mesh = DecodedMesh::decode(&bytes).expect("decode our output");
85    println!(
86        "ours: {} bytes (gzip), {} verts, {} tris, height {:.1}..{:.1} m, normals={}",
87        bytes.len(),
88        mesh.vertices.len(),
89        mesh.indices.len() / 3,
90        mesh.header.min_height,
91        mesh.header.max_height,
92        mesh.extensions.normals.is_some(),
93    );
94
95    if let Some(path) = real {
96        let raw = std::fs::read(&path).expect("read real .terrain");
97        let rm = DecodedMesh::decode(&raw).expect("decode real");
98        println!(
99            "real: {} bytes, {} verts, {} tris, height {:.1}..{:.1} m, normals={}  ({})",
100            raw.len(),
101            rm.vertices.len(),
102            rm.indices.len() / 3,
103            rm.header.min_height,
104            rm.header.max_height,
105            rm.extensions.normals.is_some(),
106            path,
107        );
108        println!(
109            "note: height offset vs real is expected — real is EGM2008 geoid-blended, ours is raw Terrarium (ellipsoidal)."
110        );
111    }
112
113    println!("\nOK ✅  web-mercator → geodetic-TMS reprojection produced valid .terrain");
114}

Trait Implementations§

Source§

impl Clone for MercatorDem

Source§

fn clone(&self) -> MercatorDem

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MercatorDem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.