Skip to content
Merged
55 changes: 42 additions & 13 deletions crates/analysis/src/texture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,28 @@ pub const PAD: usize = 64;
/// items that a small model is shaded in a few looks at Cancel.
const BLOCK_CELLS: usize = 1 << 16;

/// The most padded cells a model may take: the column pass holds two padded grids of complex
/// 32-bit numbers at once, 8 bytes a padded cell each and 16 for both, the whole of the 16 bytes a
/// cell that [`max_pixels`] plans: half as many leaves room for the model, the output and the
/// percentiles' copy beside them.
fn max_padded_cells() -> usize {
padded_cells_within(max_pixels())
}

/// The padded cells a plan of `pixels` cells (16 bytes each) holds: half of them.
fn padded_cells_within(pixels: usize) -> usize {
pixels / 2
}

/// The padded sides of a `w` × `h` model, each mirrored [`PAD`] cells out and grown to small
/// factors: `None` when a side or their product is past `limit`. A side past the limit on its own
/// is refused before it is padded, so the sum can't overflow.
fn padded_size(w: usize, h: usize, limit: usize) -> Option<(usize, usize)> {
let side = |n: usize| (n <= limit).then(|| smooth(n + 2 * PAD));
let (pw, ph) = (side(w)?, side(h)?);
(pw <= limit && ph <= limit && pw.saturating_mul(ph) <= limit).then_some((pw, ph))
}

