Skip to content

Commit d4595d1

Browse files
authored
feat(raster): read SRTM .hgt and DTED elevation natively (#2076) (#2320)
* feat(raster): read SRTM .hgt and DTED elevation natively (#2076) SRTM tiles (.hgt) and DTED levels 0-2 (.dt0, .dt1, .dt2) now open in pure Rust, on the desktop and in the web app, added by path or uploaded, instead of only through GDAL. An .hgt is placed by its name (N37W122) and checked by its size before it is read; a wrong size or name is refused, saying why. DTED follows MIL-PRF-89020B: signed-magnitude heights, the spacing zones, and the checksum of each column. A column with a damaged header or a wrong checksum, or one a cut-short file doesn't hold, is read as no data and counted in a notice. Voids are no data, with a count. Each layer says once that its heights are above the EGM96 geoid (mean sea level), not the WGS 84 ellipsoid. Large files are read at a step within the memory budget. * fix(dted): read columns with wrong checksums, two's complement heights, the DSI's level A column whose checksum doesn't match is read as stored and counted in a notice, since some producers write wrong checksums. Only a damaged record header makes a column no data. Heights that decode below -16000 m are read as two's complement and counted. The DSI's series designator gives the level, and a notice says when the extension disagrees. * fix(hgt): read 0.5 arc-second tiles, center stepped cells on their posts A 7201 x 7201 tile is read too, at a step where the memory budget calls for one. Read at a step, each kept post is now the center of its cell for SRTM and DTED alike. A name with a multi-byte character right after the tile code is refused, and the "may be cut short" hint shows for any size short of the largest tile. * fix(raster): say when a crs or layer given for SRTM or DTED is ignored These files are WGS 84 with one band. A "crs" or "layer" given with layer.addData or layer.addDataBytes, or kept by a project saved when they went through GDAL, is now said to be ignored rather than dropped silently. The read still goes ahead. * fix(python): embed only the elevation files that fit under the limit An .hgt tile (2.9 MB at its smallest) and a DTED level 2 cell (4.3 MB at its smallest) are always over EMBED_LIMIT (2 MiB), so they're added by path. Level 0 (about 34 KB) stays, and so does level 1, which is under the limit from 50 degrees of latitude, where its cells have fewer columns. * refactor(raster): pictures take their read step from step_within read_scan_limited worked out the same power-of-two step as step_within, with the channels sharing the budget. It now calls step_within with the budget divided by the channel count, which gives the same step and the same error past a step of 2^20. * chore: remove the review notes * refactor(raster): move the shared elevation helpers into raster/mod.rs * refactor(raster): one list of the elevation file extensions * refactor(raster): check an SRTM tile's name and size once * fix(dted): read records by place when their counts are numbered differently * fix(raster): an elevation file read at a step keeps its scale exact * fix(hgt): give the nearest tile sizes for a file of the wrong size * fix(raster): say what an ignored crs or layer means for SRTM and DTED * perf(raster): count skipped elevation posts without decoding them * chore: remove the review notes * fix(raster): an elevation file read at a step says its own size; the warp takes the step * test(raster): pin the warp at a step, a fixture for elevation layers A picture read at every second pixel of a 61-pixel-wide file is warped by exactly two file pixels a cell; the old overview ratio was a cell off toward the far edge. A project fixture keeps an .hgt layer with the crs it saved when these went through GDAL, and a .dt1 layer. The SRTM and DTED readers say they're one step that doesn't look at Cancel. * fix(raster): cap elevation reads; refuse DTED tape-layout partial cells The SRTM and DTED readers read no more than the size they checked, so a file that grows in between is refused, not read whole. A DTED partial cell in the magnetic-tape layout counts only the lines with heights and leaves missing posts out of its records (MIL-PRF-89020B 3.11.3.2.2), so fixed-length records would misplace them: it is refused. Partial cells on the full CD-ROM grid read as before, their missing posts as voids. * fix(dted): find a tape-layout partial cell by its DSI counts The UHL counts a full cell on both media (MIL-PRF-89020B 3.12 c); on tape only the DSI counts shrink to the lines with heights. The check compared the UHL's, so it missed real tape files. It now refuses a partial cell whose DSI counts are smaller than the UHL's. A world-file test now also turns a picture read at a step, pinning the turned grid's size at the file's resolution and its exact step. * fix(raster): a turned picture read at a step says its true size Placed by a turned world file, a picture read at every k-th pixel now gives the whole file's size turned at its own resolution, sized as the north-up grid is, not the reduced grid times k (4 × 102 for a 101 × 3 picture that turns to 3 × 101). It keeps its step, as a north-up one now does too, so a later warp scales by exactly k; a turned grid made coarser to fit goes by the sizes' ratio. * docs(raster): say why the SRTM and DTED decode stays on one thread The largest SRTM tile decodes in about 0.12 s in a release build, less than reading its 104 MB from disk; a DTED cell is at most a quarter of that. * fix(data): the capped read sizes its buffer once, when the file's size is known * fix(dted): refuse a partial cell whose file is shorter than its full grid On tape a partial cell with a height on every line counts the whole cell in its DSI too, but its records leave missing posts out (MIL-PRF-89020B 3.11.3.2.2), so the check by counts missed it and its columns were read out of place. The CD-ROM layout always holds every record whole (3.11.3.2.1), so a partial cell whose file is shorter than its full grid is now refused, said as cut short or tape layout, since the two can't be told apart. A complete cell cut short is still read as far as it goes. * fix(dted): refuse record counts that place heights in another column; say voids in two's complement aren't found * fix(dted): refuse a record whose latitude count isn't 0; the notice speaks of longitude counts only * fix(raster): refuse DTED records whose counts would place heights in the wrong column (#2076) Longitude counts are now read by place only when the whole cell counts from 1 (every record its place + 1). Any other count that isn't the record's place is refused, naming the first such record's place and count. Before, a count naming no column (such as every count offset past the cell's last line) or a column with its own record was read by place. The notice now says the counts number the columns from 1, not that they "don't match". A record whose latitude count isn't 0 was already refused; it gets its own test, with a negative count too. The data formats guide no longer says latitude counts are read by place. * fix(analysis): warp a stepped SRTM or DTED grid with each cell on its post Read at a step, these readers center each kept cell on its post, so the warp put every height (step-1)/2 file pixels off. The layer now says where its corner lies in the file's pixels, and the warp uses it both ways. * fix(raster): stream SRTM and DTED tiles from the file instead of holding them whole On the desktop the readers now decode a row (SRTM) or record (DTED) at a time, with the same checks, notices and errors, so a 7201 x 7201 tile peaks at about 2x the file instead of 3x. The browser still reads bytes. * fix(raster): an SRTM or DTED layer drops the crs it ignores, so reopening says it once * docs(raster): the read-step comment in the picture reader says what it is * docs(raster): state what the SRTM and DTED readers hold as a multiple of the file * fix(raster): a DTED file read by path counts bytes added after its size check --------- Co-authored-by: Cory Douglas Martin <4108748+flight1973@users.noreply.github.com>
1 parent 533e875 commit d4595d1

18 files changed

Lines changed: 2118 additions & 43 deletions

File tree

‎apps/rustgis-python/python/rustgis/_embed.py‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,12 @@
2929
#: each change, and some setups cap a message near 10 MB, so this stays small.
3030
EMBED_LIMIT = 2 << 20
3131

32-
# The extensions `layer.addDataBytes` reads from a file's contents.
32+
# The extensions `layer.addDataBytes` reads from a file's contents. (Not `.hgt` or `.dt2`, never
33+
# under EMBED_LIMIT; a `.dt1` cell is under it from 50° of latitude, where its spacing widens.)
3334
_EMBEDDABLE = {
34-
".tif", ".tiff", ".asc", ".geojson", ".json", ".csv", ".tsv", ".txt", ".zip", ".kml", ".kmz",
35-
".gpx", ".parquet", ".geoparquet", ".fgb", ".gpkg", ".mbtiles", ".xlsx", ".xls", ".ods",
36-
".grb", ".grib", ".grb2", ".grib2",
35+
".tif", ".tiff", ".asc", ".dt0", ".dt1", ".geojson", ".json", ".csv", ".tsv", ".txt", ".zip",
36+
".kml", ".kmz", ".gpx", ".parquet", ".geoparquet", ".fgb", ".gpkg", ".mbtiles", ".xlsx",
37+
".xls", ".ods", ".grb", ".grib", ".grb2", ".grib2",
3738
}
3839

3940
#: The page script that frames the app: an anywidget module, also run by the Qt host page.

‎apps/rustgis-web/src/web.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ const DATA_EXTS: &[&str] = &[
6161
"grib",
6262
"grb2",
6363
"grib2",
64+
// SRTM height tiles and DTED are added below (`ELEVATION_EXTENSIONS`).
6465
];
6566
const CANVAS_ID: &str = "rustgis_canvas";
6667
const LOADING_ID: &str = "rustgis_loading";
@@ -1373,7 +1374,10 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e
13731374
} else if purpose == "picture" || marker.is_some() {
13741375
rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Pictures"), &["png", "jpg", "jpeg"])
13751376
} else {
1376-
rfd::AsyncFileDialog::new().add_filter("Vector and raster data", DATA_EXTS)
1377+
rfd::AsyncFileDialog::new().add_filter(
1378+
"Vector and raster data",
1379+
&[DATA_EXTS, &rustgis_ui_egui::rustgis_engine::data::raster::ELEVATION_EXTENSIONS[..]].concat(),
1380+
)
13771381
};
13781382
// Data may come several files at once (photos gather in one layer).
13791383
let many = matches!(purpose, "data" | "shapefile");

‎crates/analysis/src/warp.rs‎

Lines changed: 62 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,9 +222,11 @@ impl Sampler<'_> {
222222
pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result<Raster, String> {
223223
let re = Reproject::new(o.points_crs, o.crs)?;
224224
let (w, h) = (f64::from(r.width), f64::from(r.height));
225-
// An overview's pixels are bigger than the full image's, which the fit is in.
226-
let (sx, sy) = r.overview.map_or((1.0, 1.0), |(fw, fh)| (f64::from(fw) / w, f64::from(fh) / h));
227-
let place = |c: f64, row: f64| fit.to_map(c * sx, row * sy).and_then(|(x, y)| re.forward(x, y));
225+
// An overview's pixels are bigger than the full image's, which the fit is in; a grid of
226+
// posts read at a step also starts before the file's corner (each cell centered on its post).
227+
let (sx, sy) = r.file_pixels();
228+
let (ox, oy) = r.file_origin();
229+
let place = |c: f64, row: f64| fit.to_map(c * sx + ox, row * sy + oy).and_then(|(x, y)| re.forward(x, y));
228230

229231
let [min_x, min_y, max_x, max_y] = footprint(w, h, &place).ok_or("the image's edge can't be placed in the output coordinate system")?;
230232
if o.crs.is_geographic() && max_x - min_x > 180.0 {
@@ -275,7 +277,7 @@ pub fn warp(r: &Raster, fit: &Fit, o: &Options) -> Result<Raster, String> {
275277
let source = |x: f64, y: f64| -> Option<(f64, f64)> {
276278
let (px, py) = re.back(x, y)?;
277279
let (c, row) = fit.to_pixel(px, py)?;
278-
let (c, row) = (c / sx, row / sy);
280+
let (c, row) = ((c - ox) / sx, (row - oy) / sy);
279281
(c.is_finite() && row.is_finite()).then_some((c, row))
280282
};
281283
sampled(None, r, &g, canvas, o.resampling, &source, o.name.clone())
@@ -1206,6 +1208,62 @@ mod tests {
12061208
assert!(out.bands[0].data.iter().all(|v| *v == 10.0 || *v == -9999.0));
12071209
}
12081210

1211+
#[test]
1212+
fn a_picture_read_at_a_step_is_warped_by_the_step_exactly() {
1213+
// A 61-pixel-wide file read at every second pixel: 31 cells, each exactly two of the
1214+
// file's pixels from the corner (61 isn't a multiple of 2, so 61/31 ≈ 1.968 would put
1215+
// the far cells about one cell off). The fit is in the file's pixels; each cell holds
1216+
// the file column it was read from.
1217+
let (w, h) = (31u32, 4u32);
1218+
let data: Vec<f32> = (0..w * h).map(|i| 2.0 * (i % w) as f32).collect();
1219+
let r = scan(w, h, vec![data], ColorHint::Gray, "Float32").read_at_step(2, (61, 7));
1220+
assert_eq!(r.file_pixels(), (2.0, 2.0));
1221+
let map = |c: f64, rw: f64| (500_000.0 + 10.0 * c, 4_000_000.0 - 10.0 * rw);
1222+
let fit = georef::fit(Kind::Affine, &gcps(61.0, 7.0, map)).unwrap();
1223+
let out = warp(&r, &fit, &opts(Some(5.0), Resampling::Nearest)).unwrap();
1224+
let mut checked = 0;
1225+
for col in 0..i64::from(out.width) {
1226+
let p = out.transform.to_world(col as f64 + 0.5, 1.5);
1227+
let Some((c, _)) = fit.to_pixel(p.x, p.y) else { continue };
1228+
// Away from the cells' edges, where nearest could go either way.
1229+
if !(0.2..61.8).contains(&c) || (c % 2.0 - 1.0).abs() < 0.2 || c % 2.0 < 0.2 {
1230+
continue;
1231+
}
1232+
let v = out.value(0, col, 1).unwrap();
1233+
assert_eq!(f64::from(v), 2.0 * (c / 2.0).floor(), "file column {c}");
1234+
checked += 1;
1235+
}
1236+
assert!(checked > 40, "{checked}");
1237+
}
1238+
1239+
#[test]
1240+
fn an_elevation_grid_read_at_a_step_is_warped_with_each_cell_on_its_post() {
1241+
// A 61-post-wide SRTM or DTED grid read at every fourth post: 16 cells, each centered on
1242+
// the post it was read from (file position 4k + 0.5), not starting at it, which put every
1243+
// height 1.5 file pixels off. Each cell holds the file column it was read from.
1244+
let (w, h) = (16u32, 4u32);
1245+
let data: Vec<f32> = (0..w * h).map(|i| 4.0 * (i % w) as f32).collect();
1246+
let r = scan(w, h, vec![data], ColorHint::Gray, "Float32").posts_read_at_step(4, (61, 13));
1247+
assert_eq!(r.file_origin(), (-1.5, -1.5));
1248+
let map = |c: f64, rw: f64| (500_000.0 + 10.0 * c, 4_000_000.0 - 10.0 * rw);
1249+
let fit = georef::fit(Kind::Affine, &gcps(61.0, 13.0, map)).unwrap();
1250+
let out = warp(&r, &fit, &opts(Some(5.0), Resampling::Nearest)).unwrap();
1251+
let mut checked = 0;
1252+
for col in 0..i64::from(out.width) {
1253+
let p = out.transform.to_world(col as f64 + 0.5, 5.5);
1254+
let Some((c, _)) = fit.to_pixel(p.x, p.y) else { continue };
1255+
// The nearest post kept, away from the cells' edges (halfway between two of them).
1256+
let k = (c - 0.5) / 4.0;
1257+
if !(0.0..60.5).contains(&c) || (k - k.floor() - 0.5).abs() < 0.05 {
1258+
continue;
1259+
}
1260+
let v = out.value(0, col, 5).unwrap();
1261+
assert_eq!(f64::from(v), 4.0 * k.round(), "file column {c}");
1262+
checked += 1;
1263+
}
1264+
assert!(checked > 100, "{checked}");
1265+
}
1266+
12091267
#[test]
12101268
fn hostile_fits_and_options_are_refused() {
12111269
let r = scan(4, 4, vec![vec![1.0; 16]], ColorHint::Gray, "Float32");

0 commit comments

Comments
 (0)