diff --git a/crates/data/src/export/tests.rs b/crates/data/src/export/tests.rs index 5e44f7f763..f6d515b490 100644 --- a/crates/data/src/export/tests.rs +++ b/crates/data/src/export/tests.rs @@ -481,8 +481,9 @@ fn a_streamed_export_into_an_existing_geopackage_starts_again_inside_its_transac assert_eq!((e.written, table), (20, Some(GpkgWritten { table: "both".into(), replaced: false, dependents: vec![] }))); let whole = d.join("whole.gpkg"); crate::io::write_path(&both, &whole).unwrap(); - let read = - |p: &Path, t: &str| crate::source::open_path(p, Some(t)).unwrap().read(&Request { extent: None, limit: 100 }).unwrap().features; + let read = |p: &Path, t: &str| { + crate::source::open_path(p, Some(t)).unwrap().read(&Request { extent: None, limit: 100, own: None }).unwrap().features + }; assert_eq!(read(&county, "both"), read(&whole, "both")); assert_eq!(read(&county, "parcels").len(), 1); let c = rusqlite::Connection::open(&county).unwrap(); diff --git a/crates/data/src/source/arcgis/tests.rs b/crates/data/src/source/arcgis/tests.rs index 06b014f609..88c499d8d9 100644 --- a/crates/data/src/source/arcgis/tests.rs +++ b/crates/data/src/source/arcgis/tests.rs @@ -246,7 +246,7 @@ fn a_view_is_read_whole_over_several_pages_with_object_ids_as_ids() { let src = open_blocking(&query).unwrap(); assert_eq!((src.info.format, src.info.count, src.info.crs.as_str()), (FORMAT, Some(FEATURES), "EPSG:4326")); assert_eq!(src.info.extent, Extent::new(-100.0, 40.0, -99.05, 40.95)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); let want: Vec = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect(); assert_eq!(ids(&b), want); assert!(b.complete && b.matched == 16); @@ -256,7 +256,7 @@ fn a_view_is_read_whole_over_several_pages_with_object_ids_as_ids() { fn a_view_holding_more_than_the_limit_reads_every_kth_feature_spread_over_it() { let (query, _) = service("live-sample.test", 30, true, None); let src = open_blocking(&query).unwrap(); - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50, own: None }).unwrap(); assert!(!b.complete && b.matched == FEATURES); // 400 over 50 is 8: every 8th object id, across the whole grid. assert!(b.features.len() == 50 && b.features.iter().all(|f| f.id % 8 == 0), "{:?}", ids(&b)); @@ -271,7 +271,7 @@ fn a_view_holding_more_than_the_limit_reads_every_kth_feature_spread_over_it() { fn a_view_read_again_asks_the_service_nothing() { let (query, asked) = service("live-again.test", 5, true, None); let src: Arc = Arc::new(open_blocking(&query).unwrap()); - let req = Request { extent: Some(small_view()), limit: 1000 }; + let req = Request { extent: Some(small_view()), limit: 1000, own: None }; let first = super::super::read_blocking(&src, &req).unwrap(); let before = asked.count.load(Ordering::Relaxed); let again = super::super::read_blocking(&src, &req).unwrap(); @@ -284,10 +284,10 @@ fn a_service_that_cant_sample_gives_its_first_features_and_says_so() { let (query, _) = service("live-nosql.test", 30, false, None); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.iter().any(|n| n.contains("standardized SQL")), "{:?}", src.info.notes); - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 50, own: None }).unwrap(); assert!(!b.complete && b.matched == FEATURES && !b.features.is_empty() && b.features.len() <= 50); // A view within the limit is read whole, whatever its cells hold. - let all = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let all = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(all.complete && all.features.len() == FEATURES as usize, "{}", all.features.len()); } @@ -360,7 +360,7 @@ fn views_anywhere_never_panic_and_ask_for_a_few_cells() { ]; for v in views { let before = asked.count.load(Ordering::Relaxed); - let b = super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100 }); + let b = super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100, own: None }); assert!(b.is_ok(), "{v:?}: {b:?}"); assert!(asked.count.load(Ordering::Relaxed) - before <= 64, "{v:?}"); } @@ -368,12 +368,13 @@ fn views_anywhere_never_panic_and_ask_for_a_few_cells() { assert!(cells(&v).len() <= 25, "{v:?}"); } // Outside the world: nothing, said to be all of it. - let outside = super::super::read_blocking(&src, &Request { extent: Some(Extent::new(200.0, 0.0, 210.0, 10.0)), limit: 100 }).unwrap(); + let outside = + super::super::read_blocking(&src, &Request { extent: Some(Extent::new(200.0, 0.0, 210.0, 10.0)), limit: 100, own: None }).unwrap(); assert!(outside.complete && outside.features.is_empty()); // No view at all: an error, never an empty answer, and nothing asked. let before = asked.count.load(Ordering::Relaxed); for v in [Extent::new(f64::NAN, 0.0, 1.0, 1.0), Extent::new(0.0, f64::INFINITY, 1.0, 1.0), Extent::new(5.0, 5.0, -5.0, -5.0)] { - assert!(super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100 }).is_err(), "{v:?}"); + assert!(super::super::read_blocking(&src, &Request { extent: Some(v), limit: 100, own: None }).is_err(), "{v:?}"); let mut visit = |_: Vec| Ok(()); assert!(src.visit_chunks(Some(v), 4 << 10, &mut visit).is_err(), "{v:?}"); } @@ -386,12 +387,12 @@ fn what_pages_lose_is_said_by_each_read_and_none_when_nothing_is() { let (query, _) = service_with("live-z.test", Opts { z: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.info.zm_dropped && src.info.notes == vec![crate::zm_note(None)], "{:?}", src.info.notes); - assert!(read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap().notes.is_empty()); + assert!(read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap().notes.is_empty()); // Values each page loses: said by each read, a view's counted in its pages. let (query, _) = service_with("live-utf8.test", Opts { bad_text: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.is_empty(), "{:?}", src.info.notes); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!( b.notes.len() == 1 && b.notes[0].contains("UTF-8") && b.notes[0].ends_with("counted in the pages read for the view"), "{:?}", @@ -404,7 +405,7 @@ fn what_pages_lose_is_said_by_each_read_and_none_when_nothing_is() { let (query, _) = service("live-clean.test", 30, true, None); let src = open_blocking(&query).unwrap(); assert!(src.info.notes.is_empty(), "{:?}", src.info.notes); - assert!(read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap().notes.is_empty()); + assert!(read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap().notes.is_empty()); } #[test] @@ -432,7 +433,7 @@ fn sampling_steps_are_powers_of_two() { fn a_query_without_geometry_still_reads_its_views() { let (query, _) = service("live-nogeometry.test", 30, true, None); let src = open_blocking(&format!("{query}&returnGeometry=false")).unwrap(); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.len() == 16 && b.features.iter().all(|f| f.geometry.is_some())); } @@ -441,7 +442,7 @@ fn empty_pages_naming_no_fields_are_read_as_empty() { let (query, _) = service_with("live-emptypages.test", Opts { empty_without_fields: true, ..Opts::default() }); let src = open_blocking(&query).unwrap(); // Every 256th: one feature (256) in all, so most cells' sampled pages are empty. - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 2 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 2, own: None }).unwrap(); assert_eq!(ids(&b), vec![256]); assert!(!b.complete); } @@ -450,8 +451,8 @@ fn empty_pages_naming_no_fields_are_read_as_empty() { fn a_budgeted_view_stays_within_its_bytes_as_it_is_read_and_spread_over_it() { let (query, _) = service("live-budget.test", 30, true, None); let src = open_blocking(&query).unwrap(); - let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }; - let all = read(&src, Request { extent: whole.extent, limit: 1000 }).unwrap(); + let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }; + let all = read(&src, Request { extent: whole.extent, limit: 1000, own: None }).unwrap(); let bytes = super::super::memory::features_bytes(&all.features) / 5; let shared: Arc = Arc::new(open_blocking(&query).unwrap()); // Fetched first, as the map's reads are, then read within the budget. @@ -476,7 +477,7 @@ fn a_layer_matching_nothing_opens_and_reads_empty() { let src = open_blocking(&query.replace("where=1%3D1", "where=1%3D0")).unwrap(); // Its geometry from the layer's description, as no feature says it. assert_eq!((src.info.count, src.info.geometry_type), (Some(0), crate::GeometryType::Point)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.is_empty() && b.matched == 0); let mut visited = 0; let all = src @@ -498,14 +499,14 @@ fn a_view_larger_than_the_answers_kept_is_read_in_part_without_running_out_of_ro let (query, _) = service_with(host, Opts { page: 30, padded: true, sql, ..Opts::default() }); let src = open_blocking(&query).unwrap(); assert!(src.page() < 30 && src.page() * 10_600 < remote::MAX_ANSWER as usize, "{}", src.page()); - let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }; + let whole = Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }; let b = read(&src, whole).unwrap(); assert!(!b.complete && b.matched == FEATURES && !b.features.is_empty() && b.features.len() < FEATURES as usize, "{host}"); assert_eq!(b.features.iter().map(|f| f.id).collect::>().len(), b.features.len()); // Read again, it asks for what it read before. assert_eq!(ids(&read(&src, whole).unwrap()), ids(&b), "{host}"); // A view whose answers fit (its cells hold a few of the large features) is read whole. - let fits = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let fits = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(fits.complete && fits.features.len() == 16, "{host}: {}", fits.features.len()); } } @@ -537,7 +538,7 @@ fn pages_whose_answers_are_too_large_are_asked_for_again_shorter() { assert_eq!(src.page(), 30); // The whole grid: cells of many features, whose pages of 30 are too large (read by a source // of its own, which shortens its own pages). - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(!b.features.is_empty()); let mut visited = Vec::new(); src.visit_chunks(None, 64 << 10, &mut |c| { @@ -594,7 +595,7 @@ fn counts_past_any_layer_never_overflow() { let src = open_blocking(&query).unwrap(); assert_eq!(src.info.count, Some(u64::MAX)); // An answer, read or refused, whatever it is: never a panic. - let _ = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }); + let _ = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }); let _ = src.visit_chunks(None, 4 << 10, &mut |_| Ok(())); } @@ -612,7 +613,7 @@ fn features_counted_but_not_sent_are_said_and_leave_the_read_incomplete() { assert!(!all.complete && visited == 390, "{visited}"); assert!(all.notes.iter().any(|n| n.contains("10 features more than it sent")), "{:?}", all.notes); // A view read whole, but for what the service didn't send. - let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(Extent::new(-101.0, 39.0, -99.0, 41.0)), limit: 1000, own: None }).unwrap(); assert!(!b.complete && b.features.len() == 390, "{}", b.features.len()); assert!(b.notes.iter().any(|n| n.contains("more than it sent")), "{:?}", b.notes); } @@ -636,7 +637,7 @@ fn a_layer_matching_nothing_may_answer_with_no_bytes() { let (query, _) = service_with("live-nobytes.test", Opts { empty_body: true, ..Opts::default() }); let src = open_blocking(&query.replace("where=1%3D1", "where=1%3D0")).unwrap(); assert_eq!(src.info.count, Some(0)); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert!(b.complete && b.features.is_empty()); } @@ -649,7 +650,7 @@ fn a_layer_is_read_in_its_own_system() { let src = open_blocking(&query).unwrap(); assert_eq!((src.coord_crs(), src.info.crs.as_str()), (crate::raster::Crs::WebMercator, "EPSG:3857")); let before = asked.count.load(Ordering::Relaxed); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); let want: Vec = (3..=6).flat_map(|row| (2..=5).map(move |col| row * 20 + col + 1)).collect(); assert_eq!(ids(&b), want); let pages: Vec = asked.since(before).into_iter().filter(|u| u.contains("resultOffset")).collect(); @@ -678,7 +679,7 @@ fn a_layer_is_read_in_its_own_system() { let (query, _) = service_with(host, opts); let src = open_blocking(&query).unwrap(); assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat, "{host}"); - assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap()), want, "{host}"); + assert_eq!(ids(&read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap()), want, "{host}"); } // A code RustGIS doesn't read: longitude/latitude, as before. let description = r#"{"name":"Points","objectIdField":"OBJECTID","maxRecordCount":30,"supportedQueryFormats":"PBF","geometryType":"esriGeometryPoint", @@ -686,7 +687,7 @@ fn a_layer_is_read_in_its_own_system() { let (query, asked) = service("unknown-system.test", 30, true, Some(description)); let src = open_blocking(&query).unwrap(); assert_eq!(src.coord_crs(), crate::raster::Crs::LonLat); - let b = read(&src, Request { extent: Some(small_view()), limit: 1000 }).unwrap(); + let b = read(&src, Request { extent: Some(small_view()), limit: 1000, own: None }).unwrap(); assert_eq!(ids(&b), want); assert!(asked.since(0).iter().filter(|u| u.contains("resultOffset")).all(|u| u.contains("outSR=4326"))); } diff --git a/crates/data/src/source/duckdb.rs b/crates/data/src/source/duckdb.rs index 64084a4add..dc8e3b92c8 100644 --- a/crates/data/src/source/duckdb.rs +++ b/crates/data/src/source/duckdb.rs @@ -1672,7 +1672,7 @@ mod tests { let dropped = |f: Family| zm.parts.iter().find(|p| p.family == f).map(|p| (p.count, p.zm_dropped)); assert_eq!((dropped(Family::Points), dropped(Family::Lines)), (Some((3, 2)), Some((1, 1)))); let line_source = open(&lines.path); - let line_batch = line_source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let line_batch = line_source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(line_batch.features.len(), 1); assert_eq!(line_batch.features[0].geometry.as_ref().unwrap().kind(), crate::GeometryType::Polyline); assert_eq!(line_batch.features[0].geometry.as_ref().unwrap().extent(), rustgis_geom::Extent::new(0.0, 0.0, 1.0, 1.0)); @@ -1683,10 +1683,12 @@ mod tests { assert_eq!(info.fields.iter().map(|f| f.name.as_str()).collect::>(), vec!["id", "name", "day", "seen"]); assert_eq!(info.fields[2].ty, crate::FieldType::Date); assert_eq!(info.fields[3].ty, crate::FieldType::DateTime); - let b = pts.read(&crate::source::Request { extent: Some(rustgis_geom::Extent::new(10.5, 20.5, 12.0, 22.0)), limit: 10 }).unwrap(); + let b = pts + .read(&crate::source::Request { extent: Some(rustgis_geom::Extent::new(10.5, 20.5, 12.0, 22.0)), limit: 10, own: None }) + .unwrap(); assert_eq!(b.features.len(), 1, "the extent query reads the covering"); assert_eq!(b.features[0].geometry.as_ref().unwrap().extent(), rustgis_geom::Extent::new(11.0, 21.0, 11.0, 21.0)); - let all_points = pts.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let all_points = pts.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(all_points.features.len(), 2); assert!(all_points.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == crate::GeometryType::Point)); let days: Vec = all_points.features.iter().map(|f| f.attrs[2].to_string()).collect(); @@ -1697,7 +1699,7 @@ mod tests { let sql = "SELECT 1 AS id, DATE 'infinity' AS d, TIMESTAMP 'infinity' AS t, TIMESTAMP_S '-infinity' AS s, \ TIMESTAMP_MS 'infinity' AS ms, TIMESTAMPTZ 'infinity' AS tz, ST_Point(1, 2) AS geom"; let out = run_in(&cache, &Query { sql, ..Query::default() }, false).unwrap(); - let infinite = open(&out.parts[0].path).read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let infinite = open(&out.parts[0].path).read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(infinite.features.len(), 1); assert_eq!(infinite.unread_dates, [0, 1, 1, 1, 1, 1]); // A nanosecond timestamp is a timestamp, rounded to the microsecond and counted. @@ -1709,7 +1711,7 @@ mod tests { nanos.info().fields.iter().map(|f| f.ty).collect::>(), [crate::FieldType::Integer, crate::FieldType::DateTime, crate::FieldType::DateTime] ); - let batch = nanos.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = nanos.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert!(batch.unread_dates.is_empty()); assert_eq!(batch.rounded_dates, [0, 1]); assert_eq!(batch.features[0].attrs[1].to_string(), "2026-03-05T12:34:56.123457"); @@ -1723,7 +1725,7 @@ mod tests { // placed where it is in longitude/latitude… let first = |path: &Path| { let source = open(path); - let batch = source.read(&crate::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 1, own: None }).unwrap(); let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; (source.coord_crs(), c, source.info().extent) }; diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 1684fe934b..6ebb37d5f3 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -354,7 +354,7 @@ impl FgbSource { /// counts features and checks Cancel between them. fn read_with(&self, open: &impl Fn() -> Result, req: &Request, scan: bool) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -398,12 +398,12 @@ impl FgbSource { if !late && !sample.wants() { continue; } - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(req) || (late && !sample.wants()) { + if !geometry.inside || (late && !sample.wants()) { continue; } let geometry = geometry.geometry; @@ -438,7 +438,7 @@ impl FgbSource { extent: Option, chunks: &mut super::chunk_memory::Chunker<'_>, ) -> Result { - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let reader = open_reader(open()?)?; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let indexed = native.filter(|_| self.info.indexed); @@ -464,12 +464,13 @@ impl FgbSource { crate::progress::step(1)?; n += 1; let id = numbers.as_ref().and_then(|v| v.get(usize::try_from(n - 1).unwrap_or(usize::MAX)).copied()).unwrap_or(n); - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = + f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, &req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(&req) { + if !geometry.inside { continue; } let geometry = geometry.geometry; @@ -682,7 +683,7 @@ impl FgbSource { /// spatial read scans every candidate within the budget, counting features and checking Cancel. fn read_remote(&self, f: &Arc, req: &Request) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -777,12 +778,13 @@ impl FgbSource { continue; } let id = hits.items.get(this).map(|(_, i)| i + 1).unwrap_or(this as u64 + 1); - let geometry = feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.read(g)); + let geometry = + feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; }; - if !geometry.in_request(req) || (late && !sample.wants()) { + if !geometry.inside || (late && !sample.wants()) { continue; } let geometry = geometry.geometry; @@ -826,6 +828,10 @@ impl FeatureSource for FgbSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() diff --git a/crates/data/src/source/gdal.rs b/crates/data/src/source/gdal.rs index b6e956cff8..b3d7517082 100644 --- a/crates/data/src/source/gdal.rs +++ b/crates/data/src/source/gdal.rs @@ -631,12 +631,12 @@ fn convert_one_in(dir: &Path, src: &Path, layer: &str, request: ConversionReques // A read failure is not an empty dataset. Never install a corrupt or partially readable // conversion as a successful replacement. let source = super::open_path(&tmp, None)?; - Ok::<_, DataError>(!source.read(&super::Request { extent: None, limit: 1 })?.features.is_empty()) + Ok::<_, DataError>(!source.read(&super::Request { extent: None, limit: 1, own: None })?.features.is_empty()) } else { Ok(tmp.exists() && super::open_path(&tmp, None) .ok() - .is_some_and(|s| s.read(&super::Request { extent: None, limit: 1 }).is_ok_and(|b| !b.features.is_empty()))) + .is_some_and(|s| s.read(&super::Request { extent: None, limit: 1, own: None }).is_ok_and(|b| !b.features.is_empty()))) } })?; // The entry is replaced in an order that never leaves it naming a missing file: the new state @@ -922,7 +922,7 @@ mod tests { }; let first = |path: &Path| { let source = super::super::open_path(path, None).unwrap(); - let batch = source.read(&super::super::Request { extent: None, limit: 1 }).unwrap(); + let batch = source.read(&super::super::Request { extent: None, limit: 1, own: None }).unwrap(); let Some(crate::Geometry::Point(c)) = batch.features.into_iter().next().unwrap().geometry else { panic!() }; (source.coord_crs(), c) }; @@ -1130,7 +1130,7 @@ mod tests { for (path, workspace) in [(&again[0].path, None), (&fresh.path, Some(fresh.workspace.clone()))] { let source = super::super::fgb::FgbSource::open_converted_path(path, "mixed", &kml, workspace).unwrap(); let captured = crate::provenance::Capture::start(); - source.read(&super::super::Request { extent: None, limit: 1 }).unwrap(); + source.read(&super::super::Request { extent: None, limit: 1, own: None }).unwrap(); source.visit_chunks(None, 1024, &mut |_| Ok(())).unwrap(); assert_eq!(captured.inputs().iter().map(|i| &i.path).collect::>(), vec![&kml.display().to_string()]); } @@ -1168,7 +1168,7 @@ mod tests { let (converted, notes) = convert_in(&dir.path().join("cache"), &path, None, None).unwrap(); assert_eq!(converted.len(), 1); let source = super::super::open_path(&converted[0].path, None).unwrap(); - let batch = source.read(&super::super::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&super::super::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 1); assert_eq!(batch.skipped, 0, "GDAL dropped the feature before RustGIS read it"); if lossy { @@ -1271,7 +1271,7 @@ mod tests { assert_eq!(fresh.notes.iter().any(|n| n.contains("Z or M coordinates on 1 source feature")), lossy); assert_eq!(fresh.zm_dropped, lossy); let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features[0].geometry.as_ref().unwrap().extent().center().x, if lossy { 2.0 } else { 8.0 }); } // A layer of points with Z, two of its three features with only XY: the one with Z is @@ -1308,7 +1308,7 @@ mod tests { assert!(fresh.notes.is_empty(), "{:?}", fresh.notes); } let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 3); assert_eq!(batch.skipped, 0, "diagnostic occurrences are not skipped-feature counts"); assert!(batch.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == GeometryType::Point)); @@ -1348,7 +1348,7 @@ mod tests { assert!(fresh.notes.is_empty(), "single-family input has no conversion losses: {:?}", fresh.notes); } let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 1); assert_eq!(batch.features[0].geometry.as_ref().unwrap().kind(), GeometryType::Point); } @@ -1445,7 +1445,7 @@ mod tests { } assert_eq!(fresh.zm_dropped, lossy); let source = crate::source::open_path(&fresh.path, None).unwrap(); - let batch = source.read(&crate::source::Request { extent: None, limit: 10 }).unwrap(); + let batch = source.read(&crate::source::Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(batch.features.len(), 2); assert!(batch.features.iter().all(|f| f.geometry.as_ref().unwrap().kind() == GeometryType::Point)); } diff --git a/crates/data/src/source/geojson.rs b/crates/data/src/source/geojson.rs index 932b1b7dba..ff48277804 100644 --- a/crates/data/src/source/geojson.rs +++ b/crates/data/src/source/geojson.rs @@ -316,6 +316,10 @@ impl FeatureSource for GeoJsonSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -337,7 +341,7 @@ impl FeatureSource for GeoJsonSource { /// A changed file invalidates the saved bounds and offsets, even for records the bounds /// would skip. A successful visit uses the same file version as the index. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; let mut f = BufReader::with_capacity(BUFFER, crate::provenance::open(&self.path)?); @@ -372,7 +376,7 @@ impl FeatureSource for GeoJsonSource { fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); // Counted first, then sampled, unless the native box is refused: no list of every match. - let extent = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let extent = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && extent.is_none() { return Err(super::unbounded_count()); @@ -445,17 +449,19 @@ impl GeoJsonSource { let place = self.places.get(i as usize).ok_or(())?; let json = read_place(f, pos, buf, place).ok_or(())?; let geometry = geojson_geometry(&json).map_err(|_| ())?; - // Kept as the file holds it, in its own system; its box in longitude/latitude answers the - // request. - let lonlat = match (self.reproject.transformer(), &geometry) { - (Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), - (_, g) => g.as_ref().map(crate::Geometry::extent), + // Kept as the file holds it, in its own system; its own box answers a request given in + // that system ([`Request::own`]), else its box in longitude/latitude. + let own = self.reproject.own_box(req); + let placed = match (own, self.reproject.transformer(), &geometry) { + (Some(_), _, g) => g.as_ref().map(crate::Geometry::extent), + (None, Some(t), Some(g)) => Some(lonlat_box(g, t).ok_or(())?), + (None, _, g) => g.as_ref().map(crate::Geometry::extent), }; // One without geometry doesn't match an extent. - let outside = match (&lonlat, &req.extent) { + let outside = match (&placed, own.or(req.extent)) { (_, None) => false, (None, Some(_)) => true, - (Some(e), Some(r)) => !e.intersects(r), + (Some(e), Some(r)) => !e.intersects(&r), }; if outside || !wanted() { return Ok(None); diff --git a/crates/data/src/source/gpkg.rs b/crates/data/src/source/gpkg.rs index e7b1706127..a6f86f2dbc 100644 --- a/crates/data/src/source/gpkg.rs +++ b/crates/data/src/source/gpkg.rs @@ -412,8 +412,8 @@ impl GpkgSource { { return Ok(Row::Skip); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { return Ok(Row::Bad) }; - if !placed.in_request(req) { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, req)) else { return Ok(Row::Bad) }; + if !placed.inside { return Ok(Row::Skip); } Ok(Row::Feature(Feature { id, geometry: Some(placed.geometry), attrs: attrs() })) @@ -433,6 +433,10 @@ impl FeatureSource for GpkgSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -450,7 +454,7 @@ impl FeatureSource for GpkgSource { let limit = clamp_limit(req.limit); let guard = self.conn.lock().map_err(|_| DataError::Format("GeoPackage connection poisoned".into()))?; let conn = guard.as_ref().ok_or_else(|| DataError::Format("GeoPackage connection closed".into()))?; - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -566,7 +570,7 @@ impl FeatureSource for GpkgSource { // An upload's SQLite copy is generated; its bytes were supplied by the caller. let conn = if self.temp.is_some() { crate::provenance::without(|| open_db(path)) } else { open_db(path) }?; same_file()?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let sql = format!("SELECT {} FROM {}", self.select_list(), quote(&self.table)); let mut st = conn.prepare(&sql).map_err(err)?; diff --git a/crates/data/src/source/gpkg/edit.rs b/crates/data/src/source/gpkg/edit.rs index 1f4a61e8fd..3b82085fd6 100644 --- a/crates/data/src/source/gpkg/edit.rs +++ b/crates/data/src/source/gpkg/edit.rs @@ -1244,7 +1244,7 @@ mod tests { assert_eq!(saved.changes.deleted, 0, "trigger-only deletion is not a submitted deletion"); let source = GpkgSource::open(&path, Some("roads")).unwrap(); for (x, expected) in [(30.5, vec![2]), (60.5, vec![7]), (4.5, vec![])] { - let batch = source.read(&Request { extent: Some(Extent::new(x, 1.0, x + 0.1, 4.0)), limit: 100 }).unwrap(); + let batch = source.read(&Request { extent: Some(Extent::new(x, 1.0, x + 0.1, 4.0)), limit: 100, own: None }).unwrap(); assert_eq!(batch.features.iter().map(|f| f.id).collect::>(), expected, "indexed={indexed}"); } let bounds: (f64, f64, f64, f64) = conn diff --git a/crates/data/src/source/gpkg_mem.rs b/crates/data/src/source/gpkg_mem.rs index ad1721491e..48a9ac6df0 100644 --- a/crates/data/src/source/gpkg_mem.rs +++ b/crates/data/src/source/gpkg_mem.rs @@ -335,6 +335,10 @@ impl FeatureSource for GpkgMemSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -344,7 +348,7 @@ impl FeatureSource for GpkgMemSource { /// Counts scanned records and checks Cancel between them. fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -394,11 +398,11 @@ impl FeatureSource for GpkgMemSource { if known && !sample.wants() { return ControlFlow::Continue(()); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, req)) else { skipped += 1; return ControlFlow::Continue(()); }; - if !placed.in_request(req) || (!known && !sample.wants()) { + if !placed.inside || (!known && !sample.wants()) { return ControlFlow::Continue(()); } let geometry = placed.geometry; @@ -436,7 +440,7 @@ impl FeatureSource for GpkgMemSource { /// and a Cancel check between records. fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut out = Batch { complete: true, ..Batch::default() }; // The visitor's error, which stops the scan. @@ -459,11 +463,11 @@ impl FeatureSource for GpkgMemSource { { return ControlFlow::Continue(()); } - let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.read(g)) else { + let Some(placed) = wkb::decode(body).and_then(|g| self.reproject.place(g, &req)) else { out.skipped += 1; return ControlFlow::Continue(()); }; - if !placed.in_request(&req) { + if !placed.inside { return ControlFlow::Continue(()); } Some(placed.geometry) diff --git a/crates/data/src/source/mod.rs b/crates/data/src/source/mod.rs index 946d58cf11..2ab9f63b00 100644 --- a/crates/data/src/source/mod.rs +++ b/crates/data/src/source/mod.rs @@ -219,12 +219,17 @@ impl SourceInfo { pub struct Request { pub extent: Option, pub limit: usize, + /// The same box in a projected system, when the asker has it there exactly (a map in that + /// system gives its view in map units), with `extent` its longitude/latitude bounds. A source + /// whose own system ([`FeatureSource::coord_crs`]) it is tests each feature's own box against + /// it, converting nothing; any other source reads `extent`, as without it. + pub own: Option<(Crs, Extent)>, } impl Request { /// Every feature, up to [`MAX_LIMIT`]. pub fn all() -> Self { - Request { extent: None, limit: MAX_LIMIT } + Request { extent: None, limit: MAX_LIMIT, own: None } } } @@ -417,6 +422,15 @@ pub trait FeatureSource: Send + Sync { fn coord_crs(&self) -> crate::raster::Crs { crate::raster::Crs::LonLat } + + /// Whether a read given its box in the source's own system ([`Request::own`]) tests its + /// features against that box (a file read in place, PostGIS), so a map in that system keeps + /// its window in map units for it. A source that reads by the longitude/latitude extent + /// whatever it is given (another database, a service, a converted copy) says no: its window is + /// kept in longitude/latitude, as it reads. + fn reads_own_box(&self) -> bool { + false + } /// The encoding the source's text values are read in, for the notice of those that aren't /// valid in it ([`not_utf8_note`]). fn text_encoding(&self) -> &'static str { @@ -679,6 +693,10 @@ impl FeatureSource for Fetching { self.0.coord_crs() } + fn reads_own_box(&self) -> bool { + self.0.reads_own_box() + } + fn lost_to_crs(&self) -> bool { self.0.lost_to_crs() } @@ -819,7 +837,7 @@ fn read_chunks(src: &dyn FeatureSource, budget: u64) -> Result { /// The geometry type of a source that doesn't declare one, from its first feature. pub(crate) fn peek_kind(src: &dyn FeatureSource) -> GeometryType { - src.read(&Request { extent: None, limit: 1 }) + src.read(&Request { extent: None, limit: 1, own: None }) .ok() .and_then(|b| b.features.into_iter().find_map(|f| f.geometry)) .map(|g| g.kind()) @@ -960,7 +978,7 @@ impl Reproject { /// A geometry as the file holds it, kept in the source's own coordinates /// ([`Reproject::crs`]), with its box in longitude/latitude for a request's extent to test - /// ([`Placed::in_request`]); `None` when a coordinate can't be converted to longitude/latitude, + /// ([`Reproject::place`]); `None` when a coordinate can't be converted to longitude/latitude, /// as a feature that can't be placed is left out. Each coordinate is converted to be checked, /// none is kept converted. pub(crate) fn read(&self, g: Geometry) -> Option { @@ -977,6 +995,40 @@ impl Reproject { ok.then_some(Placed { geometry: g, lonlat }) } + /// A geometry as the file holds it, kept in the source's own coordinates, and whether it is + /// within `req`. Given the request's box in those coordinates ([`Request::own`]), its own box + /// is tested against it, converting nothing, so a geometry with no place in + /// longitude/latitude is kept too (`None` for one with a coordinate that isn't a number). + /// Otherwise as [`Reproject::read`]: `None` when a coordinate can't be converted to + /// longitude/latitude, and its box there tested against the extent. + pub(crate) fn place(&self, g: Geometry, req: &Request) -> Option { + if let Some(own) = self.own_box(req) { + // A coordinate that isn't a number has no place here either: left out, as `read` + // leaves it out, for the reader to count. + if !g.is_finite() { + return None; + } + let inside = g.extent().intersects(&own); + return Some(Fitted { geometry: g, inside }); + } + let Placed { geometry, lonlat } = self.read(g)?; + let inside = req.extent.is_none_or(|e| lonlat.intersects(&e)); + Some(Fitted { geometry, inside }) + } + + /// The request's box in the source's own coordinates, when the asker gave it there + /// ([`Request::own`]) and they are projected. + pub(crate) fn own_box(&self, req: &Request) -> Option { + req.own.filter(|(crs, _)| self.t.is_some() && *crs == self.crs).map(|(_, e)| e) + } + + /// The request's box in the source's own coordinates, for an index to narrow by: the one the + /// asker gave there ([`Request::own`]), else its extent converted + /// ([`Reproject::extent_from_lonlat`]); `None` for none, or one that can't be bounded there. + pub(crate) fn request_box(&self, req: &Request) -> Option { + self.own_box(req).or_else(|| req.extent.and_then(|e| self.extent_from_lonlat(&e))) + } + /// A longitude/latitude geometry in the source's coordinates. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn to_native(&self, g: &Geometry) -> Option { @@ -1322,12 +1374,11 @@ pub(crate) struct Placed { pub(crate) lonlat: Extent, } -impl Placed { - /// Whether it is within a request's extent (in longitude/latitude), as [`in_request`] asks - /// of a geometry there. - pub(crate) fn in_request(&self, req: &Request) -> bool { - req.extent.is_none_or(|e| self.lonlat.intersects(&e)) - } +/// A geometry a source read for a request, in its own coordinates, and whether it is within the +/// request ([`Reproject::place`]). +pub(crate) struct Fitted { + pub(crate) geometry: Geometry, + pub(crate) inside: bool, } /// Makes ring rustls's process-wide crypto provider. SQL Server's client also builds aws-lc-rs @@ -1404,6 +1455,8 @@ pub(crate) fn read_ca_roots(label: &str, file: &Path, der: CaDer) -> Result Extent { - let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE }, Some(PROBE_TIMEOUT)) else { + let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE, own: None }, Some(PROBE_TIMEOUT)) else { return Extent::EMPTY; }; // Read in the table's own system: each placed in longitude/latitude, vertex by vertex. @@ -1314,10 +1314,10 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { let r = Reproject::from_crs(crate::raster::Crs::from_epsg(32617).unwrap(), &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r).unwrap_err().to_string().contains("can't be bounded")); - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10, own: None }; assert!(native_window(&clean, Extent::EMPTY, &r).unwrap().is_some()); assert!(native_window(&Request::all(), all, &r).unwrap().is_none()); } @@ -1368,12 +1368,12 @@ mod tests { let src = MysqlSource::open(conn.clone(), t.clone(), Some(f), None).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let opened = start.elapsed(); let i = src.info(); - let whole = src.read(&Request { extent: None, limit: 250_000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let whole = src.read(&Request { extent: None, limit: 250_000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let read = start.elapsed() - opened; let e = i.extent; let q = Extent::new(e.min_x, e.min_y, e.min_x + e.width() / 2.0, e.min_y + e.height() / 2.0); let started = std::time::Instant::now(); - let part = src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let part = src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let quarter = started.elapsed(); // In the table's own system: compared in longitude/latitude, as the request is. let to = src.coord_crs().to(crate::raster::Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); diff --git a/crates/data/src/source/own_box_tests.rs b/crates/data/src/source/own_box_tests.rs new file mode 100644 index 0000000000..b583dd7f2a --- /dev/null +++ b/crates/data/src/source/own_box_tests.rs @@ -0,0 +1,154 @@ +//! A read given its box in the source's own system ([`Request::own`]) tests each feature's own box +//! against it, converting nothing; without one, or with one in another system, it reads as before. + +use super::*; +use crate::raster::Crs; +use crate::{Dataset, Field, FieldType, Geometry, Value}; +use rustgis_geom::Coord; +use std::path::PathBuf; + +fn dir() -> PathBuf { + let d = std::env::temp_dir().join(format!("rustgis-own-box-tests-{}", std::process::id())); + std::fs::create_dir_all(&d).unwrap(); + d +} + +fn utm31() -> Crs { + Crs::from_epsg(32631).unwrap() +} + +/// Lines in UTM zone 31N: one at Paris, one from Paris to 1e9 m east (which has no place in +/// longitude/latitude), and one 400 km south. +fn lines() -> Dataset { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((451_500.0, 5_411_500.0), (1e9, 5_411_500.0)), vec![Value::Text("far east".into())]); + ds.push(line((451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), vec![Value::Text("south".into())]); + ds.held_in = utm31(); + ds +} + +fn names(b: &Batch) -> Vec { + let mut out: Vec = b + .features + .iter() + .filter_map(|f| match f.attrs.first() { + Some(Value::Text(t)) => Some(t.clone()), + _ => None, + }) + .collect(); + out.sort(); + out +} + +/// Around Paris: in longitude/latitude, and the same place in UTM 31N. +fn around_paris() -> (Extent, Extent) { + (Extent::new(2.2, 48.75, 2.5, 48.95), Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0)) +} + +fn read_three_ways(src: &dyn FeatureSource, what: &str) { + let (lonlat, utm) = around_paris(); + assert_eq!(src.coord_crs(), utm31(), "{what}"); + // In longitude/latitude, as before: the line with no place there is left out. + let plain = src.read(&Request { extent: Some(lonlat), limit: 100, own: None }).unwrap(); + assert_eq!(names(&plain), ["paris"], "{what}"); + // In its own system: the line reaching past where longitude/latitude goes is kept, as its box + // meets the view's; the one to the south still isn't. + let own = src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((utm31(), utm)) }).unwrap(); + assert_eq!(names(&own), ["far east", "paris"], "{what}"); + assert!(own.complete, "{what}"); + let line = own.features.iter().find(|f| matches!(f.attrs.first(), Some(Value::Text(t)) if t == "paris")).unwrap(); + assert_eq!(line.geometry.as_ref().map(Geometry::extent), Some(Extent::new(451_000.0, 5_411_000.0, 452_000.0, 5_412_000.0)), "{what}"); + // A box in another system is one this source can't take: read as without it. + let swiss = Extent::new(2_600_000.0, 1_200_000.0, 2_700_000.0, 1_300_000.0); + let other = src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((Crs::from_epsg(2056).unwrap(), swiss)) }).unwrap(); + assert_eq!(names(&other), ["paris"], "{what}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_read_given_its_box_in_the_files_own_system_tests_features_there() { + let d = dir(); + for ext in ["shp", "fgb", "gpkg", "parquet"] { + let p = d.join(format!("lines.{ext}")); + crate::io::write_path_in(&lines(), &p, utm31()).unwrap(); + let read = || { + let src = open_path(&p, None).unwrap(); + read_three_ways(src.as_ref(), ext); + }; + if ext == "shp" { + shp::with_test_cache(d.join("indexes"), read); + } else { + read(); + } + // The browser's GeoPackage reader too. + if ext == "gpkg" { + let bytes = Shared(std::sync::Arc::new(std::fs::read(&p).unwrap())); + let src = gpkg_mem::GpkgMemSource::open_shared(bytes, None).unwrap(); + read_three_ways(&src, "gpkg in memory"); + } + } +} + +#[test] +fn a_geojson_read_in_place_given_its_box_in_its_own_system_tests_features_there() { + let p = dir().join("lines.geojson"); + let feature = |name: &str, a: (f64, f64), b: (f64, f64)| { + format!( + r#"{{"type":"Feature","properties":{{"name":"{name}"}},"geometry":{{"type":"LineString","coordinates":[[{},{}],[{},{}]]}}}}"#, + a.0, a.1, b.0, b.1 + ) + }; + let text = format!( + r#"{{"type":"FeatureCollection","crs":{{"type":"name","properties":{{"name":"urn:ogc:def:crs:EPSG::32631"}}}},"features":[{},{}]}}"#, + feature("paris", (451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), + feature("south", (451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), + ); + std::fs::write(&p, text).unwrap(); + let src = geojson::GeoJsonSource::open_path(&p, "lines").unwrap(); + assert_eq!(src.coord_crs(), utm31()); + let (lonlat, utm) = around_paris(); + for own in [None, Some((utm31(), utm)), Some((Crs::from_epsg(2056).unwrap(), utm))] { + let b = src.read(&Request { extent: Some(lonlat), limit: 100, own }).unwrap(); + assert_eq!(names(&b), ["paris"], "{own:?}"); + } + // A box in its own system that misses Paris, though the longitude/latitude extent holds it: + // the box decides. + let elsewhere = Extent::new(600_000.0, 5_400_000.0, 620_000.0, 5_420_000.0); + assert!(src.read(&Request { extent: Some(lonlat), limit: 100, own: Some((utm31(), elsewhere)) }).unwrap().features.is_empty()); +} + +#[test] +fn a_box_in_its_own_system_is_tested_without_converting() { + let mut notes = Vec::new(); + let r = Reproject::from_crs(utm31(), &mut notes); + let (lonlat, utm) = around_paris(); + let far = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(1e9, 5_411_500.0)]]); + // No place in longitude/latitude: left out as before without the box, kept with it. + assert!(r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: None }).is_none()); + let fitted = r.place(far.clone(), &Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }).unwrap(); + assert!(fitted.inside); + assert_eq!(fitted.geometry, far); + assert_eq!(r.request_box(&Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }), Some(utm)); + // A source in longitude/latitude reads by the extent, whatever box comes with it. + let lonlat_source = Reproject::from_crs(Crs::LonLat, &mut notes); + let req = Request { extent: Some(lonlat), limit: 1, own: Some((Crs::LonLat, Extent::new(0.0, 0.0, 1.0, 1.0))) }; + assert_eq!(lonlat_source.request_box(&req), Some(lonlat)); + assert!(lonlat_source.place(Geometry::Point(Coord::new(2.3, 48.85)), &req).unwrap().inside); + assert!(notes.is_empty(), "{notes:?}"); +} + +#[test] +fn a_coordinate_that_isnt_a_number_is_left_out_in_its_own_system_too() { + let mut notes = Vec::new(); + let r = Reproject::from_crs(utm31(), &mut notes); + let (lonlat, utm) = around_paris(); + let req = Request { extent: Some(lonlat), limit: 1, own: Some((utm31(), utm)) }; + let missing = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(f64::NAN, 5_411_500.0)]]); + // Left out for the reader to count, as without the box. + assert!(r.place(missing.clone(), &req).is_none()); + assert!(r.place(missing, &Request { own: None, ..req }).is_none()); + let clean = Geometry::Line(vec![vec![Coord::new(451_500.0, 5_411_500.0), Coord::new(452_000.0, 5_411_500.0)]]); + assert!(r.place(clean, &req).unwrap().inside); +} diff --git a/crates/data/src/source/parquet.rs b/crates/data/src/source/parquet.rs index 06bd3dd13b..94fdb484e5 100644 --- a/crates/data/src/source/parquet.rs +++ b/crates/data/src/source/parquet.rs @@ -486,6 +486,10 @@ impl FeatureSource for ParquetSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -499,7 +503,7 @@ impl FeatureSource for ParquetSource { self.attribute(); let limit = clamp_limit(req.limit); let md = self.reader.metadata(); - let native = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let native = self.reproject.request_box(req); // Preserve ordinary candidate counts; a refused view needs a geometry scan to count. if limit == 0 && req.extent.is_some() && native.is_none() { return Err(super::unbounded_count()); @@ -665,7 +669,7 @@ impl FeatureSource for ParquetSource { // Null geometry is valid; malformed non-null WKB is skipped and counted. let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.read(g)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|g| self.reproject.place(g, req)) else { skipped += 1; continue; }; @@ -673,7 +677,7 @@ impl FeatureSource for ParquetSource { } None => None, }; - let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(req)); + let matches_extent = geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside); if !matches_extent || (late && !sample.wants()) { continue; } @@ -718,7 +722,7 @@ impl FeatureSource for ParquetSource { if self.remote.is_some() { return Err(DataError::Unsupported("a whole GeoParquet by its web address read a chunk at a time".into())); } - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let md = self.reader.metadata(); let native = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); let mut out = Batch { complete: true, ..Batch::default() }; @@ -774,7 +778,7 @@ impl FeatureSource for ParquetSource { crate::progress::step(1)?; let geometry = match geoms.get(k).and_then(|b| b.as_deref()) { Some(bytes) => { - let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.read(geom)) else { + let Some(geometry) = wkb::decode(bytes).and_then(|geom| self.reproject.place(geom, &req)) else { out.skipped += 1; continue; }; @@ -782,7 +786,7 @@ impl FeatureSource for ParquetSource { } None => None, }; - if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.in_request(&req)) { + if !geometry.as_ref().map_or(req.extent.is_none(), |g| g.inside) { continue; } let geometry = geometry.map(|p| p.geometry); diff --git a/crates/data/src/source/postgis.rs b/crates/data/src/source/postgis.rs index 9c7c762f4a..ffe85406f1 100644 --- a/crates/data/src/source/postgis.rs +++ b/crates/data/src/source/postgis.rs @@ -1684,11 +1684,21 @@ fn row_extent(r: &postgres::Row) -> Option { } } +/// The box a read narrows its query by when the request gives it in the table's own system +/// ([`Request::own`], [`Reproject::own_box`]); `None` otherwise, for the extent to be converted. +fn own_query_box(reproject: Option<&Reproject>, req: &Request) -> Option { + reproject.and_then(|r| r.own_box(req)) +} + impl FeatureSource for PostgisSource { fn info(&self) -> &SourceInfo { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// The table's own system when RustGIS converts it itself, else longitude/latitude, which /// the server gives. fn coord_crs(&self) -> Crs { @@ -1699,7 +1709,13 @@ impl FeatureSource for PostgisSource { fn read(&self, req: &Request) -> Result { let limit = clamp_limit(req.limit); let mut out = Batch::default(); - let native = req.extent.map(|e| self.lonlat_to_native(&e)).transpose()?; + // In the table's own system: the box the request gives there ([`Request::own`]), which + // a feature reaching past where longitude/latitude goes meets too, else its extent + // converted (refused when it can't be bounded). + let native = match own_query_box(self.reproject.as_ref(), req) { + Some(own) => Some(own), + None => req.extent.map(|e| self.lonlat_to_native(&e)).transpose()?, + }; if limit == 0 { return Ok(out); } @@ -1739,14 +1755,15 @@ impl FeatureSource for PostgisSource { }; // The index matched the request's box in the table's coordinates, which holds more // than the request when they are projected. Held in its own system, a geometry is - // placed in longitude/latitude to be compared, and kept as the table holds it. + // compared in the request's box there when it gives one, else placed in + // longitude/latitude to be compared, and kept as the table holds it. if self.held != Crs::LonLat { - let placed = feature.geometry.take().and_then(|g| self.reproject.as_ref().and_then(|r| r.read(g))); + let placed = feature.geometry.take().and_then(|g| self.reproject.as_ref().and_then(|r| r.place(g, req))); let Some(placed) = placed else { out.skipped += 1; continue; }; - if !placed.in_request(req) { + if !placed.inside { continue; } feature.geometry = Some(placed.geometry); @@ -1768,6 +1785,24 @@ impl FeatureSource for PostgisSource { mod tests { use super::*; + /// A read given its box in the table's own system narrows the query by it, not by its + /// longitude/latitude extent converted; one in another system, or a table in + /// longitude/latitude, goes by the extent as before. + #[test] + fn a_read_in_the_tables_own_system_queries_by_its_box() { + let utm = Crs::from_epsg(32631).unwrap(); + let own = Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0); + let lonlat = Some(Extent::new(2.2, 48.75, 2.5, 48.95)); + let table = Reproject::from_crs(utm, &mut Vec::new()); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), Some(own)); + let swiss = Crs::from_epsg(2056).unwrap(); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: Some((swiss, own)) }), None); + assert_eq!(own_query_box(Some(&table), &Request { extent: lonlat, limit: 10, own: None }), None); + let geographic = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); + assert_eq!(own_query_box(Some(&geographic), &Request { extent: lonlat, limit: 10, own: Some((Crs::LonLat, own)) }), None); + assert_eq!(own_query_box(None, &Request { extent: lonlat, limit: 10, own: Some((utm, own)) }), None); + } + #[test] fn families_of_declared_types() { assert_eq!(family_of("MULTIPOLYGON"), Some(Family::Polygons)); @@ -1827,13 +1862,13 @@ mod tests { let mut source = source("POINT"); source.reproject = Some(Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new())); for limit in [0, 10] { - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("can't be bounded in the database"), "{error}"); } - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 0 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 0, own: None }; assert!(source.read(&clean).unwrap().features.is_empty()); - assert!(source.read(&Request { extent: None, limit: 0 }).is_ok()); + assert!(source.read(&Request { extent: None, limit: 0, own: None }).is_ok()); } /// A table in a system RustGIS converts itself is written as the layer holds it, in that @@ -2182,12 +2217,12 @@ mod tests { }; let opened = start.elapsed(); let i = src.info(); - let all = src.read(&Request { extent: None, limit: 250_000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let all = src.read(&Request { extent: None, limit: 250_000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); let read = start.elapsed() - opened; // A view of a quarter of the extent. let e = i.extent; let q = Extent::new(e.min_x, e.min_y, e.min_x + e.width() / 2.0, e.min_y + e.height() / 2.0); - let part = src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); + let part = src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())); // Features come in the table's own system when RustGIS converts it: their boxes // are compared in longitude/latitude, as the request is. let to = src.coord_crs().to(Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); diff --git a/crates/data/src/source/shp.rs b/crates/data/src/source/shp.rs index 03b2f9282e..3cdd3533f3 100644 --- a/crates/data/src/source/shp.rs +++ b/crates/data/src/source/shp.rs @@ -236,6 +236,10 @@ impl FeatureSource for ShpSource { &self.info } + fn reads_own_box(&self) -> bool { + true + } + /// Its own system, in which it gives its features as the file holds them. fn coord_crs(&self) -> crate::raster::Crs { self.reproject.crs() @@ -251,7 +255,7 @@ impl FeatureSource for ShpSource { fn read(&self, req: &Request) -> Result { let encoding = self.encoding.decoder(); let limit = clamp_limit(req.limit); - let extent = req.extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); + let extent = self.reproject.request_box(req); // Keep indexed zero-limit counts; a refused view has no cheap candidate count. if limit == 0 && req.extent.is_some() && extent.is_none() { return Err(super::unbounded_count()); @@ -297,7 +301,7 @@ impl FeatureSource for ShpSource { boxed_off += u64::from(index::usable(record_box(&buf, u64::from(place.len)))); return Ok(()); } - Ok(Some(g)) => match self.reproject.read(g) { + Ok(Some(g)) => match self.reproject.place(g, req) { Some(placed) => Some(placed), None => { skipped += 1; @@ -312,7 +316,7 @@ impl FeatureSource for ShpSource { }; // The index's boxes are rounded outward to f32, so it can match a shape just outside. A // shape without geometry doesn't match an extent, bounded natively or not. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.inside) { return Ok(()); } let geometry = geometry.map(|p| p.geometry); @@ -384,7 +388,7 @@ impl FeatureSource for ShpSource { fn visit_chunks(&self, extent: Option, bytes: usize, visit: &mut dyn FnMut(Vec) -> Result<()>) -> Result { let encoding = self.encoding.decoder(); let mut chunks = super::chunk_memory::Chunker::new(bytes, visit)?; - let req = Request { extent, limit: usize::MAX }; + let req = Request { extent, limit: usize::MAX, own: None }; let extent = extent.and_then(|e| self.reproject.extent_from_lonlat(&e)); if extent.is_some_and(|e| e.is_empty()) { return Ok(Batch { complete: true, ..Batch::default() }); @@ -440,7 +444,7 @@ impl FeatureSource for ShpSource { let stored = record_box(&buf, u64::from(place.len)); missed = index::usable(stored) && !holds(stored, &g.extent()); } - match self.reproject.read(g) { + match self.reproject.place(g, &req) { Some(placed) => Some(placed), None => { skipped += 1; @@ -455,7 +459,7 @@ impl FeatureSource for ShpSource { } }; // As in `read`, the shape itself is checked. - if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.in_request(&req)) { + if geometry.as_ref().map_or(req.extent.is_some(), |g| !g.inside) { return Ok(()); } let geometry = geometry.map(|p| p.geometry); diff --git a/crates/data/src/source/shp/cache/tests.rs b/crates/data/src/source/shp/cache/tests.rs index 74b146ad16..f6c83eb886 100644 --- a/crates/data/src/source/shp/cache/tests.rs +++ b/crates/data/src/source/shp/cache/tests.rs @@ -503,7 +503,8 @@ fn cache_child_fixture() { assert!(!source.info().indexed); assert!(source.info().notes.iter().any(|n| n.contains("scanning record headers"))); for limit in [0, 1, 100] { - let batch = source.read(&crate::source::Request { extent: Some(crate::Extent::new(0.0, 0.0, 3.0, 3.0)), limit }).unwrap(); + let batch = + source.read(&crate::source::Request { extent: Some(crate::Extent::new(0.0, 0.0, 3.0, 3.0)), limit, own: None }).unwrap(); assert_eq!(batch.matched, 1); assert_eq!(batch.features.len(), limit.min(1)); } diff --git a/crates/data/src/source/shp/tests.rs b/crates/data/src/source/shp/tests.rs index f652fe48ef..101492c80d 100644 --- a/crates/data/src/source/shp/tests.rs +++ b/crates/data/src/source/shp/tests.rs @@ -333,7 +333,7 @@ fn shapefile_disk_index_reopens_and_invalidates_without_changing_source() { let p = fixture.join("indexed-grid.shp"); points_shapefile(&p); let original = std::fs::read(&p).unwrap(); - let req = Request { extent: Some(Extent::new(10.0, 10.0, 40.0, 30.0)), limit: 1000 }; + let req = Request { extent: Some(Extent::new(10.0, 10.0, 40.0, 30.0)), limit: 1000, own: None }; let src = open_path(&p, None).unwrap(); let expected = src.read(&req).unwrap(); let reopened = open_path(&p, None).unwrap(); @@ -371,14 +371,14 @@ fn shapefile_disk_index_keeps_file_order_and_query_boundaries() { } std::fs::write(&p, bytes).unwrap(); let src = open_path(&p, None).unwrap(); - let batch = src.read(&Request { extent: Some(Extent::new(1.0, -1.0, 2.0, 1.0)), limit: 1000 }).unwrap(); + let batch = src.read(&Request { extent: Some(Extent::new(1.0, -1.0, 2.0, 1.0)), limit: 1000, own: None }).unwrap(); assert_eq!(batch.matched, 101); assert_eq!(batch.features.len(), 101); assert!(batch.complete); assert!(batch.features.windows(2).all(|p| p[0].id < p[1].id)); assert_eq!(batch.features.first().unwrap().geometry, Some(Geometry::Point(Coord::new(2.0, 0.0)))); assert_eq!(batch.features.last().unwrap().geometry, Some(Geometry::Point(Coord::new(1.0, 0.0)))); - let sample = src.read(&Request { extent: None, limit: 10 }).unwrap(); + let sample = src.read(&Request { extent: None, limit: 10, own: None }).unwrap(); assert_eq!(sample.matched, 1000); assert_eq!(sample.features.len(), 10); assert!(!sample.complete); @@ -404,7 +404,7 @@ fn shapefile_overview_index_shortcut_does_not_include_null_shapes() { std::fs::write(&p, bytes).unwrap(); let src = open_path(&p, None).unwrap(); assert_eq!(src.read(&Request::all()).unwrap().features.len(), 2); - let view = src.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 100 }).unwrap(); + let view = src.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 100, own: None }).unwrap(); assert_eq!(view.matched, 1); assert_eq!(view.features.len(), 1); assert!(view.features.iter().all(|f| f.geometry.is_some())); @@ -506,7 +506,7 @@ fn disk_queries_match_legacy_scan_sampling_and_edges() { for limit in [0, 1, 7, 29, 1000] { let step = crate::source::stride(ids.len() as u64, limit).max(1) as usize; let expected: Vec<_> = ids.iter().copied().step_by(step).take(limit).collect(); - let batch = src.read(&Request { extent, limit }).unwrap(); + let batch = src.read(&Request { extent, limit, own: None }).unwrap(); assert_eq!(batch.matched, ids.len() as u64); assert_eq!(batch.complete, step == 1); assert_eq!(batch.features.iter().map(|f| f.id).collect::>(), expected); @@ -534,7 +534,7 @@ fn shapefile_disk_index_benchmark() { let clock = std::time::Instant::now(); let source = ShpSource::open_path(&path, "benchmark").unwrap(); let warm = clock.elapsed(); - let request = Request { extent: Some(Extent::new(-1.0, -1.0, 1.0, 1.0)), limit: 1000 }; + let request = Request { extent: Some(Extent::new(-1.0, -1.0, 1.0, 1.0)), limit: 1000, own: None }; let clock = std::time::Instant::now(); let indexed = source.read(&request).unwrap(); let query = clock.elapsed(); @@ -564,7 +564,7 @@ fn shapefile_disk_index_complete_chunks_preserve_full_reads_and_file_order() { points_shapefile(&path); let source = open_path(&path, None).unwrap(); assert!(source.info().indexed); - assert_eq!(source.read(&Request { extent: None, limit: 1 }).unwrap().features.len(), 1); + assert_eq!(source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.len(), 1); for extent in [None, Some(Extent::new(10.0, 5.0, 15.0, 10.0)), Some(Extent::EMPTY)] { let expected = source.read(&Request { extent, ..Request::all() }).unwrap(); for budget in [1, 256, 8192] { @@ -590,7 +590,7 @@ fn shapefile_disk_index_complete_chunks_preserve_full_reads_and_file_order() { source .visit_chunks(None, 256, &mut |_| { if !reentrant { - assert_eq!(source.read(&Request { extent: None, limit: 1 })?.features.len(), 1); + assert_eq!(source.read(&Request { extent: None, limit: 1, own: None })?.features.len(), 1); reentrant = true; } Ok(()) diff --git a/crates/data/src/source/sqlserver.rs b/crates/data/src/source/sqlserver.rs index 46a6c915d0..8aea2a6fa1 100644 --- a/crates/data/src/source/sqlserver.rs +++ b/crates/data/src/source/sqlserver.rs @@ -956,7 +956,7 @@ impl SqlServerSource { } fn measure(&self) -> Extent { - let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE }, Some(PROBE_TIMEOUT)) else { + let Ok(b) = self.read_within(&Request { extent: None, limit: EXTENT_SAMPLE, own: None }, Some(PROBE_TIMEOUT)) else { return Extent::EMPTY; }; // Read in the table's own system: each placed in longitude/latitude, vertex by vertex. @@ -1328,17 +1328,17 @@ mod tests { #[test] fn refused_database_view_is_not_a_whole_table_sample() { let r = Reproject::from_crs(Crs::from_epsg(32617).unwrap(), &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let all = Extent::new(-84.0, 0.0, -78.0, 25.0); assert!(native_window(&req, all, &r, false, 160).unwrap_err().to_string().contains("can't be bounded")); - let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10 }; + let clean = Request { extent: Some(Extent::new(-84.0, 30.0, -78.0, 40.0)), limit: 10, own: None }; assert!(native_window(&clean, Extent::EMPTY, &r, false, 160).unwrap().is_some()); } #[test] fn native_windows_respect_database_compatibility() { let reproject = Reproject::from_crs(Crs::LonLat, &mut Vec::new()); - let req = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 100 }; + let req = Request { extent: Some(Extent::new(-180.0, -90.0, 180.0, 90.0)), limit: 100, own: None }; for compatibility in [0, 80, 90, 100] { assert_eq!(native_window(&req, Extent::EMPTY, &reproject, true, compatibility).unwrap(), None); } @@ -1354,7 +1354,7 @@ mod tests { ); } assert_eq!(native_window(&req, Extent::new(-10.0, -10.0, 10.0, 10.0), &reproject, true, 110).unwrap(), None); - assert_eq!(native_window(&Request { extent: None, limit: 100 }, Extent::EMPTY, &reproject, true, 110).unwrap(), None); + assert_eq!(native_window(&Request { extent: None, limit: 100, own: None }, Extent::EMPTY, &reproject, true, 110).unwrap(), None); } #[test] @@ -1493,7 +1493,7 @@ mod tests { Err(e) => panic!("{}: {e}", t.label()), }; let i = src.info(); - let whole = match src.read(&Request { extent: None, limit: 250_000 }) { + let whole = match src.read(&Request { extent: None, limit: 250_000, own: None }) { Ok(whole) => whole, // A table too large to count and sample whole in the statement timeout says so; // its reads by extent are what a map asks for. @@ -1516,7 +1516,7 @@ mod tests { let part = if e.is_empty() { Batch::default() } else { - src.read(&Request { extent: Some(q), limit: 1000 }).unwrap_or_else(|e| panic!("{}: {e}", t.label())) + src.read(&Request { extent: Some(q), limit: 1000, own: None }).unwrap_or_else(|e| panic!("{}: {e}", t.label())) }; // In the table's own system: compared in longitude/latitude, as the request is. let to = src.coord_crs().to(crate::raster::Crs::LonLat).unwrap_or_else(|e| panic!("{e}")); @@ -1528,7 +1528,7 @@ mod tests { ids.sort_unstable(); ids.dedup(); assert_eq!(ids.len(), whole.features.len(), "{}: ids repeat", t.label()); - let sample = src.read(&Request { extent: None, limit: 1 }).unwrap_or_else(|e| panic!("{e}")); + let sample = src.read(&Request { extent: None, limit: 1, own: None }).unwrap_or_else(|e| panic!("{e}")); assert!(sample.features.len() <= 1); assert_eq!(sample.matched, whole.matched); println!( diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 1fd2d08b02..953dc09a34 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -398,13 +398,13 @@ fn geopackage_provenance_excludes_temporary_copies() { let upload = gpkg::GpkgUpload::new(&bytes).unwrap(); assert!(upload.unsupported_table_counts().unwrap().is_empty()); let source = upload.open(None).unwrap(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); assert_eq!(captured.inputs().len(), 1); assert_eq!(captured.inputs()[0].path, path.display().to_string()); assert!(captured.inputs()[0].sha256.is_some()); drop(captured); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); let mut count = 0; source .visit_chunks(None, 1 << 20, &mut |features| { @@ -425,13 +425,13 @@ fn geopackage_provenance_skips_a_replaced_path() { write_gpkg(&path, true); let source = open_path(&path, None).unwrap(); let captured = crate::provenance::Capture::start(); - source.read(&Request { extent: None, limit: 1 }).unwrap(); + source.read(&Request { extent: None, limit: 1, own: None }).unwrap(); assert!(captured.inputs().iter().any(|i| i.path == path.display().to_string())); drop(captured); std::fs::rename(&path, folder.path().join("retained.gpkg")).unwrap(); std::fs::write(&path, b"replacement").unwrap(); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); assert!(captured.inputs().is_empty()); } @@ -450,7 +450,7 @@ fn geopackage_provenance_keeps_a_linked_path() { let inputs = |path: &Path| { let source = open_path(path, None).unwrap(); let captured = crate::provenance::Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs().into_iter().map(|i| i.path).collect::>() }; let resolved = std::fs::canonicalize(&target).unwrap(); @@ -482,7 +482,7 @@ fn a_conversion_names_its_original_as_it_was_when_opened() { let source = super::fgb::FgbSource::open_converted_path(&converted, "grid", &original, None).unwrap(); let inputs = || { let captured = Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs() }; let before = inputs(); @@ -498,7 +498,7 @@ fn a_conversion_names_its_original_as_it_was_when_opened() { let source = super::parquet::ParquetSource::open_converted_path(&parquet, "grid", Some(&db), None).unwrap(); let inputs = || { let captured = Capture::start(); - assert!(!source.read(&Request { extent: None, limit: 1 }).unwrap().features.is_empty()); + assert!(!source.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.is_empty()); captured.inputs() }; let before: Vec = inputs(); @@ -670,13 +670,14 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!((c.x - (-138.0)).abs() < 1e-4 && (c.y - (-44.0)).abs() < 1e-4, "{c:?} in {}", info.format); assert_eq!(f.attrs[vi], Value::Int(64)); // Ids stay put between reads. - let near = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100 }).unwrap()); + let near = + in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-140.0, -46.0, -130.0, -40.0)), limit: 100, own: None }).unwrap()); let g = near.features.iter().find(|g| g.attrs.contains(&Value::Text("p3_4".into()))).unwrap(); assert_eq!(g.id, f.id, "{}", info.format); // An extent: exactly the points in it. let e = Extent::new(-60.0, -10.0, 40.0, 50.0); - let got = in_lonlat(src, src.read(&Request { extent: Some(e), limit: 10_000 }).unwrap()); + let got = in_lonlat(src, src.read(&Request { extent: Some(e), limit: 10_000, own: None }).unwrap()); assert_eq!(got.features.len(), in_box(&e), "{}", info.format); assert!(got.complete); assert!(got.features.iter().all(|f| f.geometry.as_ref().is_some_and(|g| e.contains(g.extent().center())))); @@ -688,7 +689,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { } // A limit: a sample spread over the whole extent, not the first rows. - let s = in_lonlat(src, src.read(&Request { extent: None, limit: 60 }).unwrap()); + let s = in_lonlat(src, src.read(&Request { extent: None, limit: 60, own: None }).unwrap()); assert!(!s.complete); assert!(s.features.len() <= 60 && s.features.len() >= 50, "{} of {}", s.features.len(), info.format); let xs: Vec = s.features.iter().filter_map(|f| f.geometry.as_ref()).map(|g| g.extent().min_x).collect(); @@ -696,7 +697,7 @@ fn check(src: &dyn FeatureSource, expect_indexed: bool) { assert!(s.matched >= 600); // An extent outside the data. - let none = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100 }).unwrap()); + let none = in_lonlat(src, src.read(&Request { extent: Some(Extent::new(-179.9, 80.0, -179.0, 84.0)), limit: 100, own: None }).unwrap()); assert!(none.features.is_empty()); // A whole read into a dataset. @@ -1711,7 +1712,7 @@ fn hostile_files_are_errors_not_panics() { for name in ["x.parquet", "x.fgb", "x.gpkg"] { if let Ok(s) = open_bytes(name, bytes.clone(), None) { let _ = s.read(&Request::all()); - let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 3 }); + let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 3, own: None }); } } } @@ -1755,7 +1756,7 @@ fn vector_samples() { e.center().y + e.height() / 8.0, ); let t2 = std::time::Instant::now(); - let b = match src.read(&Request { extent: Some(view), limit: 200_000 }) { + let b = match src.read(&Request { extent: Some(view), limit: 200_000, own: None }) { Ok(b) => b, Err(e) => { println!("{} [{layer}]: {e}", p.display()); @@ -1853,7 +1854,7 @@ fn writes_geopackage_geoparquet_and_shapefile() { for ext in ["gpkg", "parquet"] { let s = open_path(&d.join(format!("parcels.{ext}")), None).unwrap(); assert_eq!(s.info().count, Some(3), "{ext}"); - let b = s.read(&Request { extent: Some(Extent::new(15.0, 15.0, 25.0, 25.0)), limit: 100 }).unwrap(); + let b = s.read(&Request { extent: Some(Extent::new(15.0, 15.0, 25.0, 25.0)), limit: 100, own: None }).unwrap(); assert_eq!(b.features.len(), 1, "{ext}"); if ext == "gpkg" { assert_eq!(b.features[0].id, 2); @@ -1908,7 +1909,7 @@ fn geoparquet_exports_keep_exact_values_and_remote_extent_reads() { // Null rows must not consume a sample slot, whether the group is partly or wholly inside. for (extent, matched) in [(Extent::new(-90.0, 36.0, -89.0, 37.0), 1), (Extent::new(-180.0, -90.0, 180.0, 90.0), 2)] { for limit in [1, 10] { - let req = Request { extent: Some(extent), limit }; + let req = Request { extent: Some(extent), limit, own: None }; let remote = source.read(&req).unwrap(); let local_batch = local.read(&req).unwrap(); assert_eq!(remote.features.len(), matched.min(limit)); @@ -1959,7 +1960,7 @@ fn geoparquet_inferred_covering_nulls_fall_back_to_geometry() { let remote = open_driven(url); for extent in [Extent::new(-90.0, 36.0, -89.0, 37.0), Extent::new(-180.0, -90.0, 180.0, 90.0)] { for limit in [1, 10] { - let req = Request { extent: Some(extent), limit }; + let req = Request { extent: Some(extent), limit, own: None }; let expected = local.read(&req).unwrap(); assert_eq!(expected.features.len(), 1); assert_eq!((expected.matched, expected.complete, expected.skipped), (1, true, 0)); @@ -2320,7 +2321,7 @@ fn flatgeobuf_and_geoparquet_by_address() { let src = open_driven(&url); assert_eq!(src.info().count, Some(160_000), "{name}"); let e = Extent::new(10.0, 10.0, 12.0, 12.0); - let req = Request { extent: Some(e), limit: 10_000 }; + let req = Request { extent: Some(e), limit: 10_000, own: None }; let got = src.read(&req).unwrap(); let local = open_bytes(name, bytes, None).unwrap().read(&req).unwrap(); let ids = |b: &Batch| b.features.iter().map(|f| f.id).collect::>(); @@ -2332,7 +2333,7 @@ fn flatgeobuf_and_geoparquet_by_address() { let fetched = sent.load(std::sync::atomic::Ordering::Relaxed); assert!(fetched < total / 4, "{name}: fetched {fetched} of {total} bytes"); // A sample of the whole file, spread over it. - let s = src.read(&Request { extent: None, limit: 500 }).unwrap(); + let s = src.read(&Request { extent: None, limit: 500, own: None }).unwrap(); assert!(!s.complete && s.features.len() <= 500 && s.features.len() >= 250, "{name}: {}", s.features.len()); } @@ -2508,10 +2509,11 @@ fn shapefile_in_place_reprojects_from_its_prj() { assert!((e.min_x - 2.335).abs() < 1e-6 && (e.min_y - 48.855).abs() < 1e-6, "{e:?}"); assert!(src.info().notes.is_empty(), "{:?}", src.info().notes); // A longitude/latitude extent finds it; one beside it doesn't. - let near = in_lonlat(src.as_ref(), src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10 }).unwrap()); + let near = + in_lonlat(src.as_ref(), src.read(&Request { extent: Some(Extent::new(2.0, 48.5, 2.5, 49.0)), limit: 10, own: None }).unwrap()); let c = near.features.first().and_then(|f| f.geometry.as_ref()).and_then(Geometry::label_point).unwrap(); assert!((c.x - 2.335).abs() < 1e-6 && (c.y - 48.855).abs() < 1e-6, "{c:?}"); - assert!(src.read(&Request { extent: Some(Extent::new(3.0, 48.5, 3.5, 49.0)), limit: 10 }).unwrap().features.is_empty()); + assert!(src.read(&Request { extent: Some(Extent::new(3.0, 48.5, 3.5, 49.0)), limit: 10, own: None }).unwrap().features.is_empty()); // Without the .prj the coordinates are taken as they are, and that's said. std::fs::remove_file(p.with_extension("prj")).unwrap(); let src = open_path(&p, None).unwrap(); @@ -2530,7 +2532,7 @@ fn damaged_shapefiles_are_errors_or_skips_not_panics() { let read = || { if let Ok(s) = open_path(p, None) { let _ = s.read(&Request::all()); - let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 1 }); + let _ = s.read(&Request { extent: Some(Extent::new(-10.0, -10.0, 10.0, 10.0)), limit: 1, own: None }); } }; #[cfg(not(target_arch = "wasm32"))] @@ -2710,7 +2712,7 @@ fn geojson_in_place_matches_one_read_whole() { assert_eq!(inplace.features, whole.features, "{file}"); assert_eq!(report.messages.len(), whole_report.messages.len(), "{file}: {:?}", report.messages); // Extent reads skip features without geometry, and find each by its box. - let b = src.read(&Request { extent: Some(Extent::new(0.5, 0.5, 1.5, 2.5)), limit: 100 }).unwrap(); + let b = src.read(&Request { extent: Some(Extent::new(0.5, 0.5, 1.5, 2.5)), limit: 100, own: None }).unwrap(); assert!(b.features.iter().all(|f| f.geometry.is_some()), "{file}"); } // Not a FeatureCollection, or not GeoJSON: not read in place. @@ -2800,7 +2802,7 @@ fn geojson_legacy_crs_is_honoured_by_both_paths() { let p = dir().join("geojson-crs").join("rd.geojson"); for in_memory in [crate::io::BYTES_FLOOR, 0] { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); - let at = |e: Extent| src.read(&Request { extent: Some(e), limit: 100 }).unwrap().features.len(); + let at = |e: Extent| src.read(&Request { extent: Some(e), limit: 100, own: None }).unwrap().features.len(); assert_eq!(at(Extent::new(5.85, 51.95, 5.86, 51.96)), 1, "the polygon only"); assert_eq!(at(Extent::new(5.95, 52.02, 5.96, 52.03)), 1, "the polygon only"); assert_eq!(at(Extent::new(5.8, 51.9, 6.0, 52.1)), 2); @@ -2990,9 +2992,9 @@ fn geojson_sampling_skips_dropped_features() { for in_memory in [crate::io::BYTES_FLOOR, 0] { let src = geojson::GeoJsonSource::open_with(&p, "x", in_memory).unwrap(); assert_eq!(src.info().count, Some(3)); - let all = src.read(&Request { extent: None, limit: 100 }).unwrap(); + let all = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); assert_eq!((all.features.len(), all.matched, all.skipped, all.complete), (3, 3, 0, true)); - let some = src.read(&Request { extent: None, limit: 2 }).unwrap(); + let some = src.read(&Request { extent: None, limit: 2, own: None }).unwrap(); assert_eq!((some.features.len(), some.matched, some.skipped, some.complete), (2, 3, 0, false)); assert!(some.features.iter().all(|f| f.geometry.is_some())); let ids: Vec = all.features.iter().map(|f| f.id).collect(); @@ -3332,7 +3334,8 @@ fn nested_columns_and_vectors_by_address() { let e = Extent::new(10.0, 10.0, 40.0, 30.0); // The rows in the extent, with the nested column as a field. let (fields, batch) = - query_url_blocking(url, vec!["assets.data.href".into(), "no.such".into()], Request { extent: Some(e), limit: 1000 }).unwrap(); + query_url_blocking(url, vec!["assets.data.href".into(), "no.such".into()], Request { extent: Some(e), limit: 1000, own: None }) + .unwrap(); let k = fields.iter().position(|f| f.name == "assets.data.href").unwrap(); assert!(!fields.iter().any(|f| f.name == "no.such")); assert_eq!(batch.features.len(), in_box(&e)); @@ -3427,7 +3430,7 @@ fn shapefile_complete_chunks_keep_all_rows_order_attributes_and_budget() { let empty = shp::ShpSource::open_path(&empty_path, "empty").unwrap(); assert!(empty.visit_chunks(None, 0, &mut |_| panic!("zero budget must not emit")).is_err()); let extent = Some(Extent::new(0.02, 0.0, 0.1, 2.0)); - let expected = source.read(&Request { extent, limit: 1000 }).unwrap(); + let expected = source.read(&Request { extent, limit: 1000, own: None }).unwrap(); let mut rows = Vec::new(); source .visit_chunks(extent, 256, &mut |chunk| { @@ -3474,7 +3477,7 @@ fn geopackage_keeps_rows_without_geometry() { let (rows, summary, _) = visit_all(src.as_ref(), None, 1024); assert_eq!((rows, summary.matched, summary.skipped), (whole.features, 602, 4), "{format}"); let world = Extent::new(-180.0, -85.0, 180.0, 85.0); - let part = src.read(&Request { extent: Some(world), limit: 10_000 }).unwrap(); + let part = src.read(&Request { extent: Some(world), limit: 10_000, own: None }).unwrap(); assert_eq!(part.features.len(), 600, "{format}"); assert_eq!(visit_all(src.as_ref(), Some(world), 1024).0.len(), 600, "{format}"); } @@ -3541,7 +3544,7 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { // Each row alone when none fits the budget. assert_eq!(visit_all(src.as_ref(), None, 1).0, whole.features, "{format}"); // An extent: the features a complete read of it gives (the R-tree's order may differ). - let part = src.read(&Request { extent: Some(extent), limit: 10_000 }).unwrap(); + let part = src.read(&Request { extent: Some(extent), limit: 10_000, own: None }).unwrap(); assert!(part.complete && part.features.len() == in_box(&extent), "{format}"); let (rows, summary, _) = visit_all(src.as_ref(), Some(extent), 1024); assert!(summary.complete && summary.features.is_empty() && summary.matched == rows.len() as u64, "{format}"); @@ -3561,7 +3564,7 @@ fn geopackage_flatgeobuf_and_geoparquet_visit_what_a_whole_read_gives() { assert!(src.visit_chunks(None, 0, &mut |_| panic!("a zero budget must not emit")).is_err(), "{format}"); // The map's reads of the layer go on while a traversal waits on its visitor. src.visit_chunks(None, 256, &mut |_| { - assert_eq!(src.read(&Request { extent: None, limit: 1 }).unwrap().features.len(), 1, "{format}"); + assert_eq!(src.read(&Request { extent: None, limit: 1, own: None }).unwrap().features.len(), 1, "{format}"); Ok(()) }) .unwrap(); @@ -3940,7 +3943,7 @@ fn geopackage_export_adds_and_replaces_tables_and_keeps_the_others() { let owners = |p: &Path| rusqlite::Connection::open(p).unwrap().query_row("SELECT count(*) FROM owners", [], |r| r.get::<_, i64>(0)).unwrap(); assert_eq!(owners(&path), 1); - let read = |t: &str, extent| open_path(&path, Some(t)).unwrap().read(&Request { extent, limit: 100 }).unwrap().features; + let read = |t: &str, extent| open_path(&path, Some(t)).unwrap().read(&Request { extent, limit: 100, own: None }).unwrap().features; assert_eq!(read("permits", None).len(), 3); // Its spatial index answers an extent query. assert_eq!(read("permits", Some(Extent::new(10.5, 19.0, 11.5, 21.0))).len(), 1); @@ -4482,7 +4485,7 @@ fn parquet_date_units_invalid_values_and_nulls() { assert_eq!(batch.features[1].attrs[3].to_string(), "1970-01-01T00:00:00.000001"); assert!(batch.features[2].attrs.iter().all(Value::is_null)); let extent = Extent::new(-0.1, -0.1, 0.1, 0.1); - let filtered = source.read(&Request { extent: Some(extent), limit: usize::MAX }).unwrap(); + let filtered = source.read(&Request { extent: Some(extent), limit: usize::MAX, own: None }).unwrap(); assert_eq!(filtered.features.len(), 1); assert!(filtered.unread_dates.is_empty(), "invalid dates in filtered-out rows aren't read losses"); let filtered = source.visit_chunks(Some(extent), 256, &mut |_| Ok(())).unwrap(); @@ -4564,7 +4567,7 @@ fn a_feature_just_outside_an_extent_is_left_out_of_its_read() { let mut ds = Dataset::new("edge", GeometryType::Point, vec![]); ds.push(Some(Geometry::Point(Coord::new(0.0, 0.999_999_999))), vec![]); let extent = Some(Extent::new(-1.0, 1.0, 1.0, 2.0)); - let req = Request { extent, limit: 1000 }; + let req = Request { extent, limit: 1000, own: None }; let (shp_path, geojson_path) = (d.join("edge.shp"), d.join("edge.geojson")); crate::io::write_path(&ds, &shp_path).unwrap(); crate::io::write_path(&ds, &geojson_path).unwrap(); @@ -4687,12 +4690,12 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { // A zero limit cannot give a count for a view requiring a complete geometry scan. let probe = crate::progress::tests::Counted::cancelling_after(0); let _guard = crate::progress::install(Some(probe.clone())); - let error = source.read(&Request { extent: Some(view), limit: 0 }).unwrap_err().to_string(); + let error = source.read(&Request { extent: Some(view), limit: 0, own: None }).unwrap_err().to_string(); assert!(error.contains("zero-limit") && error.contains("count"), "{ext}: {error}"); assert_eq!(probe.done.load(std::sync::atomic::Ordering::Relaxed), 0, "{ext}"); } for limit in [10, 2201] { - let read = in_lonlat(source, source.read(&Request { extent: Some(view), limit }).unwrap()); + let read = in_lonlat(source, source.read(&Request { extent: Some(view), limit, own: None }).unwrap()); assert_eq!(read.matched, 200, "{ext}: count only view matches before sampling"); if limit == 10 { // Adaptive sampling keeps between half the limit and the limit. @@ -4711,7 +4714,7 @@ fn a_view_its_system_cant_bound_reads_what_is_in_view() { // Cancel while scanning, not before the read starts; the view needs a complete scan. let probe = crate::progress::tests::Counted::cancelling_after(3); let _guard = crate::progress::install(Some(probe.clone())); - assert!(matches!(source.read(&Request { extent: Some(view), limit: 10 }), Err(DataError::Cancelled)), "{ext}"); + assert!(matches!(source.read(&Request { extent: Some(view), limit: 10, own: None }), Err(DataError::Cancelled)), "{ext}"); assert_eq!(probe.done.load(std::sync::atomic::Ordering::Relaxed), 3, "{ext}"); } if source.visits_chunks() { @@ -4733,7 +4736,7 @@ fn unbounded_parquet_view_refuses_a_capped_group() { ds.push(Some(Geometry::Point(Coord::new(-81.0, 0.0))), vec![Value::Int(1)]); write_unbounded_view_fixture(&ds, &p); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_group_rows(1); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("more than the 1 read from one"), "{error}"); } @@ -4748,12 +4751,12 @@ fn unbounded_parquet_view_refuses_decoded_columns_over_budget() { } write_unbounded_view_fixture(&ds, &p); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_scan_bytes(16 << 10); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 1 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 1, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); let error = source.visit_chunks(req.extent, 4096, &mut |_| Ok(())).unwrap_err().to_string(); assert!(error.contains("decoded-column budget"), "{error}"); - let clean = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 1 }; + let clean = Request { extent: Some(Extent::new(-84.0, -1.0, -78.0, 1.0)), limit: 1, own: None }; assert_eq!(source.read(&clean).unwrap().features.len(), 1); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); let batch = source.read(&req).unwrap(); @@ -4771,7 +4774,7 @@ fn unbounded_parquet_scan_accepts_two_thousand_distinct_points() { } write_projected_parquet_fixture(&ds, &p, 2000, true); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let batch = source.read(&req).unwrap(); assert_eq!(batch.matched, 2000); assert!((5..=10).contains(&batch.features.len())); @@ -4825,7 +4828,7 @@ fn unbounded_parquet_view_bounds_aggregate_row_masks() { (0..40_000).map(|id| crate::Feature { id, geometry: Some(Geometry::Point(Coord::new(-81.0, 0.0))), attrs: vec![] }).collect(); write_projected_parquet_fixture(&ds, &p, 100, true); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap().with_scan_bytes(32 << 10); - let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10 }; + let req = Request { extent: Some(Extent::new(-120.0, -30.0, 10.0, 30.0)), limit: 10, own: None }; let error = source.read(&req).unwrap_err().to_string(); assert!(error.contains("row-mask budget"), "{error}"); let source = parquet::ParquetSource::open_path(&p, "pts").unwrap(); diff --git a/crates/data/tests/integration/extent_query_properties.rs b/crates/data/tests/integration/extent_query_properties.rs index 894cda1ac9..080c3b2621 100644 --- a/crates/data/tests/integration/extent_query_properties.rs +++ b/crates/data/tests/integration/extent_query_properties.rs @@ -145,7 +145,7 @@ fn differences(all: &[rustgis_data::Feature], got: &[u64], q: &Extent, how: &str /// What `src` does differently for `q`, besides the limits. fn check(src: &dyn FeatureSource, q: &Extent) -> Result<(Vec, usize, usize), String> { let all = src.read(&Request::all()).map_err(|e| format!("whole read: {e}"))?; - let read = src.read(&Request { extent: Some(*q), limit: MAX_LIMIT }).map_err(|e| format!("read: {e}"))?; + let read = src.read(&Request { extent: Some(*q), limit: MAX_LIMIT, own: None }).map_err(|e| format!("read: {e}"))?; let mut found = differences(&all.features, &ids(read.features.iter().map(|f| f.id)), q, "read"); if !read.complete { found.push("read was incomplete".into()); diff --git a/crates/data/tests/integration/shapefile_encoding.rs b/crates/data/tests/integration/shapefile_encoding.rs index 60f5c3a345..48e0bc03f8 100644 --- a/crates/data/tests/integration/shapefile_encoding.rs +++ b/crates/data/tests/integration/shapefile_encoding.rs @@ -654,7 +654,7 @@ fn check_ldid_readers(ldid: u8, text: &[u8], expected: &str, cpg: Option<&[u8]>, let whole: Vec = notes.iter().map(|n| if n.starts_with("places: ") { n.to_string() } else { format!("places: {n}") }).collect(); assert_eq!(rustgis_data::source::materialize(&src).unwrap().1.messages, whole, "LDID {ldid:02X} whole read in place"); - for (request, rows, complete) in [(Request { extent: None, limit: 1 }, 1, false), (Request::all(), 3, true)] { + for (request, rows, complete) in [(Request { extent: None, limit: 1, own: None }, 1, false), (Request::all(), 3, true)] { let batch = src.read(&request).unwrap(); assert_eq!(batch.matched, 3); assert_eq!(batch.complete, complete); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 91b84784e8..e0b3078269 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -3504,7 +3504,7 @@ const ASPRS: [(i64, [u8; 3]); 13] = [ /// sample of its points. fn lidar_renderer(src: &dyn rustgis_data::source::FeatureSource, seed: u32) -> Option { let info = src.info(); - let sample = src.read(&rustgis_data::source::Request { extent: None, limit: 100_000 }).ok()?; + let sample = src.read(&rustgis_data::source::Request { extent: None, limit: 100_000, own: None }).ok()?; let mut ds = rustgis_data::Dataset::new(info.name.clone(), GeometryType::Point, info.fields.clone()); ds.features = sample.features.into(); let mut base = rustgis_map::Symbol::default_for(GeometryType::Point, seed); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 116ce9232c..acd60c9902 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -2135,7 +2135,8 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sky: false, }; let lonlat = crate::render::view_lonlat(s.map(), &view); - let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let own = crate::render::view_own(s.map(), &view); + let reading = s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); // Context around the data (neighbouring borders, the states around in one colour), which the // placement already sets aside, is left out of the legend too, unless "contextInLegend" (#1379). // It is judged again at each other scale the search below draws the map at, as the placement @@ -2409,7 +2410,9 @@ fn publication(s: &mut Session, p: &Value) -> CmdResult { sky: false, }; let lonlat = crate::render::view_lonlat(s.map(), &view); - let reading = s.map_mut().sync_sources(&lonlat, render_scale, true); + let own = crate::render::view_own(s.map(), &view); + let reading = + s.map_mut().sync_sources_in(&lonlat, own.as_ref(), render_scale, true, &rustgis_data::query::Env::default()); let here_context = if tried == asked_scale { context.clone() } else { context_at(s, centred, tried) }; let here = if reading || (tried != asked_scale && crate::render::layout::tile_legends_pending(s.map(), render_scale, &[])) { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 520cdb06e2..fb71876743 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -44590,7 +44590,7 @@ fn postgis_dates_live() { let conn = postgis::connect(&url, false).unwrap(); let t = postgis::find_table(&conn, &format!("public.{table}")).unwrap(); let src = postgis::PostgisSource::open(conn, t, None, None).unwrap(); - let b = src.read(&Request { extent: None, limit: 100 }).unwrap(); + let b = src.read(&Request { extent: None, limit: 100, own: None }).unwrap(); let note = rustgis_data::source::unread_dates_note(&src.info().fields, &b.unread_dates); assert_eq!(note.as_deref(), Some("2 values aren't dates and were read as empty, in 'd', 'ts'")); let f = b.features.iter().find(|f| f.id == 1).unwrap(); diff --git a/crates/engine/tests/integration/portable_projects/reload.rs b/crates/engine/tests/integration/portable_projects/reload.rs index f88cb6a6ce..92eb7d1f04 100644 --- a/crates/engine/tests/integration/portable_projects/reload.rs +++ b/crates/engine/tests/integration/portable_projects/reload.rs @@ -696,7 +696,7 @@ fn reload_reconverts_original_gdal_folder_and_accepts_its_declared_empty_table() assert!(loaded(&reopened, id).features.is_empty()); drop(reopened); assert!(restored_workspace.exists(), "an escaped restored reader pins its fresh workspace"); - let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1, own: None }).unwrap(); assert!(batch.complete && batch.features.is_empty() && batch.skipped == 0); drop(restored_reader); assert!(!restored_workspace.exists(), "the last restored reader releases all conversion artifacts"); @@ -806,7 +806,7 @@ fn reload_reconverts_duckdb_table_and_keeps_only_its_original_geometry_branch() assert!(loaded(&reopened, id).features.is_empty()); drop(reopened); assert!(restored_workspace.exists(), "an escaped restored reader pins its fresh workspace"); - let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1 }).unwrap(); + let batch = restored_reader.read(&rustgis_engine::data::source::Request { extent: None, limit: 1, own: None }).unwrap(); assert!(batch.complete && batch.features.is_empty() && batch.skipped == 0); drop(restored_reader); assert!(!restored_workspace.exists(), "the last restored reader releases all conversion artifacts"); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index 6068463f82..064a10162d 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -640,11 +640,14 @@ impl Layer { /// read, and starts one when the view has moved beyond what was read. With `block`, reads in /// place and waits (for exports). Returns whether a read is still running. pub fn sync_source(&mut self, view: &Extent, block: bool) -> bool { - self.sync_source_with(view, block, &rustgis_data::query::Env::default()) + self.sync_source_with(view, None, block, &rustgis_data::query::Env::default()) } - /// Updates the source window, using the page when its definition query depends on it. - fn sync_source_with(&mut self, view: &Extent, block: bool, env: &rustgis_data::query::Env) -> bool { + /// Updates the source window, using the page when its definition query depends on it. `own` + /// is the view in map units with the map's system: taken when the source, once open, is in + /// that system and tests its features against a box there + /// (`FeatureSource::reads_own_box`). + fn sync_source_with(&mut self, view: &Extent, own: Option<&MapView<'_>>, block: bool, env: &rustgis_data::query::Env) -> bool { let Some(src) = &mut self.source else { return false }; if !src.is_open() { // Opened once after a project loads; a failure is kept, not retried every frame. @@ -691,9 +694,9 @@ impl Layer { // previous view's features. match src.poll(block) { source::Polled::Done(window, batch) => { - src.saw_unread_dates(&window.extent, &batch.unread_dates, &batch.rounded_dates); - src.saw_null_text(&window.extent, &batch.null_text); - src.saw_not_utf8(&window.extent, &batch.not_utf8); + src.saw_unread_dates(&window, &batch.unread_dates, &batch.rounded_dates); + src.saw_null_text(&window, &batch.null_text); + src.saw_not_utf8(&window, &batch.not_utf8); src.saw_read_notes(&batch.notes); self.install(batch.features) } @@ -701,13 +704,16 @@ impl Layer { source::Polled::Idle | source::Polled::Waiting => {} } let Some(src) = &mut self.source else { return false }; - if let Some(e) = src.wanted(view) { - src.start(e, block); + // Decided now that the source is open: one opened in this very call (an export waiting for + // it) reads in map units from its first window. + let own = own.filter(|m| src.reads_own_box() && src.coord_crs() == m.system).map(|m| (m.flat, m.view)); + if let Some(wanted) = src.wanted_in(view, own) { + src.start_wanted(wanted, block); match src.poll(block) { source::Polled::Done(window, batch) => { - src.saw_unread_dates(&window.extent, &batch.unread_dates, &batch.rounded_dates); - src.saw_null_text(&window.extent, &batch.null_text); - src.saw_not_utf8(&window.extent, &batch.not_utf8); + src.saw_unread_dates(&window, &batch.unread_dates, &batch.rounded_dates); + src.saw_null_text(&window, &batch.null_text); + src.saw_not_utf8(&window, &batch.not_utf8); src.saw_read_notes(&batch.notes); self.install(batch.features) } @@ -3049,6 +3055,21 @@ impl Map { /// Syncs drawing windows with the current page for source-side definition queries. pub fn sync_sources_with(&mut self, view: &Extent, scale: f64, block: bool, env: &rustgis_data::query::Env) -> bool { + self.sync_sources_in(view, None, scale, block, env) + } + + /// [`Map::sync_sources_with`], given the view in map units too (`own`, for an upright flat + /// view): a layer whose source is in the map's own system ([`Map::own_system`]) reads its + /// window in map units, which the source tests its features' own boxes against + /// ([`rustgis_data::source::Request::own`]), converting none. + pub fn sync_sources_in( + &mut self, + view: &Extent, + own: Option<&Extent>, + scale: f64, + block: bool, + env: &rustgis_data::query::Env, + ) -> bool { let mut pending = false; let held = self.held_by_group(scale); // Hidden resident layers share the budget too; toggling visibility cannot multiply it. @@ -3059,8 +3080,8 @@ impl Map { pending |= raster.poll_reload(); } if let Some(src) = &mut layer.source { - // Its features are held in longitude/latitude: a datum grid that arrived since - // they were read places them otherwise. + // A datum grid that arrived since its features were read places them otherwise in + // longitude/latitude, where a read finds them and the map draws them from. let grids = rustgis_data::raster::crs::grid_generation(); let new_grids = src.grids.is_some_and(|g| g != grids); src.grids = Some(grids); @@ -3089,12 +3110,34 @@ impl Map { } } } + let flat = self.flat(); + // The view in map units with the map's system, for each layer to take once its source is + // open and says its own system ([`Layer::sync_source_with`]). + let own = own.and_then(|o| Self::own_system_of(&flat, &self.projection).map(|system| MapView { flat: &flat, system, view: *o })); for l in self.layers.iter_mut().filter(|l| l.is_streamed() && l.visible && l.in_scale_range(scale) && !held.contains(&l.id)) { - pending |= l.sync_source_with(view, block, env); + pending |= l.sync_source_with(view, own.as_ref(), block, env); } pending } + /// The system the map's coordinates are in, when geometry there is drawn as it is + /// ([`projection::Flat::held`]): Web Mercator's on its map, and the one a map in a projected + /// system names ([`projection::Flat::direct_system`]). `None` for the globe and every other + /// map. + pub fn own_system(&self) -> Option { + Self::own_system_of(&self.flat(), &self.projection) + } + + fn own_system_of(flat: &projection::Flat, projection: &Projection) -> Option { + if projection.is_globe() { + return None; + } + match flat { + projection::Flat::Mercator => Some(rustgis_data::raster::Crs::WebMercator), + _ => flat.direct_system(), + } + } + /// Adds a raster layer; returns its id. pub fn add_raster(&mut self, name: impl Into, raster: RasterLayer) -> u32 { let id = self.next_id(); @@ -3742,6 +3785,14 @@ impl LonLatCopy { } } +/// A view in map units, with the projection and the system the map's coordinates are in +/// ([`Map::own_system`]), for a streamed layer in that system to read by +/// ([`Map::sync_sources_in`]). +struct MapView<'a> { + flat: &'a projection::Flat, + system: Crs, + view: Extent, +} #[cfg(test)] mod tests { use super::*; @@ -4434,7 +4485,7 @@ mod tests { page: Some(std::sync::Arc::new(rustgis_data::query::SeriesPage { feature_id: 1, name: number.to_string(), number })), ..Default::default() }; - l.sync_source_with(&view, true, &env); + l.sync_source_with(&view, None, true, &env); assert_eq!(l.dataset.features.len(), 1); assert_eq!(l.dataset.value(0, 0), &Value::Int(number as i64 - 1)); assert_eq!(l.drawn_rows_with(1e6, &env), [true]); diff --git a/crates/map/src/source.rs b/crates/map/src/source.rs index a952b4f266..9f36d463b7 100644 --- a/crates/map/src/source.rs +++ b/crates/map/src/source.rs @@ -14,10 +14,13 @@ use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; +use crate::projection::Flat; use rustgis_data::source::{Batch, FeatureSource, Request, SourceInfo}; -use rustgis_geom::Extent; +use rustgis_geom::{Coord, Extent}; use serde::{Deserialize, Serialize}; +#[cfg(test)] +mod own_tests; mod render_lod; mod window; pub(crate) use window::Query; @@ -704,11 +707,15 @@ pub struct Window { pub kept: usize, /// The read kept the definition query's matches: `matched` counts them. pub filtered: bool, + /// The same box in map units, when it was read in the map's own system, which is the + /// source's ([`SourceLayer::wanted_in`]): a later view is tested against it there. + pub own: Option, } /// A read in flight. struct Pending { extent: Extent, + own: Option, result: Mutex>>, still: Option, } @@ -773,11 +780,33 @@ pub(crate) fn another_frame() { /// How many windows a [`Tally`] keeps apart. const WINDOWS_COUNTED: usize = 64; +/// Which read a batch's counts are of ([`SourceLayer::saw_unread_dates`]): its window's +/// longitude/latitude extent and, for one read in map units, its box there. Two windows in map +/// units can share a longitude/latitude extent (both read by the view's where the map can't take +/// their boxes back), so the box tells them apart. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WindowKey { + extent: Extent, + own: Option, +} + +impl From<&Extent> for WindowKey { + fn from(extent: &Extent) -> Self { + WindowKey { extent: *extent, own: None } + } +} + +impl From<&Window> for WindowKey { + fn from(w: &Window) -> Self { + WindowKey { extent: w.extent, own: w.own } + } +} + /// What view reads found, counted for each field by its position, kept for each window read: a /// window read again replaces its counts instead of adding to them. #[derive(Clone, Default)] struct Tally { - windows: Vec<(Extent, Vec)>, + windows: Vec<(WindowKey, Vec)>, /// Counts of windows past [`WINDOWS_COUNTED`], added up as they come. // ponytail: past 64 windows between two notice passes a window read again adds up as before; // keep rows' identity in `Batch` to count exactly. @@ -785,8 +814,9 @@ struct Tally { } impl Tally { - fn saw(&mut self, window: &Extent, counts: &[usize]) { - let at = self.windows.iter().position(|(w, _)| w == window); + fn saw(&mut self, window: impl Into, counts: &[usize]) { + let window = window.into(); + let at = self.windows.iter().position(|(w, _)| *w == window); if counts.iter().all(|n| *n == 0) { if let Some(at) = at { self.windows.remove(at); @@ -794,7 +824,7 @@ impl Tally { } else if let Some((_, kept)) = at.and_then(|at| self.windows.get_mut(at)) { *kept = counts.to_vec(); } else if self.windows.len() < WINDOWS_COUNTED { - self.windows.push((*window, counts.to_vec())); + self.windows.push((window, counts.to_vec())); } else { rustgis_data::source::add_unread_dates(&mut self.rest, counts); } @@ -825,7 +855,7 @@ pub enum Polled { /// A read is still running. Waiting, /// A read finished: install its features. - Done(Window, Batch), + Done(Window, Box), /// A read failed. Failed(String), } @@ -839,10 +869,11 @@ impl SourceLayer { /// [`SourceLayer::take_unread_dates`] says it. Once said, later reads aren't counted: they /// read the same features again, and the notice says Load All Features counts them all. /// Each kind is counted until its own notice is said, so saying one doesn't silence the other. - /// `window` is the extent the batch was read for: reading it again replaces its counts, so the - /// same rows aren't counted twice. Two different windows that overlap still count the rows + /// `window` is what the batch was read for ([`WindowKey`]: its extent, and its box in map + /// units): reading it again replaces its counts, so the same rows aren't counted twice. Two different windows that overlap still count the rows /// they share twice; the notice says "so far" and Load All Features counts them all. - pub fn saw_unread_dates(&mut self, window: &Extent, unread: &[usize], rounded: &[usize]) { + pub fn saw_unread_dates(&mut self, window: impl Into, unread: &[usize], rounded: &[usize]) { + let window = window.into(); if !self.unread_dates_said { self.unread_dates.saw(window, unread); } @@ -870,7 +901,7 @@ impl SourceLayer { /// Keeps what view reads found of text values `` read as null, until /// [`SourceLayer::take_null_text`] says it, as [`SourceLayer::saw_unread_dates`] does for dates. - pub fn saw_null_text(&mut self, window: &Extent, counts: &[usize]) { + pub fn saw_null_text(&mut self, window: impl Into, counts: &[usize]) { if !self.null_text_said { self.null_text.saw(window, counts); } @@ -887,7 +918,7 @@ impl SourceLayer { /// Keeps what view reads found of text values that aren't UTF-8, until /// [`SourceLayer::take_not_utf8`] says it, as [`SourceLayer::saw_unread_dates`] does for dates. - pub fn saw_not_utf8(&mut self, window: &Extent, counts: &[usize]) { + pub fn saw_not_utf8(&mut self, window: impl Into, counts: &[usize]) { if !self.not_utf8_said { let encoding = self.handle.as_ref().map_or("UTF-8", |h| h.text_encoding()); // Counts of another encoding are of another opening's text: they aren't added to these. @@ -1132,7 +1163,7 @@ impl SourceLayer { // Opening a header alone doesn't establish that its payload is readable. Probe the // candidate, never the live source, before the caller commits the replacement. let handle = new.handle.as_deref().ok_or_else(|| named("the replacement source didn't open"))?; - let probe = handle.read(&Request { extent: None, limit: 1 }).map_err(|e| named(&e.to_string()))?; + let probe = handle.read(&Request { extent: None, limit: 1, own: None }).map_err(|e| named(&e.to_string()))?; if probe.features.is_empty() && probe.skipped > 0 { return Err(named(&format!( "no readable features found while checking the replacement ({} rows could not be read)", @@ -1172,6 +1203,12 @@ impl SourceLayer { self.handle.as_ref().map_or(rustgis_data::raster::Crs::LonLat, |h| h.coord_crs()) } + /// Whether its source tests its features against a box in its own system + /// ([`FeatureSource::reads_own_box`]); no until it is open. + pub fn reads_own_box(&self) -> bool { + self.handle.as_ref().is_some_and(|h| h.reads_own_box()) + } + /// A source that can be read whole a chunk at a time, for an export. pub fn visit_source(&self) -> Option> { self.handle.as_ref().filter(|h| h.visits_chunks()).cloned() @@ -1794,21 +1831,48 @@ impl SourceLayer { self.saved_selection.clear(); } - /// The extent to read for a view (longitude/latitude), or `None` when the window serves it. - pub fn wanted(&self, view: &Extent) -> Option { + /// The extent to read for a view, or `None` when the window serves it. `own` is the view in + /// map units with the map's projection, given when the map is in the source's own system: the + /// window is then read and kept in map units too, its longitude/latitude extent the place of + /// that box there. + pub fn wanted_in(&self, view: &Extent, own: Option<(&Flat, Extent)>) -> Option { let v = clamp_world(view); if v.is_empty() { return None; } - if let Some(w) = &self.window { - let all = self.info().map(|i| i.extent).filter(|e| !e.is_empty()); - // Everything has been read: nothing more to fetch, wherever the view goes. - if w.complete && all.is_some_and(|a| contains(&w.extent, &a)) { + let own = own.filter(|(_, o)| !o.is_empty() && [o.min_x, o.min_y, o.max_x, o.max_y].iter().all(|n| n.is_finite())); + // A view past the world (zoomed out) reads the world, as in longitude/latitude: clamped to + // the world's box in map units, or read in longitude/latitude where the map can't place + // the world (a system for an area). + let whole = contains(&v, &Extent::WORLD_LONLAT); + let own = own.and_then(|(flat, o)| { + if !whole { + return Some((flat, o)); + } + let world = map_around(flat, &Extent::WORLD_LONLAT)?; + let clamped = + Extent::new(o.min_x.max(world.min_x), o.min_y.max(world.min_y), o.max_x.min(world.max_x), o.max_y.min(world.max_y)); + (!clamped.is_empty()).then_some((flat, clamped)) + }); + let all = self.info().map(|i| i.extent).filter(|e| !e.is_empty()); + // A window is reused only by a view of the kind it was read for: one read in + // longitude/latitude lacks the features a read in map units also keeps (a place past + // where longitude/latitude goes), and one read in map units holds less than its + // longitude/latitude extent. + if let Some(w) = self.window.as_ref().filter(|w| w.own.is_some() == own.is_some()) { + // Everything has been read: nothing more to fetch, wherever the view goes. Only in + // longitude/latitude, where the source's extent bounds every feature it reads; in map + // units a feature with no place in longitude/latitude lies outside that extent. + if w.own.is_none() && w.complete && all.is_some_and(|a| contains(&w.extent, &a)) { return None; } // The window covers the view, and is complete or not much larger (a view zoomed well // inside a sampled window reads again, for the detail the sample left out). - if contains(&w.extent, &v) && (w.complete || area(&v) * 6.0 > area(&w.extent)) { + let (view, read) = match (own, w.own) { + (Some((_, o)), Some(read)) => (o, read), + _ => (v, w.extent), + }; + if contains(&read, &view) && (w.complete || area(&view) * 6.0 > area(&read)) { return None; } } @@ -1818,15 +1882,34 @@ impl SourceLayer { if self.pending.is_some() { return None; } - Some(clamp_world(&v.padded(0.5, 0.0))) + let lonlat = clamp_world(&v.padded(0.5, 0.0)); + // In map units, the read's longitude/latitude extent is the place of its box there. Where + // the map can't take that box back (a regional system zoomed far out), it is the view's, + // as without one; the window is still kept in map units, so the same view doesn't read + // again. + if let Some((flat, o)) = own { + let padded = o.padded(0.5, 0.0); + let extent = lonlat_around(flat, &padded).map(|e| clamp_world(&e)).filter(|e| !e.is_empty()).unwrap_or(lonlat); + return Some(Wanted { extent, own: Some(padded) }); + } + Some(Wanted { extent: lonlat, own: None }) } /// Starts reading an extent: on a background thread unless `block` (or in the browser). pub fn start(&mut self, extent: Extent, block: bool) { + self.start_wanted(Wanted { extent, own: None }, block); + } + + /// Starts reading what [`SourceLayer::wanted_in`] asked for: on a background thread unless + /// `block` (or in the browser). A box in map units goes to the source as one in its own + /// system ([`Request::own`]). + pub fn start_wanted(&mut self, wanted: Wanted, block: bool) { + let Wanted { extent, own } = wanted; self.ready_cache = None; let Some(h) = self.handle.clone() else { return }; let most = if h.remote().is_some() { REMOTE_VIEW_LIMIT } else { VIEW_LIMIT }; - let req = Request { extent: Some(extent), limit: if self.limit == 0 { most } else { self.limit } }; + let own_box = own.map(|o| (h.coord_crs(), o)); + let req = Request { extent: Some(extent), limit: if self.limit == 0 { most } else { self.limit }, own: own_box }; let budget = self.budget(); let projection = self.projection.clone().unwrap_or(crate::Projection::WebMercator); let estimate = self.estimated_row_bytes; @@ -1834,7 +1917,7 @@ impl SourceLayer { let fields = self.window_fields; let query = self.query.clone(); let still = rustgis_data::source::remote::current_still(); - let pending = Arc::new(Pending { extent, result: Mutex::new(None), still: still.clone() }); + let pending = Arc::new(Pending { extent, own, result: Mutex::new(None), still: still.clone() }); let p = pending.clone(); // A source by its web address: the read runs as its bytes land (on the desktop and in // the browser alike), fetching what it needs in rounds. @@ -1895,7 +1978,7 @@ impl SourceLayer { Err(e) => { self.saved_selection.clear(); self.error = Some(format!("couldn't start reading the layer: {e}")); - self.window = Some(Window { extent, complete: true, matched: 0, kept: 0, filtered: false }); + self.window = Some(Window { extent, complete: true, matched: 0, kept: 0, filtered: false, own }); } } return; @@ -1917,10 +2000,11 @@ impl SourceLayer { self.estimated_row_bytes = cache.mean_bytes; let filtered = cache.filtered; self.ready_cache = Some(cache); - let w = Window { extent: p.extent, complete: b.complete, matched: b.matched, kept: b.features.len(), filtered }; + let w = + Window { extent: p.extent, complete: b.complete, matched: b.matched, kept: b.features.len(), filtered, own: p.own }; self.window = Some(w); self.clear_error(); - return Polled::Done(w, b); + return Polled::Done(w, Box::new(b)); } Some(Err(e)) => { self.pending = None; @@ -1928,7 +2012,7 @@ impl SourceLayer { self.saved_selection.clear(); self.error = Some(e.clone()); // Not read again until the view moves past it. - self.window = Some(Window { extent: p.extent, complete: true, matched: 0, kept: 0, filtered: false }); + self.window = Some(Window { extent: p.extent, complete: true, matched: 0, kept: 0, filtered: false, own: p.own }); return Polled::Failed(e); } None if block && cfg!(not(target_arch = "wasm32")) && start.elapsed() < web_time::Duration::from_secs(60) => { @@ -1972,6 +2056,50 @@ fn contains(outer: &Extent, inner: &Extent) -> bool { && outer.max_y >= inner.max_y } +/// What a view wants read ([`SourceLayer::wanted_in`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Wanted { + /// Longitude/latitude. + pub extent: Extent, + /// The same box in map units, when the map is in the source's own system. + pub own: Option, +} + +/// Where a box in map units lies in longitude/latitude: its edges taken back, 16 places each, +/// reaching a pole inside it (a polar system); `None` when the map can't take a place back. +fn lonlat_around(flat: &Flat, e: &Extent) -> Option { + let mut out = Extent::EMPTY; + const N: usize = 16; + for i in 0..=N { + let t = i as f64 / N as f64; + let (x, y) = (e.min_x + t * e.width(), e.min_y + t * e.height()); + for c in [Coord::new(x, e.min_y), Coord::new(x, e.max_y), Coord::new(e.min_x, y), Coord::new(e.max_x, y)] { + out.expand(flat.inverse(c).filter(|p| p.is_finite())?); + } + } + for pole in [Coord::new(0.0, 90.0), Coord::new(0.0, -90.0)] { + if flat.forward(pole).is_some_and(|p| p.is_finite() && e.contains(p)) { + out = Extent::new(-180.0, out.min_y.min(pole.y), 180.0, out.max_y.max(pole.y)); + } + } + (!out.is_empty()).then_some(out) +} + +/// Where a longitude/latitude box lies in map units: its edges taken there, 16 places each; +/// `None` when the map can't place one of them. +fn map_around(flat: &Flat, e: &Extent) -> Option { + let mut out = Extent::EMPTY; + const N: usize = 16; + for i in 0..=N { + let t = i as f64 / N as f64; + let (x, y) = (e.min_x + t * e.width(), e.min_y + t * e.height()); + for c in [Coord::new(x, e.min_y), Coord::new(x, e.max_y), Coord::new(e.min_x, y), Coord::new(e.max_x, y)] { + out.expand(flat.forward(c).filter(|p| p.is_finite())?); + } + } + (!out.is_empty()).then_some(out) +} + fn clamp_world(e: &Extent) -> Extent { if e.is_empty() { return *e; @@ -2224,6 +2352,18 @@ mod tests { assert_eq!(tally.total(), Some(vec![1])); tally.saw(&b, &[0]); assert_eq!(tally.total(), None); + // Two windows in map units read by the same longitude/latitude extent (where the map can't + // take their boxes back) are told apart by their boxes: the second's clean read leaves the + // first's counts. + let mut apart = Tally::default(); + let first = + super::Window { extent: a, complete: true, matched: 1, kept: 1, filtered: false, own: Some(Extent::new(0.0, 0.0, 1.0, 1.0)) }; + let second = super::Window { own: Some(Extent::new(5.0, 5.0, 6.0, 6.0)), ..first }; + apart.saw(&first, &[1]); + apart.saw(&second, &[0]); + assert_eq!(apart.total(), Some(vec![1])); + apart.saw(&first, &[0]); + assert_eq!(apart.total(), None); let nan = Extent::new(f64::NAN, 0.0, 1.0, 1.0); for _ in 0..2 * WINDOWS_COUNTED { tally.saw(&nan, &[1]); diff --git a/crates/map/src/source/own_tests.rs b/crates/map/src/source/own_tests.rs new file mode 100644 index 0000000000..307da7e66a --- /dev/null +++ b/crates/map/src/source/own_tests.rs @@ -0,0 +1,367 @@ +//! A map in a streamed source's own system reads its window in map units, which the source tests +//! its features' own boxes against ([`Request::own`]); every other map reads in +//! longitude/latitude, as before. + +use super::*; +use rustgis_data::raster::Crs; +use rustgis_data::{Dataset, Field, FieldType, Geometry, GeometryType, Value}; + +/// A source that keeps the requests it is asked. +struct Recording { + inner: Box, + asked: Arc>>, + /// Whether it says it reads by a box in its own system, as its inner source does, or not + /// (as a database read by its longitude/latitude extent). + own_box: bool, +} + +impl FeatureSource for Recording { + fn info(&self) -> &SourceInfo { + self.inner.info() + } + fn coord_crs(&self) -> Crs { + self.inner.coord_crs() + } + fn reads_own_box(&self) -> bool { + self.own_box && self.inner.reads_own_box() + } + fn read(&self, req: &Request) -> rustgis_data::Result { + self.asked.lock().unwrap().push(*req); + self.inner.read(req) + } +} + +fn utm31() -> Crs { + Crs::from_epsg(32631).unwrap() +} + +/// Lines in UTM zone 31N, as a FlatGeobuf: one at Paris, one from Paris to 1e9 m east (which has +/// no place in longitude/latitude), and one 400 km south. +fn lines() -> (Box, Arc>>) { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((451_500.0, 5_411_500.0), (1e9, 5_411_500.0)), vec![Value::Text("far east".into())]); + ds.push(line((451_000.0, 5_011_000.0), (452_000.0, 5_012_000.0)), vec![Value::Text("south".into())]); + ds.held_in = utm31(); + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); + let inner = rustgis_data::source::open_bytes("lines.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone(), own_box: true }), asked) +} + +fn names(layer: &crate::Layer) -> Vec { + let mut out: Vec = layer + .dataset + .features + .iter() + .filter_map(|f| match f.attrs.first() { + Some(Value::Text(t)) => Some(t.clone()), + _ => None, + }) + .collect(); + out.sort(); + out +} + +/// Around Paris: in longitude/latitude, and the same place in UTM 31N. +fn around_paris() -> (Extent, Extent) { + (Extent::new(2.2, 48.75, 2.5, 48.95), Extent::new(440_000.0, 5_400_000.0, 470_000.0, 5_420_000.0)) +} + +fn sync(map: &mut crate::Map, lonlat: &Extent, own: &Extent) { + map.sync_sources_in(lonlat, Some(own), 1000.0, true, &rustgis_data::query::Env::default()); +} + +#[test] +fn a_map_in_the_sources_own_system_reads_its_window_in_map_units() { + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + assert_eq!(map.own_system(), Some(utm31())); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &lonlat, &utm); + let read = asked.lock().unwrap().last().copied().unwrap(); + let padded = utm.padded(0.5, 0.0); + assert_eq!(read.own, Some((utm31(), padded))); + // Its longitude/latitude extent is where that box lies, for a source reading by it. + let e = read.extent.unwrap(); + assert!(e.min_x < 2.1 && e.max_x > 2.6 && e.min_y < 48.7 && e.max_y > 49.0, "{e:?}"); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, Some(padded)); + // Tested in its own system, the line past where longitude/latitude goes is read too. + assert_eq!(names(layer), ["far east", "paris"]); + // A view within the window, in map units, reads nothing more; one past it reads again. + let reads = asked.lock().unwrap().len(); + let nudged = Extent::new(utm.min_x + 5_000.0, utm.min_y, utm.max_x + 5_000.0, utm.max_y); + sync(&mut map, &lonlat, &nudged); + assert_eq!(asked.lock().unwrap().len(), reads); + let away = Extent::new(utm.min_x + 40_000.0, utm.min_y, utm.max_x + 40_000.0, utm.max_y); + sync(&mut map, &lonlat, &away); + assert_eq!(asked.lock().unwrap().len(), reads + 1); +} + +#[test] +fn every_other_map_reads_in_longitude_latitude_as_before() { + let (lonlat, utm) = around_paris(); + // Web Mercator, and a map in another projected system: the box in map units isn't the + // source's, so it isn't given. + for projection in [crate::Projection::WebMercator, crate::Projection::Custom("EPSG:2154".into())] { + let mut map = crate::Map::new("other"); + map.set_projection(projection.clone()); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &lonlat, &utm); + let read = asked.lock().unwrap().last().copied().unwrap(); + assert_eq!(read.own, None, "{projection:?}"); + assert_eq!(read.extent, Some(clamp_world(&lonlat.padded(0.5, 0.0))), "{projection:?}"); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, None, "{projection:?}"); + assert_eq!(names(layer), ["paris"], "{projection:?}"); + } + // Without the view in map units (the globe, a caller that has none), the same. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + map.sync_sources(&lonlat, 1000.0, true); + assert_eq!(asked.lock().unwrap().last().unwrap().own, None); +} + +/// A source of points in `crs`, as a FlatGeobuf. +fn points(crs: Crs, at: &[(f64, f64, &str)]) -> (Box, Arc>>) { + let mut ds = Dataset::new("points", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for (x, y, name) in at { + ds.push(Some(Geometry::Point(Coord::new(*x, *y))), vec![Value::Text((*name).into())]); + } + ds.held_in = crs; + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", crs).unwrap(); + let inner = rustgis_data::source::open_bytes("points.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone(), own_box: true }), asked) +} + +#[test] +fn a_window_read_in_map_units_holds_everything_only_when_its_box_does() { + // Around the South Pole in Antarctic Polar Stereographic, the window's longitude/latitude + // extent reaches every longitude and down to its corners' latitude: points 2,500 km out on + // every side are inside that, but outside the box read (2,000 km out at its edges' middles). + let polar = Crs::from_epsg(3031).unwrap(); + let mut map = crate::Map::new("polar"); + map.set_projection(crate::Projection::Custom("EPSG:3031".into())); + assert_eq!(map.own_system(), Some(polar)); + // A GeoJSON file read in place, whose extent is where its features are, not its box's corners. + let out = 2_500_000.0; + let at = [(0.0, 0.0, "pole"), (out, 0.0, "east"), (-out, 0.0, "west"), (0.0, out, "north"), (0.0, -out, "south")]; + let features: Vec = at + .iter() + .map(|(x, y, name)| { + format!(r#"{{"type":"Feature","properties":{{"name":"{name}"}},"geometry":{{"type":"Point","coordinates":[{x},{y}]}}}}"#) + }) + .collect(); + let path = std::env::temp_dir().join(format!("rustgis-own-polar-{}.geojson", std::process::id())); + std::fs::write( + &path, + format!( + r#"{{"type":"FeatureCollection","crs":{{"type":"name","properties":{{"name":"urn:ogc:def:crs:EPSG::3031"}}}},"features":[{}]}}"#, + features.join(",") + ), + ) + .unwrap(); + let inner = Box::new(rustgis_data::source::geojson::GeoJsonSource::open_path(&path, "points").unwrap()); + let asked = Arc::new(Mutex::new(Vec::new())); + let source: Box = Box::new(Recording { inner, asked: asked.clone(), own_box: true }); + let id = map.add_streamed("points", SourceLayer::from_path("points.fgb", None, source)); + let view = Extent::new(-1_000_000.0, -1_000_000.0, 1_000_000.0, 1_000_000.0); + let lonlat = Extent::new(-180.0, -90.0, 180.0, -80.0); + sync(&mut map, &lonlat, &view); + let layer = map.layer(id).unwrap(); + assert_eq!(names(layer), ["pole"]); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + // Panned onto it, it is read: the window didn't hold everything. + let reads = asked.lock().unwrap().len(); + let there = Extent::new(1_500_000.0, -1_000_000.0, 3_500_000.0, 1_000_000.0); + sync(&mut map, &lonlat, &there); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["east"]); +} + +#[test] +fn a_view_past_the_world_in_map_units_reads_no_more() { + // Points sampled on a map in their own system: zoomed out past the world, a view reaches only + // as far as the world does there, so zooming further out doesn't read the sample again. + for (projection, crs) in [(crate::Projection::WebMercator, Crs::WebMercator), (crate::Projection::Custom("EPSG:32631".into()), utm31())] + { + let mut map = crate::Map::new("world"); + map.set_projection(projection.clone()); + assert_eq!(map.own_system(), Some(crs)); + let (source, asked) = points(crs, &[(0.0, 0.0, "a"), (100_000.0, 0.0, "b"), (0.0, 100_000.0, "c")]); + let mut layer = SourceLayer::from_path("points.fgb", None, source); + layer.limit = 1; + let id = map.add_streamed("points", layer); + let world = Extent::new(-180.0, -85.0, 180.0, 85.0); + sync(&mut map, &world, &Extent::new(-4e7, -4e7, 4e7, 4e7)); + assert!(!map.layer(id).unwrap().source.as_ref().unwrap().window().unwrap().complete, "{projection:?}"); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &world, &Extent::new(-9e7, -9e7, 9e7, 9e7)); + sync(&mut map, &world, &Extent::new(-3e7, -1e7, 5e7, 2e7)); + assert_eq!(asked.lock().unwrap().len(), reads, "{projection:?}"); + } + // On Web Mercator's map, the world's box to 85°, padded by half. + let mut map = crate::Map::new("mercator"); + let (source, asked) = points(Crs::WebMercator, &[(0.0, 0.0, "a")]); + map.add_streamed("points", SourceLayer::from_path("points.fgb", None, source)); + sync(&mut map, &Extent::new(-180.0, -85.0, 180.0, 85.0), &Extent::new(-4e7, -4e7, 4e7, 4e7)); + let (_, read) = asked.lock().unwrap().last().unwrap().own.unwrap(); + let corner = rustgis_geom::lonlat_to_merc(Coord::new(180.0, 85.0)); + let (w, h) = (corner.x * 2.0, corner.y * 2.0); + for (got, want) in [(read.min_x, -w), (read.min_y, -h), (read.max_x, w), (read.max_y, h)] { + assert!((got - want).abs() < 1.0, "{read:?}"); + } +} + +#[test] +fn a_stated_extent_too_small_hides_nothing_in_view() { + // A source whose stated extent misses features (a GeoPackage's stale contents row, a line + // reaching past where longitude/latitude goes): the view is read as it is. + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + let east = Extent::new(utm.min_x + 100_000.0, utm.min_y, utm.max_x + 100_000.0, utm.max_y); + sync(&mut map, &lonlat, &east); + assert_eq!(asked.lock().unwrap().last().unwrap().own, Some((utm31(), east.padded(0.5, 0.0)))); + // 100 km east of Paris only the line reaching 1e9 m east passes, past the stated extent: read. + assert_eq!(names(map.layer(id).unwrap()), ["far east"]); +} + +/// Lines in UTM 31N as a FlatGeobuf: one at Paris and one from 1,200 km east to 1e9 m east, whose +/// far end has no place in longitude/latitude, so the file's stated extent covers Paris only. +fn far_lines() -> (Box, Arc>>) { + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + let line = |a: (f64, f64), b: (f64, f64)| Some(Geometry::Line(vec![vec![Coord::new(a.0, a.1), Coord::new(b.0, b.1)]])); + ds.push(line((451_000.0, 5_411_000.0), (452_000.0, 5_412_000.0)), vec![Value::Text("paris".into())]); + ds.push(line((1_200_000.0, 5_411_000.0), (1e9, 5_411_000.0)), vec![Value::Text("far".into())]); + ds.held_in = utm31(); + let (bytes, _) = rustgis_data::io::write_bytes_in(&ds, "fgb", utm31()).unwrap(); + let inner = rustgis_data::source::open_bytes("far.fgb", bytes, None).unwrap(); + let asked = Arc::new(Mutex::new(Vec::new())); + (Box::new(Recording { inner, asked: asked.clone(), own_box: true }), asked) +} + +#[test] +fn a_complete_window_in_map_units_still_reads_a_feature_past_the_stated_extent() { + let (source, asked) = far_lines(); + let stated = source.info().extent; + assert!(stated.max_x < 3.0, "the stated extent covers Paris only: {stated:?}"); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let id = map.add_streamed("lines", SourceLayer::from_path("far.fgb", None, source)); + let (lonlat, utm) = around_paris(); + sync(&mut map, &lonlat, &utm); + let layer = map.layer(id).unwrap(); + assert_eq!(names(layer), ["paris"]); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + // Panned 750 km east, onto the far line: read, though the window read everything the stated + // extent holds. + let reads = asked.lock().unwrap().len(); + let east = Extent::new(1_190_000.0, 5_400_000.0, 1_220_000.0, 5_420_000.0); + sync(&mut map, &Extent::new(12.0, 48.5, 13.0, 49.5), &east); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["far"]); +} + +#[test] +fn a_window_read_in_longitude_latitude_isnt_reused_for_a_view_in_map_units() { + // Read first without the view in map units (the far line is left out there, as its far end + // has no place in longitude/latitude), then with it on the same map: read again, the far line + // with it. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + let (lonlat, utm) = around_paris(); + map.sync_sources(&lonlat, 1000.0, true); + assert_eq!(names(map.layer(id).unwrap()), ["paris"]); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &lonlat, &utm); + assert_eq!(asked.lock().unwrap().len(), reads + 1); + assert_eq!(names(map.layer(id).unwrap()), ["far east", "paris"]); +} + +#[test] +fn a_source_that_reads_by_longitude_latitude_keeps_its_window_there() { + // A source in the map's system that reads by the longitude/latitude extent whatever it is given + // (another database, a service) gets no box in map units, and its window is kept in + // longitude/latitude, where "everything read" holds and panning past it reads nothing more. + let (lonlat, utm) = around_paris(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + let source: Box = { + let inner = source; + Box::new(Recording { inner, asked: asked.clone(), own_box: false }) + }; + let id = map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + sync(&mut map, &Extent::new(-6.0, 41.0, 10.0, 52.0), &Extent::new(-500_000.0, 4_500_000.0, 1_500_000.0, 5_800_000.0)); + let read = asked.lock().unwrap().last().copied().unwrap(); + assert_eq!(read.own, None); + let layer = map.layer(id).unwrap(); + assert_eq!(layer.source.as_ref().unwrap().window().unwrap().own, None); + assert!(layer.source.as_ref().unwrap().window().unwrap().complete); + let reads = asked.lock().unwrap().len(); + sync(&mut map, &lonlat, &utm); + sync(&mut map, &Extent::new(2.0, 44.5, 3.0, 45.5), &Extent::new(420_000.0, 4_930_000.0, 500_000.0, 5_040_000.0)); + assert_eq!(asked.lock().unwrap().len(), reads); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_layer_opened_as_it_syncs_reads_in_map_units_from_its_first_window() { + // A layer of a project just opened has no source yet: opened in the sync that waits for it (an + // export), its first read is in map units already, so no second read follows. + let mut ds = Dataset::new("lines", GeometryType::Polyline, vec![Field::new("name", FieldType::Text)]); + ds.push( + Some(Geometry::Line(vec![vec![Coord::new(451_000.0, 5_411_000.0), Coord::new(452_000.0, 5_412_000.0)]])), + vec![Value::Text("paris".into())], + ); + ds.held_in = utm31(); + let path = std::env::temp_dir().join(format!("rustgis-own-opened-{}.fgb", std::process::id())); + rustgis_data::io::write_path_in(&ds, &path, utm31()).unwrap(); + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let src = SourceLayer { path: Some(path.display().to_string()), ..SourceLayer::default() }; + let id = map.add_streamed("lines", src); + assert!(!map.layer(id).unwrap().source.as_ref().unwrap().is_open()); + let (lonlat, utm) = around_paris(); + sync(&mut map, &lonlat, &utm); + let window = *map.layer(id).unwrap().source.as_ref().unwrap().window().unwrap(); + assert_eq!(window.own, Some(utm.padded(0.5, 0.0))); + assert_eq!(names(map.layer(id).unwrap()), ["paris"]); + let _ = std::fs::remove_file(path); +} + +#[test] +fn a_view_the_map_cant_place_reads_once() { + // On a UTM map, a view the map can't take back to longitude/latitude: read once, by the + // view's longitude/latitude, the window kept in map units, so the same view reads nothing more. + let mut map = crate::Map::new("utm"); + map.set_projection(crate::Projection::Custom("EPSG:32631".into())); + let (source, asked) = lines(); + map.add_streamed("lines", SourceLayer::from_path("lines.fgb", None, source)); + // A view whose longitude/latitude is known, but whose padded box reaches past where the + // system goes, so the map can't take that box back. + let (lonlat, _) = around_paris(); + let edge = Extent::new(1e8, 1e8, 1.1e8, 1.1e8); + sync(&mut map, &lonlat, &edge); + let reads = asked.lock().unwrap().len(); + let first = asked.lock().unwrap().last().copied().unwrap(); + assert!(first.own.is_some()); + assert_eq!(first.extent, Some(lonlat.padded(0.5, 0.0)), "read by the view's longitude/latitude"); + for _ in 0..3 { + sync(&mut map, &lonlat, &edge); + } + assert_eq!(asked.lock().unwrap().len(), reads); +} diff --git a/crates/map/src/source/window.rs b/crates/map/src/source/window.rs index e618399ba2..bcced86262 100644 --- a/crates/map/src/source/window.rs +++ b/crates/map/src/source/window.rs @@ -425,7 +425,8 @@ mod tests { let scratch = Dataset::new("Polar", GeometryType::Polygon, vec![]); let expr = rustgis_data::query::parse(&query.text, &scratch).unwrap(); let error = - read_filtered(source.as_ref(), &Request { extent: None, limit: 1 }, usize::MAX, scratch, &expr, true, &query.env).unwrap_err(); + read_filtered(source.as_ref(), &Request { extent: None, limit: 1, own: None }, usize::MAX, scratch, &expr, true, &query.env) + .unwrap_err(); assert!(error.to_string().contains("Polar") && error.to_string().contains("2 ring(s) in 2 feature(s)"), "{error}"); // Text mentioning $area is ordinary text, not a request to measure the geometry. let text = Query { text: "'$area' = '$area'".into(), fields: vec![], env: Default::default() }; @@ -522,7 +523,7 @@ mod tests { let source = source(); let projection = crate::Projection::WebMercator; for estimate in [0, 100] { - let request = Request { extent: None, limit: 0 }; + let request = Request { extent: None, limit: 0, own: None }; let (batch, cache) = read(source.as_ref(), &request, 4096, &projection, estimate).unwrap(); assert!(batch.features.is_empty()); assert!(cache.projected.is_empty()); @@ -674,7 +675,7 @@ mod tests { #[test] fn one_feature_can_use_the_optional_display_reservation() { let source = source(); - let req = Request { extent: None, limit: 1 }; + let req = Request { extent: None, limit: 1, own: None }; let projection = crate::Projection::WebMercator; let (mut full, cache) = read_mode(source.as_ref(), &req, 1, &projection, 0, true, None, None).unwrap(); full.features.shrink_to_fit(); diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index d01a44e011..534d741571 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -662,8 +662,9 @@ fn draw_page( { let view = View { width: fw, height: fh, pixels_per_point: 1.0, camera: cam, sky: false }; let lonlat = crate::view_lonlat(map, &view); + let own = crate::view_own(map, &view); let scale = map.ground_res_at(&cam) / rustgis_geom::PIXEL_M; - map.sync_sources_with(&lonlat, scale, true, env); + map.sync_sources_in(&lonlat, own.as_ref(), scale, true, env); let mut failed_source = None; let Some(entries) = complete_shown_legends(map, scale, *show_no_data, &mut failed_source, env) else { *source_error = failed_source_error(map, failed_source); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 95b11ad703..8bc0b9695e 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2099,6 +2099,12 @@ fn blend_over(dst: &mut tiny_skia::PixmapMut, src: &Pixmap, x: i64, y: i64) { } } +/// What a view shows in map units, for streamed layers in the map's own system to read by +/// ([`Map::sync_sources_in`]); `None` on the globe. +pub fn view_own(map: &Map, view: &View) -> Option { + (!map.projection.is_globe()).then(|| view.camera.extent(view.width, view.height)) +} + /// The longitude/latitude extent a view shows (the whole world on the globe, or when the /// projection can't say). pub fn view_lonlat(map: &Map, view: &View) -> Extent { @@ -4111,10 +4117,11 @@ pub fn sync_tilted_view(map: &mut Map, view: &View) -> bool { /// running. fn sync_tilted(map: &mut Map, view: &View, bands: &[rustgis_map::camera::Band], block: bool, env: &Env) -> bool { let lonlat = view_lonlat(map, view); + let own = view_own(map, view); let mut pending = false; for b in bands { let scale = map.ground_res_at(&b.camera) / rustgis_geom::PIXEL_M; - pending |= map.sync_sources_with(&lonlat, scale, block, env); + pending |= map.sync_sources_in(&lonlat, own.as_ref(), scale, block, env); } pending } @@ -4485,7 +4492,7 @@ fn render_frame( let label_env = env.at_scale(Some(label_scale)); let data_pending = match labels_to { Labels::Tilted(..) | Labels::Shared => false, - _ => map.sync_sources_with(&view_lonlat(map, view), scale, full_res_rasters, env), + _ => map.sync_sources_in(&view_lonlat(map, view), view_own(map, view).as_ref(), scale, full_res_rasters, env), }; let globe = map.projection.is_globe().then(|| Globe::new(&view.camera, view.width, view.height)); let (flat, key) = (map.flat(), map.projection.code()); diff --git a/crates/tiles/src/embeddings.rs b/crates/tiles/src/embeddings.rs index bdfab9fa9a..8b519ba1a7 100644 --- a/crates/tiles/src/embeddings.rs +++ b/crates/tiles/src/embeddings.rs @@ -454,7 +454,7 @@ pub fn aef_place(url: &str) -> Option { pub type Found = (Vec, bool); fn aef_request(bbox: [f64; 4]) -> Request { - Request { extent: Some(Extent::new(bbox[0], bbox[1], bbox[2], bbox[3])), limit: MAX_INDEX_ROWS } + Request { extent: Some(Extent::new(bbox[0], bbox[1], bbox[2], bbox[3])), limit: MAX_INDEX_ROWS, own: None } } /// Finds AlphaEarth's tiles of a year in a box (longitude/latitude), reading the index in place. diff --git a/docs/user-guide/data.md b/docs/user-guide/data.md index 9d867d3716..96a18872ff 100644 --- a/docs/user-guide/data.md +++ b/docs/user-guide/data.md @@ -1436,7 +1436,12 @@ dataset. The layer reads features in view in the background as the map moves, us indexes: the GeoPackage R-tree, the FlatGeobuf packed R-tree, GeoParquet row-group bounding boxes, or a cached Shapefile R-tree built from the shapes' bounding boxes. When a local file's view holds more than 250,000 features (100,000 in the web app), the layer draws an -evenly spread sample of them and its tooltip in Layers says so: zoom in to see them all. Remote files have lower limits (see +evenly spread sample of them and its tooltip in Layers says so: zoom in to see them all. On a map +in the file's own coordinate system (a UTM file on a UTM map), the view is read in map units: each +feature's own bounding box is compared with it as the file holds it, with no coordinate +converted, and a feature reaching past where longitude/latitude goes is read too (except from a +GeoJSON file, which leaves such a feature out when it opens, and says so). On any other +map, each feature is placed in longitude/latitude to be compared. Remote files have lower limits (see [Data formats](data-formats.md)). Smaller files load whole; `layer.addData` with `"stream": true` or `false` overrides the choice.