/// The fractional Laplacian of band `b` of `r` with exponent `alpha`: positive on ridges, negative
/// in valleys, in the band's unit per metre^α, [`NODATA`] where the band has none. Cells are
/// measured in metres ([`Raster::cell_size_m`]: a geographic model at its middle's latitude, a
Expand All @@ -43,7 +65,8 @@ pub fn texture(r: &Raster, b: usize, alpha: f64) -> Result<Vec<f32>, String> {
/// Three passes, each by blocks of rows on the threads: the padded model is read and its rows transformed;
/// each column is transformed, filtered and transformed back; then each row of the model is
/// transformed back. Beyond the model and the output, it holds two padded grids of complex
/// 32-bit numbers (16 bytes a padded cell), the first only until the columns are taken from it.
/// 32-bit numbers (8 bytes a padded cell each, 16 for both), the first only until the columns
/// are taken from it; [`max_padded_cells`] plans for both.
pub(crate) fn texture_on(threads: Option<usize>, r: &Raster, b: usize, alpha: f64) -> Result<Vec<f32>, String> {
if !(alpha.is_finite() && alpha > 0.0) {
return Err("alpha must be a number more than 0".into());
Expand All @@ -66,19 +89,13 @@ pub(crate) fn texture_on(threads: Option<usize>, r: &Raster, b: usize, alpha: f6
if !(cx.is_finite() && cy.is_finite() && cx > 0.0 && cy > 0.0) {
return Err(format!("{}'s cells have no size", r.name));
}
let too_large = || {
format!(
"{} is too large for texture shading: with its margins, more than the {} cells this computer can hold",
r.name,
max_pixels()
)
let limit = max_padded_cells();
Comment thread
giswqs marked this conversation as resolved.
Resolved
let Some((pw, ph)) = padded_size(w, h, limit) else {
return Err(format!(
"{} is too large for texture shading: with its margins, more than the {limit} cells this computer can hold; clip it to a smaller area first",
r.name
));
};
// A side past the limit on its own is refused before it is padded, so the sum can't overflow.
let side = |n: usize| (n <= max_pixels()).then(|| smooth(n + 2 * PAD));
let (Some(pw), Some(ph)) = (side(w), side(h)) else { return Err(too_large()) };
if pw.saturating_mul(ph) > max_pixels() {
return Err(too_large());
}
let mut planner = FftPlanner::<f32>::new();
let (row_fwd, row_inv) = (planner.plan_fft_forward(pw), planner.plan_fft_inverse(pw));
let (col_fwd, col_inv) = (planner.plan_fft_forward(ph), planner.plan_fft_inverse(ph));
Expand Down Expand Up @@ -199,6 +216,18 @@ mod tests {
use super::*;
use rustgis_data::raster::{ColorHint, Crs, GeoTransform};

/// The padded size is refused one cell past the limit and kept at it, a side past it on its
/// own included; the limit plans for both complex grids, not one.
#[test]
fn the_padded_size_keeps_to_its_limit() {
let (pw, ph) = (smooth(100 + 2 * PAD), smooth(40 + 2 * PAD));
let at = pw * ph;
assert_eq!(padded_size(100, 40, at), Some((pw, ph)));
assert_eq!(padded_size(100, 40, at - 1), None);
assert_eq!(padded_size(usize::MAX, 1, at), None, "a side past the limit isn't padded");
assert_eq!(padded_cells_within(64 << 20), 32 << 20, "two grids of 8 bytes a cell, and room beside them, against a plan of 16");
}

/// A `width × height` grid of 30 m × 20 m cells in UTM 23S, each `z(col, row)`, -9999 its no-data.
fn dem(width: u32, height: u32, z: impl Fn(f64, f64) -> f64) -> Raster {
dem_in(Crs::Epsg(32723), (30., 20.), width, height, z)
Expand Down
5 changes: 1 addition & 4 deletions crates/assistant/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -569,10 +569,7 @@ impl Session {
if let Some(t) = u.pointer("/content/text").and_then(Value::as_str) {
// A message past MAX_TEXT is cut there: the agent's output is untrusted.
let room = MAX_TEXT.saturating_sub(self.text.len());
let mut end = t.len().min(room);
while !t.is_char_boundary(end) {
end -= 1;
}
let end = t.floor_char_boundary(room);
self.text.push_str(t.get(..end).unwrap_or(""));
}
Vec::new()
Expand Down
10 changes: 2 additions & 8 deletions crates/assistant/src/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,7 @@ fn cut_results(rs: &mut [ToolResult]) -> bool {
let mut changed = false;
for r in rs.iter_mut() {
if r.content.len() > TRIMMED_RESULT {
let mut end = TRIMMED_RESULT - TRIMMED_SUFFIX.len();
while !r.content.is_char_boundary(end) {
end -= 1;
}
let end = r.content.floor_char_boundary(TRIMMED_RESULT - TRIMMED_SUFFIX.len());
r.content = format!("{}{TRIMMED_SUFFIX}", r.content.get(..end).unwrap_or_default());
changed = true;
}
Expand Down Expand Up @@ -222,10 +219,7 @@ pub fn as_text_with_limit(turns: &[Turn], upto: usize, limit: usize) -> String {
remaining -= text.len();
chunks.push(text);
} else {
let mut start = text.len().saturating_sub(remaining);
while !text.is_char_boundary(start) {
start += 1;
}
let start = text.ceil_char_boundary(text.len().saturating_sub(remaining));
chunks.push(text.get(start..).unwrap_or_default().to_string());
omitted = true;
break;
Expand Down
2 changes: 1 addition & 1 deletion crates/assistant/src/provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1118,7 +1118,7 @@ impl StreamPreview {
self.text.push_str(&self.delta(&v));
// Previews stay small: the whole reply is read separately.
if self.text.len() > MAX_RESPONSE {
let cut = (0..=MAX_RESPONSE).rev().find(|i| self.text.is_char_boundary(*i)).unwrap_or(0);
let cut = self.text.floor_char_boundary(MAX_RESPONSE);
self.text.truncate(cut);
}
}
Expand Down
14 changes: 9 additions & 5 deletions crates/assistant/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1065,11 +1065,7 @@ fn loss_forms(losses: &[Value]) -> Vec<(Value, bool)> {

/// The first `max` bytes of `text`, cut at a character boundary.
fn clip_bytes(text: &str, max: usize) -> String {
let mut end = max.min(text.len());
while !text.is_char_boundary(end) {
end -= 1;
}
text[..end].to_string()
text.get(..text.floor_char_boundary(max)).unwrap_or_default().to_string()
Comment thread
giswqs marked this conversation as resolved.
Resolved
}

/// A failed command's error, cleaned of login values, with what the command said before failing
Expand Down Expand Up @@ -1536,6 +1532,14 @@ mod tests {
use super::*;
Comment thread
giswqs marked this conversation as resolved.
Resolved
use rustgis_engine::render::rustgis_tiles::logins;

/// A clip keeps whole characters: one straddling the limit is dropped, not cut.
#[test]
fn clip_bytes_drops_a_character_straddling_the_limit() {
assert_eq!(clip_bytes("aé", 2), "a");
assert_eq!(clip_bytes("aé", 3), "aé");
assert_eq!(clip_bytes("abc", 10), "abc");
}

#[test]
fn results_carry_plain_addresses_not_login_wrappers() {
let mut s = Session::new(rustgis_engine::Project::default());
Expand Down
12 changes: 12 additions & 0 deletions crates/data/src/filegdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,18 @@ pub(crate) fn crs_of_code(code: u32) -> Option<Crs> {
Crs::from_epsg(code).or_else(|| crate::raster::crs::esri_crs(code))
}

/// An ArcGIS `spatialReference`'s system and code: the first of its `latestWkid` and `wkid` that
/// [`crs_of_code`] knows, so a newer code RustGIS can't read falls back to the older one.
pub(crate) fn arcgis_code(reference: &serde_json::Value) -> Option<(Crs, u32)> {
arcgis_codes(reference).find_map(|c| Some((crs_of_code(c)?, c)))
}

/// An ArcGIS `spatialReference`'s codes, `latestWkid` then `wkid`, each a nonzero `u32`.
pub(crate) fn arcgis_codes(reference: &serde_json::Value) -> impl Iterator<Item = u32> {
let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok()).filter(|c| *c != 0);
[code("latestWkid"), code("wkid")].into_iter().flatten()
}

/// One table as a dataset: `None` for a table with no rows and no fields worth showing. `wkid` is
/// its coordinate system's code, when the item definitions give one.
/// Reads a table and its row index, keeping typed attributes and reporting invalid or rounded dates.
Expand Down
2 changes: 2 additions & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ pub mod ogc;
pub mod osm;
pub mod photo;
pub mod png;
#[cfg(not(target_arch = "wasm32"))]
pub mod process;
pub mod progress;
pub mod provenance;
#[cfg(not(target_arch = "wasm32"))]
Expand Down
36 changes: 33 additions & 3 deletions crates/data/src/ogc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2694,7 +2694,11 @@ fn merc_to_lonlat(x: f64, y: f64) -> (f64, f64) {
fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> {
let f = |k: &str| e.get(k).and_then(|v| v.as_f64());
let (x0, y0, x1, y1) = (f("xmin")?, f("ymin")?, f("xmax")?, f("ymax")?);
let wkid = e.pointer("/spatialReference/latestWkid").or_else(|| e.pointer("/spatialReference/wkid")).and_then(|w| w.as_i64())?;
// The first of latestWkid and wkid that RustGIS reads, as a layer's own system is chosen: an
// extent it can't convert in that system has no box, not one read in the other.
let mercator = |c: u32| matches!(c, 3857 | 102100 | 102113 | 900913);
let wkid = crate::filegdb::arcgis_codes(e.get("spatialReference")?)
.find(|c| *c == 4326 || mercator(*c) || crate::filegdb::crs_of_code(*c).is_some())?;
match wkid {
4326 => lonlat_box(x0, y0, x1, y1),
3857 | 102100 | 102113 | 900913 => {
Expand All @@ -2704,7 +2708,7 @@ fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> {
}
// Another system RustGIS reads: its box converted, its edges followed.
_ => {
let crs = crate::filegdb::crs_of_code(u32::try_from(wkid).ok()?)?;
let crs = crate::filegdb::crs_of_code(wkid)?;
let b = crs.to(crate::raster::Crs::LonLat).ok()?.extent(&rustgis_geom::Extent { min_x: x0, min_y: y0, max_x: x1, max_y: y1 });
if b.is_empty() {
return None;
Expand All @@ -2717,7 +2721,11 @@ fn arcgis_extent(e: &serde_json::Value) -> Option<[f64; 4]> {
/// Whether a cached map service's tiles are Web Mercator's own pyramid (zoom 0 at 156543 m/px).
fn arcgis_mercator_cache(v: &serde_json::Value) -> bool {
let Some(ti) = v.get("tileInfo") else { return false };
let wkid = ti.pointer("/spatialReference/latestWkid").or_else(|| ti.pointer("/spatialReference/wkid")).and_then(|w| w.as_i64());
// The first of latestWkid and wkid that RustGIS reads, as an extent's code is chosen.
let mercator = |c: u32| matches!(c, 3857 | 102100 | 102113);
let wkid = ti
.get("spatialReference")
.and_then(|r| crate::filegdb::arcgis_codes(r).find(|c| mercator(*c) || crate::filegdb::crs_of_code(*c).is_some()));
let first = ti.pointer("/lods/0/resolution").and_then(|r| r.as_f64());
let level0 = ti.pointer("/lods/0/level").and_then(|l| l.as_i64());
let rows = ti.get("rows").and_then(|r| r.as_i64()).unwrap_or(256);
Expand Down Expand Up @@ -5782,6 +5790,20 @@ mod document_tests;
mod tests {
use super::*;

/// A tile cache's code is the first of latestWkid and wkid that RustGIS reads: one it can't
/// read falls back to Web Mercator's wkid, and one it reads that isn't Web Mercator stays not.
#[test]
fn a_mercator_cache_falls_back_to_its_wkid() {
let cache = |sr: serde_json::Value| serde_json::json!({"tileInfo": {"rows": 256, "spatialReference": sr, "lods": [{"level": 0, "resolution": 156_543.033_928_041}]}});
assert!(arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 3857}))));
assert!(arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 999_999}))));
assert!(!arcgis_mercator_cache(&cache(serde_json::json!({"wkid": 102100, "latestWkid": 4326}))));
// An extent its first readable code can't hold has no box, rather than one read in the other.
let extent =
serde_json::json!({"xmin": 200, "ymin": 40, "xmax": 201, "ymax": 41, "spatialReference": {"latestWkid": 4326, "wkid": 3857}});
assert_eq!(arcgis_extent(&extent), None);
}

#[test]
fn capabilities_and_collections_preserve_only_the_explicit_login() {
let binding = "0123456789abcdef";
Expand Down Expand Up @@ -5975,6 +5997,14 @@ mod tests {
let bern = parse("https://x.org/arcgis/rest/services/A/FeatureServer", lv95.as_bytes()).unwrap();
let [w, so, e, n] = bern.layers[0].bbox.unwrap();
assert!(w < 7.44 && e > 7.44 && so < 46.95 && n > 46.95 && e - w < 2.0 && n - so < 1.5, "{:?}", bern.layers[0].bbox);
// A latestWkid RustGIS doesn't read falls back to the wkid, as a layer's own system does.
let newer = lv95.replace(r#"{"wkid": 2056}"#, r#"{"wkid": 2056, "latestWkid": 999999}"#);
assert_ne!(newer, lv95);
let newer = parse("https://x.org/arcgis/rest/services/A/FeatureServer", newer.as_bytes()).unwrap();
assert_eq!(newer.layers[0].bbox, bern.layers[0].bbox);
// Web Mercator's old and new codes stay Web Mercator.
let [w, so, e, n] = s.layers[0].bbox.unwrap();
assert!((w + 8.98).abs() < 0.01 && so.abs() < 1e-9 && (e - 8.98).abs() < 0.01 && (n - 8.94).abs() < 0.01, "{:?}", s.layers[0].bbox);
// In longitude/latitude, or a system RustGIS doesn't read (said): asked in EPSG:4326.
// A system given only as WKT has no code to ask for it by: said too.
for (sr, note) in [
Expand Down
52 changes: 52 additions & 0 deletions crates/data/src/process.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//! Reading what a program started on the desktop prints, within a limit.

/// The most of a program's standard output, and of its standard error, that is kept.
pub const PIPE_LIMIT: u64 = 64 << 20;

/// What ends a program's messages cut at their limit ([`marked_cut`]).
pub const CUT: &[u8] = b"\n(cut)";

/// `text` kept to `limit` bytes and ended with [`CUT`] when `cut`: for messages that are only
/// shown, so a cut is said rather than refused.
pub fn marked_cut(mut text: Vec<u8>, cut: bool, limit: u64) -> Vec<u8> {
if cut {
text.truncate(usize::try_from(limit).unwrap_or(usize::MAX).saturating_sub(CUT.len()));
text.extend_from_slice(CUT);
}
text
}

/// Reads `pipe` to its end on a thread of its own, keeping its first `limit` bytes and reading
/// the rest into the void, so a program that prints without end can't fill the memory, and
/// can't block on a full pipe either. The thread answers the bytes kept and whether any were
/// left out (or a read failed partway); a thread the system refuses is the error.
pub fn drain_bounded(
mut pipe: impl std::io::Read + Send + 'static,
limit: u64,
) -> std::io::Result<std::thread::JoinHandle<(Vec<u8>, bool)>> {
use std::io::Read as _;
std::thread::Builder::new().spawn(move || {
let mut buf = Vec::new();
let read = pipe.by_ref().take(limit).read_to_end(&mut buf);
let rest = std::io::copy(&mut pipe, &mut std::io::sink());
// A pipe that fails partway counts as cut: what was kept may not be all it held.
(buf, read.is_err() || !matches!(rest, Ok(0)))
})
}

#[cfg(test)]
mod tests {
use super::*;

/// Exactly the limit is kept whole and said uncut; one byte more is cut to the limit and said.
#[test]
fn a_pipe_is_kept_to_its_limit_and_says_when_cut() {
let (kept, cut) = drain_bounded(std::io::Cursor::new(vec![7u8; 10]), 10).unwrap().join().unwrap();
assert_eq!((kept.len(), cut), (10, false));
let (kept, cut) = drain_bounded(std::io::Cursor::new(vec![7u8; 11]), 10).unwrap().join().unwrap();
assert_eq!((kept.len(), cut), (10, true));
assert_eq!(marked_cut(kept.clone(), false, 10), kept);
let marked = marked_cut(kept, true, 10);
assert!(marked.len() == 10 && marked.ends_with(CUT), "{marked:?}");
}
}
3 changes: 1 addition & 2 deletions crates/data/src/source/arcgis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,8 +216,7 @@ pub fn open_now(remote: Arc<Remote>) -> Result<ArcgisSource> {
/// longitude/latitude or one RustGIS can't read, which is asked for in longitude/latitude instead.
fn own_system(description: &serde_json::Value) -> Option<(crate::raster::Crs, crate::raster::Transformer, u32)> {
let reference = description.pointer("/extent/spatialReference").or_else(|| description.get("sourceSpatialReference"))?;
let code = |k: &str| reference.get(k).and_then(serde_json::Value::as_u64).and_then(|c| u32::try_from(c).ok());
let (crs, code) = [code("latestWkid"), code("wkid")].into_iter().flatten().find_map(|c| Some((crate::filegdb::crs_of_code(c)?, c)))?;
let (crs, code) = crate::filegdb::arcgis_code(reference)?;
if crs == crate::raster::Crs::LonLat {
return None;
}
Expand Down
Loading
Loading