From 4e7d6cb4e784155e47779d1284a6eab1e16ab539 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 14:58:03 -0300 Subject: [PATCH 1/4] feat(render): a polygon block's holes are wells with their own walls (#2318) A block cut to polygons now cuts their holes too: the ground inside a hole isn't drawn, its walls face into it and stand where they face the eye (its far side), and its floor is drawn at the base. The "holes aren't cut" notice is gone. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/project.rs | 10 +- crates/engine/src/cmd/view.rs | 11 +- crates/engine/src/tests.rs | 9 +- crates/map/src/view.rs | 4 +- crates/render/src/block.rs | 157 +++++++++++++++++++++++---- crates/render/src/lib.rs | 63 +++++++++++ crates/render/src/terrain/outline.rs | 111 +++++++++++++------ docs/user-guide/maps.md | 7 +- 8 files changed, 291 insertions(+), 81 deletions(-) diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 494be01942..03c82d34b0 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -413,9 +413,9 @@ fn reset(s: &mut Session, p: Project) { .collect(); // A block cut to polygons (#2318) whose layer is missing or picks no polygon with an area // isn't drawn: said, and kept, so a polygon layer of that name, or an edit, brings it back. - // One whose outline was simplified to stay under 65 535 sides, or whose polygons have holes - // (not cut), is said as `map.terrain` says it. Each outline is read once. - let (mut uncut, mut simplified, mut holed) = (Vec::new(), Vec::new(), Vec::new()); + // One whose outline was simplified to stay under 65 535 sides is said as `map.terrain` says + // it. Each outline is read once. + let (mut uncut, mut simplified) = (Vec::new(), Vec::new()); for m in &s.project.maps { let Some(rustgis_map::view::BlockShape::Polygon { layer, filter }) = m.view.terrain.as_ref().and_then(|t| t.block.as_ref()).map(|b| &b.shape) @@ -427,7 +427,6 @@ fn reset(s: &mut Session, p: Project) { continue; }; simplified.extend(super::view::outline_simplified(layer, &o).map(|said| format!("{}: {said}", m.name))); - holed.extend(super::view::outline_holes(layer, &o).map(|said| format!("{}: {said}", m.name))); } match simplified.as_slice() { [] => {} @@ -437,9 +436,6 @@ fn reset(s: &mut Session, p: Project) { false, ), } - if !holed.is_empty() { - s.notify(holed.join("; "), false); - } if !uncut.is_empty() { s.notify( format!( diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index dd3b4f0a86..15deb75f66 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -49,7 +49,7 @@ pub fn commands() -> Vec { }).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"mode": "none"|"distance", "distance"?: metres from the view's centre}"#), C::new("map.terrain", "Terrain", "View › Scene", terrain).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r##"{"layer"?: a DEM raster layer (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons' outer rings, holes not cut, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "water"?: the terrain's water shown in the walls' section {"depth"?: metres from the level to the floor, "field"?: a numeric field of the water layer holding each one's depth} (one of them needed), or false}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##, + r##"{"layer"?: a DEM raster layer (heights in metres; without layer or tiles, and no terrain yet, the active layer when it is a raster) | "tiles"?: elevation tile URL with {z}/{x}/{y}, "encoding"?: "terrarium"|"mapbox" (tiles; default terrarium), "exaggeration"?: 0 to 20 (default 1, or the terrain's), "block"?: a block diagram {"extent"?: "layer" (the DEM's extent, default) | [xmin, ymin, xmax, ymax] in map units (needed over tiles), "depth"?: metres from the lowest ground to the base (default half the relief, at least 100), "walls"?: "#RRGGBB" (default #C8B89A) | {"color"?: "#RRGGBB" (default #C8B89A), "layer"?: a polygon layer that holds all its features (not one read a view at a time; it may be hidden): its symbology colours the walls where its polygons meet the block's edge, and the walls are color off its polygons}, "shape"?: "box" (default) | "circle" (the largest circle in the box, its walls round it) | {"layer": a polygon layer, "where"?: sql (picks its polygons, as a definition query)} (the ground inside the polygons, each hole a well with its own walls and its floor at the base, the box round them: no extent), "radius"?: a circle's radius in map units (default: the largest in the box), "water"?: the terrain's water shown in the walls' section {"depth"?: metres from the level to the floor, "field"?: a numeric field of the water layer holding each one's depth} (one of them needed), or false}, keys left out stay as the block had them and null puts one back to its default (a new block takes the defaults), and the block's "water" is given whole each time, replacing the old, or false to take it off (default: as it was), "water"?: water bodies drawn flat at their level {"layer": a polygon layer, "level"?: a numeric field of levels in metres (default: each polygon's lowest height along its shore), "glint"?: 0 to 1, how brightly a tilted view's water shines where it reflects the sun toward the eye (default 0.3; 0: none), "shore"?: 0 to 1, how dark the band along the water's shore is at the outline, fading a few pixels inside it (default 0.35; 0: none)}, or false to take it off (default: as it was), "off"?: true}"##, ), C::new("map.exportOrbit", "Export Orbit", "View › Scene", |s, p| super::exports::write_here(s, p, "map.exportOrbit")).inputs(orbit_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .view() @@ -478,13 +478,6 @@ pub(crate) fn outline_simplified(layer: &str, o: &rustgis_render::terrain::Outli }) } -/// The holes of a polygon block's polygons, which aren't cut: the ground inside them is drawn -/// (said when it is set and when a project opens). -pub(crate) fn outline_holes(layer: &str, o: &rustgis_render::terrain::Outline) -> Option { - let n = o.holes(); - (n > 0).then(|| format!("{n} hole(s) in the polygons of '{layer}' the block is cut to aren't cut: the ground inside them is drawn")) -} - /// The name of the polygon layer `name` for `what` (water, a block's walls), checked: a polygon /// layer (`holds` says of what) holding all its polygons, of a name of its own. fn polygon_layer(s: &Session, name: &str, what: &str, holds: &str) -> Result { @@ -839,7 +832,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { m.view.terrain = Some(t); // A polygon block's outline simplified past a third of the finest mesh cell, or short of its // smallest rings, to stay under 65 535 sides: said, with how far. - for said in outline.iter().flat_map(|(layer, o)| [outline_simplified(layer, o), outline_holes(layer, o)]).flatten() { + for said in outline.iter().flat_map(|(layer, o)| outline_simplified(layer, o)) { s.notify(format!("Terrain: {said}"), false); } if block_cut { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index abfdd7b115..d792a688d8 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15624,18 +15624,15 @@ fn terrain_block_cut_to_polygons() { let mut opened = Session::new(Project::default()); crate::cmd::project::reset_to(&mut opened, s.project.clone()); assert!(!simplified(&s) && !simplified(&opened), "{:?}", opened.notices); - // Nor holes, which a polygon with one gives: said once as it is set and as it opens. - let holes = |s: &Session| s.notices.iter().filter(|n| n.text.contains("hole(s) in the polygons")).count(); - assert_eq!((holes(&s), holes(&opened)), (0, 0), "{:?}", opened.notices); + // A polygon with a hole is cut with a well there (reported), which leaves nothing to say. let mut holed = Session::new(Project::default()); crate::cmd::project::reset_to(&mut holed, s.project.clone()); let v = holed.run("map.terrain", &json!({"layer": dem, "block": {"shape": {"layer": "bacias", "where": "nome = 'd'"}}})).unwrap(); assert_eq!(v["block"]["outline"]["holes"], json!(1)); - assert_eq!(holes(&holed), 1, "{:?}", holed.notices); + assert_eq!(v["block"]["outline"]["sides"], json!(8)); let mut opened = Session::new(Project::default()); crate::cmd::project::reset_to(&mut opened, holed.project.clone()); - assert_eq!(holes(&opened), 1, "{:?}", opened.notices); - assert!(opened.notices.iter().any(|n| n.text.contains("1 hole(s) in the polygons of 'bacias'")), "{:?}", opened.notices); + assert!(!holed.notices.iter().chain(&opened.notices).any(|n| n.text.contains("hole")), "{:?}", opened.notices); // A saved block cut to a polygon off the DEM is kept as the project opens, and said. let mut far = s.project.clone(); if let Some(b) = far.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()) { diff --git a/crates/map/src/view.rs b/crates/map/src/view.rs index 6a8ada110c..2bbd5a3eb1 100644 --- a/crates/map/src/view.rs +++ b/crates/map/src/view.rs @@ -249,8 +249,8 @@ pub enum BlockShape { radius: Option, }, /// The polygons of `layer` (by name, as the terrain's DEM) that `filter` picks among the rows - /// its definition query keeps (all of them without one): the ground inside their outer rings, - /// their holes not cut, the box being the one round them. + /// its definition query keeps (all of them without one): the ground inside them, each hole a + /// well, the box being the one round them. Polygon { layer: String, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 9f46c55ace..74d8209231 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -197,8 +197,9 @@ fn corners_box(m: [Coord; 3]) -> (Coord, Coord) { /// The parts of the triangle `m` (Web Mercator) inside the polygon outline `o`, each a polygon /// (concave, maybe) anticlockwise: each stretch of a ring inside the triangle runs from where it /// enters to where it leaves, then along the triangle's edge (anticlockwise, as the rings run) -/// to where the next stretch of the same ring enters, until the part closes. A ring wholly inside -/// is a part of its own. A ring that crosses none of it but holds it (its middle) adds the +/// to where the next stretch of the same polygon (its outer ring or a hole) enters, until the +/// part closes. An outer ring wholly inside is a part of its own, and a hole wholly inside is cut +/// from the part round it. A polygon that crosses none of it but holds it (its middle) adds the /// whole triangle, which several touching or overlapping polygons can give alongside the parts of /// another ring that crosses it. A corner is marked with the outline's side (plus one) the part's edge from it runs along, 0 /// along the triangle's edge. Only the sides near the triangle are looked at ([`Outline::near`]). @@ -211,11 +212,12 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { } let t = if area > 0.0 { m } else { [m[0], m[2], m[1]] }; let mark = |p: Coord, on: u32| -> Clipped { ([0, 1, 2].map(|i| cross(m[(i + 1) % 3], m[(i + 2) % 3], p) / area), p, on) }; - // The whole triangle when a ring that doesn't cross it holds its middle (a point strictly - // inside, so a ring only touching it doesn't count). + // The whole triangle when a polygon none of whose rings crosses it holds its middle (a point + // strictly inside, so a ring only touching it doesn't count), its holes wholly inside the + // triangle left out (they are cut from it below). let middle = Coord::new((t[0].x + t[1].x + t[2].x) / 3.0, (t[0].y + t[1].y + t[2].y) / 3.0); - let whole = |crossing: &[u32]| -> Option> { - o.inside_ring(middle, |r| !crossing.contains(&r)).then(|| t.iter().map(|c| mark(*c, 0)).collect()) + let whole = |crossing: &[u32], within: &[u32]| -> Option> { + o.inside_ring(middle, |r| !crossing.contains(&o.kind(r).0) && !within.contains(&r)).then(|| t.iter().map(|c| mark(*c, 0)).collect()) }; // How far inside edge `e` (from corner e to the next) `p` lies. let len = [0, 1, 2].map(|e| (t[(e + 1) % 3].x - t[e].x).hypot(t[(e + 1) % 3].y - t[e].y).max(1e-300)); @@ -244,11 +246,8 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { } } if parts.is_empty() { - return whole(&[]).into_iter().collect(); + return whole(&[], &[]).into_iter().collect(); } - let mut crossing: Vec = parts.iter().map(|p| sides[p.0].ring).collect(); - crossing.sort_unstable(); - crossing.dedup(); let find = |k: usize| parts.binary_search_by_key(&k, |p| p.0).ok(); let at = |k: usize, u: f64| sides.get(k).map_or(t[0], |s| Coord::new(s.a.x + (s.z.x - s.a.x) * u, s.a.y + (s.z.y - s.a.y) * u)); // Where on the triangle's edge a point lies: the edge's number plus the share along it. @@ -294,21 +293,45 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { corners.push(mark(out, 0)); chains.push((sides[parts[i].0].ring, corners, into, place(out))); } - // Rings wholly inside the triangle: parts of their own. - let mut out: Vec> = Vec::new(); + // The polygons whose rings cross the triangle's edges. + let mut crossing: Vec = chains.iter().map(|c| o.kind(c.0).0).collect(); + crossing.sort_unstable(); + crossing.dedup(); + // Rings wholly inside the triangle: an outer one a part of its own, a hole cut from the part + // of its polygon round it, below. + let mut out: Vec<(u32, Vec)> = Vec::new(); + let mut wells: Vec<(u32, Vec)> = Vec::new(); for i in 0..parts.len() { if !used[i] { + let ring = sides[parts[i].0].ring; let (corners, _) = follow(i, &mut used); if corners.len() >= 3 { - out.push(corners); + let (polygon, hole) = o.kind(ring); + if hole { wells.push((ring, corners)) } else { out.push((polygon, corners)) } } } } - out.extend(whole(&crossing)); - if chains.is_empty() { - return out; + // The whole triangle from a polygon that neither crosses it, nor lies in it, nor has a hole + // in it; failing one, from each polygon with holes in it whose other rings hold it, those + // holes cut from it below. + let within: Vec = wells.iter().map(|w| w.0).collect(); + let mut holed: Vec = + wells.iter().map(|w| o.kind(w.0).0).filter(|p| !crossing.contains(p) && !out.iter().any(|q| q.0 == *p)).collect(); + holed.sort_unstable(); + holed.dedup(); + let crossed: Vec = crossing.iter().chain(out.iter().map(|p| &p.0)).chain(&holed).copied().collect(); + if let Some(w) = whole(&crossed, &[]) { + out.push((u32::MAX, w)); + } else { + for p in holed { + if o.inside_ring(middle, |r| o.kind(r).0 == p && !within.contains(&r)) { + out.push((p, t.iter().map(|c| mark(*c, 0)).collect())); + } + } } - // Each chain, then the triangle's edge on to the next chain of its ring, until back. + // Each chain, then the triangle's edge on to the next chain of its polygon (its outer ring + // or a hole: the rings of one polygon don't cross, so the next one met round the edge + // bounds the same ground), until back. let mut done = vec![false; chains.len()]; for c0 in 0..chains.len() { if done[c0] { @@ -318,10 +341,11 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { loop { done[c] = true; piece.extend(chains[c].1.iter().copied()); - let (ring, leaves) = (chains[c].0, chains[c].3); + let (polygon, leaves) = (o.kind(chains[c].0).0, chains[c].3); let ahead = |s: f64| (s - leaves).rem_euclid(3.0); - let Some(n) = - (0..chains.len()).filter(|j| chains[*j].0 == ring).min_by(|a, b| ahead(chains[*a].2).total_cmp(&ahead(chains[*b].2))) + let Some(n) = (0..chains.len()) + .filter(|j| o.kind(chains[*j].0).0 == polygon) + .min_by(|a, b| ahead(chains[*a].2).total_cmp(&ahead(chains[*b].2))) else { break; }; @@ -339,10 +363,39 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { c = n; } if piece.len() >= 3 { - out.push(piece); + out.push((o.kind(chains[c0].0).0, piece)); + } + } + // A hole wholly inside the triangle is cut from its polygon's part round it, joined to it + // by a seam there and back from the part's nearest corner: the hole runs the other way, so + // filled by winding it stays empty, and the seam's two edges, on no side, give no wall. A + // hole in no part of its polygon (one lying outside its own outer ring) cuts nothing. + for (ring, hole) in wells { + let polygon = o.kind(ring).0; + let Some(h) = hole.first().copied() else { continue }; + let Some((_, part)) = out.iter_mut().find(|(p, part)| *p == polygon && holds(part, h.1)) else { continue }; + let d = |c: &Clipped| (c.1.x - h.1.x).hypot(c.1.y - h.1.y); + let Some(i) = (0..part.len()).min_by(|a, b| d(&part[*a]).total_cmp(&d(&part[*b]))) else { continue }; + let mut cut = part[..=i].to_vec(); + cut.last_mut().into_iter().for_each(|c| c.2 = 0); + cut.extend(hole.iter().copied()); + cut.push((h.0, h.1, 0)); + cut.extend(part[i..].iter().copied()); + *part = cut; + } + out.into_iter().map(|p| p.1).collect() +} + +/// Whether `p` lies inside the polygon `part` (by its corners' places), even-odd. +fn holds(part: &[Clipped], p: Coord) -> bool { + let mut inside = false; + for (i, a) in part.iter().enumerate() { + let z = part[(i + 1) % part.len()]; + if (a.1.y > p.y) != (z.1.y > p.y) && p.x < a.1.x + (p.y - a.1.y) / (z.1.y - a.1.y) * (z.1.x - a.1.x) { + inside = !inside; } } - out + inside } /// How near a corner must lie to a side of the box to be on it (Web Mercator metres). @@ -1263,6 +1316,24 @@ pub(crate) fn draw_walls( let mut mask: Option = None; // The part of it the last run filled, cleared before the next: a round block has hundreds of sides. let mut dirty: Option = None; + // A polygon block's wells: each hole's floor at the base, in the walls' colour as shaded at + // their foot facing away from the light, drawn first, so the ground and walls in front of it + // cover it and it shows only down the well. A hole with no stretch under the ground drawn + // isn't in the picture: no floor. + for sides in b.outline.iter().flat_map(|o| o.hole_sides()) { + let Some(depth) = edges.iter().filter(|e| sides.contains(&usize::from(e.side))).map(|e| e.depth).min_by(f64::total_cmp) else { + continue; + }; + let mut floor = PathBuilder::new(); + for (i, p) in sides.filter_map(|i| foot(b.side(i).1)).enumerate() { + if i == 0 { floor.move_to(pt(p).0, pt(p).1) } else { floor.line_to(pt(p).0, pt(p).1) } + } + floor.close(); + if let Some(path) = floor.finish() { + let tone = b.walls.shade(0.6 * 0.72).lerp(fog, fog_at(depth)); + pm.fill_path(&path, &paint(tone, 1.0), FillRule::Winding, Transform::identity(), None); + } + } for (s, key, stretches) in &walk { let (s, key) = (*s, *key); let Some(n) = faces[s] else { continue }; @@ -1648,6 +1719,48 @@ mod tests { parts.iter().map(ring).sum() } + #[test] + fn a_polygon_blocks_hole_is_cut_from_the_triangles_round_it_as_a_well() { + // #2318: a square 10 a side with a hole 2 a side in its middle (both given anticlockwise: + // the hole is turned round). Inside the hole nothing is ground; a triangle across its + // edge keeps the part outside it, its edge along the hole's side; one round the whole + // hole keeps all but the hole, in one part joined to it by a seam that gives no wall. + let ring = |c: &[(f64, f64)]| c.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); + let square = ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]); + let hole = ring(&[(4.0, 4.0), (6.0, 4.0), (6.0, 6.0), (4.0, 6.0)]); + // A hole of a polygon whose outer ring has no area goes with it. + let flat = ring(&[(20.0, 0.0), (30.0, 0.0), (25.0, 0.0)]); + let alone = Outline::from_polygons(vec![vec![square.clone()], vec![flat, hole.clone()]]).expect("an outline"); + assert_eq!((alone.side_count(), alone.holes(), alone.dropped()), (4, 0, 0)); + let o = Outline::from_polygons(vec![vec![square, hole]]).expect("an outline"); + assert_eq!((o.side_count(), o.holes()), (8, 1)); + assert!(o.contains(Coord::new(2.0, 2.0)) && !o.contains(Coord::new(5.0, 5.0))); + let b = Block { x0: 0.0, y0: 0.0, x1: 10.0, y1: 10.0, outline: Some(Arc::new(o)), ..unit_block() }; + assert!(pieces([Coord::new(4.5, 4.5), Coord::new(5.5, 4.5), Coord::new(4.5, 5.5)], &b).is_empty()); + // Across the hole's west side: x 3 to 5, so the half from x 4 is in the hole. + let across = pieces([Coord::new(3.0, 4.5), Coord::new(5.0, 4.5), Coord::new(3.0, 5.5)], &b); + assert!((area(&across) - (1.0 - 0.25)).abs() < 1e-9, "{}", area(&across)); + let mut out = Vec::new(); + let screen = |p: &Vec| p.iter().map(|c| (c.1.x, c.1.y)).collect::>(); + across.iter().for_each(|p| edges(&b, p, &screen(p), 1.0, &mut out)); + assert!( + out.len() == 1 && out[0].ends.iter().all(|e| (e.x - 4.0).abs() < 1e-9), + "{:?}", + out.iter().map(|e| e.ends).collect::>() + ); + // Round the whole hole: the triangle's 32 less the hole's 4, its four sides the walls. + let round = pieces([Coord::new(1.0, 1.0), Coord::new(9.0, 1.0), Coord::new(5.0, 9.0)], &b); + assert!(round.len() == 1 && (area(&round) - 28.0).abs() < 1e-9, "{}", area(&round)); + out.clear(); + edges(&b, &round[0], &screen(&round[0]), 1.0, &mut out); + let mut sides: Vec = out.iter().map(|e| e.side).collect(); + sides.sort_unstable(); + assert_eq!(sides, vec![4, 5, 6, 7]); + // A hole's walls face into it: its north side (its first, run east) faces south. + assert_eq!(b.side(4).1, Coord::new(4.0, 6.0)); + assert!(b.beyond(4, Coord::new(5.0, 5.0)) > 0.0 && b.beyond(4, Coord::new(5.0, 7.0)) < 0.0); + } + #[test] fn a_polygon_block_cuts_a_triangle_across_its_inner_corner_to_the_part_inside() { // #2318: an L, the square 10 a side without its north-east quarter (given clockwise: it is diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 78ad8c8b27..df53479346 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -11476,6 +11476,69 @@ mod tests { assert!(sandy(seen), "{seen:?}"); } + #[test] + fn a_polygon_blocks_hole_is_a_well_with_its_far_wall_and_its_floor() { + // #2318: flat ground 500 m high cut to a 2 km square with a 600 m hole in its middle, + // seen from the south. Down the hole the far (north) wall shows, and seen from nearly + // above, its floor at the base: both in the walls' sandy brown, where without the hole + // the grey ground showed. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: -5000.0, origin_y: 5000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let dem = + Raster::new("dem", 500, 500, vec![vec![500.0; 500 * 500]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.add_raster("dem", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + let deg = |x: f64, y: f64| rustgis_geom::merc_to_lonlat(Coord::new(x, y)); + let ring = |r: f64| [(-r, -r), (r, -r), (r, r), (-r, r), (-r, -r)].iter().map(|&(x, y)| deg(x, y)).collect::>(); + let mut d = Dataset::new("area", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + d.push(Some(Geometry::Polygon(vec![vec![ring(1000.0), ring(300.0)]])), vec![Value::Text("holed".into())]); + d.push(Some(Geometry::Polygon(vec![vec![ring(1000.0)]])), vec![Value::Text("plain".into())]); + m.add_dataset(d); + let frame = |m: &mut Map, name: &str, pitch: f64| { + let camera = Camera { center: Coord::new(0.0, 0.0), res: 10.0, bearing: 0.0, pitch }; + let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + let shape = rustgis_map::view::BlockShape::Polygon { layer: "area".into(), filter: Some(format!("name = '{name}'")) }; + m.view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 1.0, + block: Some(rustgis_map::view::TerrainBlock { + extent: None, + depth: Some(1000.0), + walls: rustgis_map::view::BLOCK_WALLS, + walls_layer: None, + water: None, + shape, + }), + water: None, + }); + let g = terrain::Ground::of(m, &camera).expect("terrain"); + let per_unit = g.per_unit(Coord::new(0.0, 0.0)); + let r = render(m, &view).expect("a frame"); + let at = move |x: f64, y: f64, metres: f64| { + let (u, v) = camera.ground_px(Coord::new(x, y)); + camera.project_raised(u, v, metres / per_unit / camera.res, view.width, view.height).expect("in view") + }; + (r, at) + }; + let px = |r: &Rendered, p: (f64, f64)| r.pixmap.pixel(p.0 as u32, p.1 as u32).expect("in the frame").demultiply(); + let sandy = |c: tiny_skia::ColorU8| c.red() > c.green() && c.green() > c.blue() + 8; + // The far wall, just under its top: the ray meets nothing in front of it. + let (holed, at) = frame(&mut m, "holed", 60.0); + let (plain, _) = frame(&mut m, "plain", 60.0); + let wall = at(0.0, 300.0, 440.0); + assert!(sandy(px(&holed, wall)), "{:?}", px(&holed, wall)); + assert!(!sandy(px(&plain, wall)), "{:?}", px(&plain, wall)); + // Nearly from above, the hole's middle at the base: the floor, darker than the wall's top. + let (holed, at) = frame(&mut m, "holed", 10.0); + let (plain, _) = frame(&mut m, "plain", 10.0); + let floor = px(&holed, at(0.0, 0.0, -500.0)); + assert!(sandy(floor) && floor.red() < 140, "{floor:?}"); + assert!(!sandy(px(&plain, at(0.0, 0.0, -500.0)))); + // The ground round the hole is drawn as over a whole square. + assert_eq!(px(&holed, at(600.0, 600.0, 500.0)), px(&plain, at(600.0, 600.0, 500.0))); + } + #[test] fn a_round_block_cuts_the_ground_to_its_circle_and_stands_its_wall_round_it() { // #2318: the circle in a 2 km box over flat ground 500 m high, seen from the south. Below diff --git a/crates/render/src/terrain/outline.rs b/crates/render/src/terrain/outline.rs index cde90153ae..b57673ba56 100644 --- a/crates/render/src/terrain/outline.rs +++ b/crates/render/src/terrain/outline.rs @@ -18,8 +18,9 @@ const SPACING: f64 = 1.0 / 2000.0; /// The most entries the sides' row index holds (each side once in every row it spans): 16 MB. const ROW_BUDGET: usize = 4_000_000; -/// One side of an outline: its ends (anticlockwise round its ring), its ring, and how far along -/// the ring it begins (Web Mercator metres). +/// One side of an outline: its ends (its polygon's ground on their left: anticlockwise round an +/// outer ring, clockwise round a hole), its ring, and how far along the ring it begins (Web +/// Mercator metres). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Side { pub a: Coord, @@ -28,14 +29,17 @@ pub(crate) struct Side { pub along: f64, } -/// The outer rings of a block's polygons (Web Mercator, each anticlockwise), their sides in -/// order, and the sides by row of the outline's box, for [`Outline::contains`] and -/// [`Outline::near`]. Holes are left out: the ground inside them is kept. +/// The rings of a block's polygons (Web Mercator; outer rings anticlockwise, holes clockwise, +/// each polygon's rings in a row), their sides in order, and the sides by row of the outline's +/// box, for [`Outline::contains`] and [`Outline::near`]. A hole is a well: its ground isn't +/// drawn, its walls face into it, and its floor is drawn at the base. #[derive(Debug, PartialEq)] pub struct Outline { sides: Vec, /// Each ring's first side, its count of sides and its length round. rings: Vec<(usize, usize, f64)>, + /// Each ring's polygon (a number its outer ring and its holes share) and whether it is a hole. + kinds: Vec<(u32, bool)>, extent: [f64; 4], rows: Vec>, /// How near two corners in a row were let lie (Web Mercator metres; [`SPACING`] of the longer @@ -44,7 +48,7 @@ pub struct Outline { spacing: f64, coarsened: bool, dropped: usize, - /// How many holes (inner rings with an area) the picked polygons have: not cut, so said. + /// How many holes the outline keeps, each cut as a well. holes: usize, /// How many rings with an area had none left once thinned (narrower than the spacing). narrow: usize, @@ -75,7 +79,7 @@ impl Outline { let keep = l.query_rows(&l.dataset); let pick = rustgis_data::rows::Query::compile(filter, &l.dataset).ok()?; let env = rustgis_data::query::Env::default(); - let (mut rings, mut holes) = (Vec::new(), 0); + let mut polygons: Vec>> = Vec::new(); // In longitude/latitude whatever system the layer holds its coordinates in, as the walls // read it (`block::units`); a polygon that can't be given there isn't drawn by the map either. let to = l.dataset.shown_conversion().ok(); @@ -87,10 +91,9 @@ impl Outline { continue; }; let Geometry::Polygon(parts) = &*lonlat else { continue }; - rings.extend(parts.iter().filter_map(|p| p.first()).map(|r| r.iter().map(|c| lonlat_to_merc(*c)).collect())); - holes += parts.iter().flat_map(|p| p.iter().skip(1)).filter(|h| area2(h).abs() > 0.0).count(); + polygons.extend(parts.iter().map(|p| p.iter().map(|r| r.iter().map(|c| lonlat_to_merc(*c)).collect()).collect())); } - let o = Outline::from_rings(rings).map(|o| Arc::new(Outline { holes, ..o })); + let o = Outline::from_polygons(polygons).map(Arc::new); if let Ok(mut last) = LAST.lock() { last.retain(|k| k.0.strong_count() > 0 && !same(k)); if last.len() >= KEPT { @@ -101,16 +104,32 @@ impl Outline { o } - /// The outline of `rings` (Web Mercator, either way round, closed or not), corners nearer than - /// [`SPACING`] of its longer side to the last one kept left out (more spaced still if it - /// would have over [`MAX_SIDES`] sides). `None` when no ring has an area. + /// The outline of `rings`, each a polygon without holes ([`Outline::from_polygons`]). + #[cfg(test)] pub(crate) fn from_rings(rings: Vec>) -> Option { - // Only rings with an area count: one without gives no ground and sets no spacing. - let rings: Vec> = rings - .into_iter() - .map(|r| r.into_iter().filter(|c| c.x.is_finite() && c.y.is_finite()).collect::>()) - .filter(|r| r.len() >= 3 && area2(r).abs() > 0.0 && area2(r).is_finite()) - .collect(); + Outline::from_polygons(rings.into_iter().map(|r| vec![r]).collect()) + } + + /// The outline of `polygons` (each its outer ring, then its holes; Web Mercator, either way + /// round, closed or not), corners nearer than [`SPACING`] of its longer side to the last one + /// kept left out (more spaced still if it would have over [`MAX_SIDES`] sides). `None` when + /// no outer ring has an area. + pub(crate) fn from_polygons(polygons: Vec>>) -> Option { + // Only rings with an area count: one without gives no ground and sets no spacing. Each + // keeps its polygon's number and whether it is a hole; a polygon whose outer ring has no + // area gives no holes either. + let (mut rings, mut kinds): (Vec>, Vec<(u32, bool)>) = (Vec::new(), Vec::new()); + for (p, polygon) in polygons.into_iter().enumerate() { + for (i, r) in polygon.into_iter().enumerate() { + let r: Vec = r.into_iter().filter(|c| c.x.is_finite() && c.y.is_finite()).collect(); + if r.len() >= 3 && area2(&r).abs() > 0.0 && area2(&r).is_finite() { + rings.push(r); + kinds.push((p as u32, i > 0)); + } else if i == 0 { + break; + } + } + } let (mut x0, mut y0, mut x1, mut y1) = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); for c in rings.iter().flatten() { (x0, y0, x1, y1) = (x0.min(c.x), y0.min(c.y), x1.max(c.x), y1.max(c.y)); @@ -137,8 +156,16 @@ impl Outline { } gap *= 2.0; }; + // A hole whose outer ring was left out goes with it: alone it would cut ground no ring + // holds. Counted with the ring: narrow here, past the sides below. + let orphans = |t: &mut Vec<(usize, Vec)>| { + let outers: Vec = t.iter().filter(|(i, _)| !kinds[*i].1).map(|(i, _)| kinds[*i].0).collect(); + t.retain(|(i, _)| !kinds[*i].1 || outers.contains(&kinds[*i].0)); + }; + orphans(&mut thinned); let narrow = rings.len() - thinned.len(); - // Still too many (thousands of small rings): the largest that fit are kept. + // Still too many (thousands of small rings): the largest that fit are kept, put back in + // order so each polygon's rings stay in a row. let all = thinned.len(); if count(&thinned) > MAX_SIDES { thinned.sort_by(|a, b| area2(&b.1).total_cmp(&area2(&a.1))); @@ -148,6 +175,8 @@ impl Outline { used += if fits { r.1.len() } else { 0 }; fits }); + thinned.sort_by_key(|r| r.0); + orphans(&mut thinned); } let dropped = all - thinned.len(); // The widest gap a ring was thinned at: past an eighth of the largest ring, `gap` only @@ -159,7 +188,12 @@ impl Outline { (x0, y0, x1, y1) = (x0.min(c.x), y0.min(c.y), x1.max(c.x), y1.max(c.y)); } let (mut sides, mut starts) = (Vec::new(), Vec::new()); - for (i, (_, r)) in thinned.iter().enumerate() { + let kept: Vec<(u32, bool)> = thinned.iter().map(|(i, _)| kinds[*i]).collect(); + for (i, (from, r)) in thinned.iter_mut().enumerate() { + // [`thin`] turns every ring anticlockwise: a hole is turned back, its ground on the left. + if kinds[*from].1 { + r.reverse(); + } let first = sides.len(); let mut along = 0.0; for (j, &a) in r.iter().enumerate() { @@ -184,12 +218,13 @@ impl Outline { Some(Outline { sides, rings: starts, + holes: kept.iter().filter(|k| k.1).count(), + kinds: kept, extent: [x0, y0, x1, y1], rows, spacing, coarsened: spacing > first, dropped, - holes: 0, narrow, }) } @@ -211,11 +246,21 @@ impl Outline { self.dropped } - /// How many holes the picked polygons have: the ground inside them is kept, not cut. + /// How many holes the outline keeps, each cut as a well with its own walls. pub fn holes(&self) -> usize { self.holes } + /// Ring `r`'s polygon and whether it is a hole. + pub(crate) fn kind(&self, r: u32) -> (u32, bool) { + self.kinds.get(r as usize).copied().unwrap_or((r, false)) + } + + /// Each hole's sides (their numbers), in a row round it. + pub(crate) fn hole_sides(&self) -> impl Iterator> + '_ { + self.rings.iter().zip(&self.kinds).filter(|(_, k)| k.1).map(|(r, _)| r.0..r.0 + r.1) + } + /// How many of the polygons' rings were left out as narrower than the spacing: thinned, no /// area was left. pub fn narrow(&self) -> usize { @@ -251,33 +296,35 @@ impl Outline { row(y0)..=row(y1) } - /// Whether `m` lies inside the outline: inside any of its rings. + /// Whether `m` lies inside the outline: inside one of its polygons and none of its holes. pub fn contains(&self, m: Coord) -> bool { self.inside_ring(m, |_| true) } - /// Whether `m` lies inside one of the rings `counted` keeps. + /// Whether `m` lies inside one of the polygons, of their rings `counted` keeps. pub(crate) fn inside_ring(&self, m: Coord, counted: impl Fn(u32) -> bool) -> bool { let [x0, y0, x1, y1] = self.extent; if !(m.x >= x0 && m.x <= x1 && m.y >= y0 && m.y <= y1) { return false; } - // Each ring is anticlockwise: a ring round `m` winds it once. A row lists its sides in - // order, and a ring's sides follow one another, so each ring's winding is summed in turn. - let (mut ring_of, mut winding) = (u32::MAX, 0); + // An outer ring runs anticlockwise and a hole clockwise: a polygon round `m` winds it once, + // and once back when `m` is in one of its holes. A row lists its sides in order, and a + // polygon's sides follow one another, so each polygon's winding is summed in turn. + let (mut polygon_of, mut winding) = (u32::MAX, 0); for &k in self.rows.get(*self.rows_of(m.y, m.y).start()).into_iter().flatten() { let Some(Side { a, z, ring, .. }) = self.sides.get(k as usize).copied() else { continue }; - if ring != ring_of { - if winding != 0 { + let polygon = self.kind(ring).0; + if polygon != polygon_of { + if winding > 0 { return true; } - (ring_of, winding) = (ring, 0); + (polygon_of, winding) = (polygon, 0); } if counted(ring) && (a.y > m.y) != (z.y > m.y) && m.x < a.x + (m.y - a.y) / (z.y - a.y) * (z.x - a.x) { winding += if z.y > a.y { 1 } else { -1 }; } } - winding != 0 + winding > 0 } /// The sides whose box meets the box from `lo` to `hi`, each once, into `out` (emptied first). diff --git a/docs/user-guide/maps.md b/docs/user-guide/maps.md index 36e46a8ea8..81432fd245 100644 --- a/docs/user-guide/maps.md +++ b/docs/user-guide/maps.md @@ -150,12 +150,13 @@ takes it back to the box. A block kept from before stays round when another key `"shape": {"layer": "Bacias", "where": "nome = 'Rio Doce'"}` cuts the block to a study area: the polygons of a polygon layer that the expression picks (written as a definition query, among the rows the layer's own definition query keeps; all of them without `"where"`). Only the ground -inside their outer rings is drawn and sets the base, the block's box is the one round them (so +inside them is drawn and sets the base, the block's box is the one round them (so no `"extent"`), and it works over elevation tiles too. The walls stand along the outline where it faces you, a concave outline's hidden where nearer ground or walls stand in front of them, with everything a box's walls have; a wall's corner is outlined where the outline turns by more -than 45°. A `"where"` that picks no polygon is refused. Holes are not cut: the ground inside -them is drawn, and a notice says how many. Several polygons each stand as their own block on the +than 45°. A `"where"` that picks no polygon is refused. Each hole is a well: its ground isn't +drawn, its walls stand along it where they face you (on its far side), and its floor is drawn at +the base, in the walls' colour in shade. Several polygons each stand as their own block on the same base (dissolve touching ones first for one outline). The outline follows the polygons to about a third of the finest mesh cell (a ring narrower than that is left out, and said), and is read again when the layer is edited. A box kept from before is dropped when the block is cut to polygons. From d30a6c88bf79e2913f690008d3d094c15fcc78db Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Sun, 22 Nov 2026 16:57:33 -0300 Subject: [PATCH 2/4] fix(render): leave out holes outside their polygon; floor depth by side (#2318) Review round 1 of #2714: - A hole lying outside its own outer ring closed on its own as ground with walls: from_polygons now leaves it out, counts it (stray), and map.terrain reports and says it. - The floor pass looks up each hole side's stretches with of_side instead of scanning every stretch per hole. - The orphan-hole check keeps outer rings in a HashSet. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/view.rs | 28 ++++++++++++----------- crates/engine/src/tests.rs | 9 ++++++++ crates/render/src/block.rs | 14 ++++++++++-- crates/render/src/terrain/outline.rs | 33 ++++++++++++++++++++++++++-- 4 files changed, 67 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/view.rs b/crates/engine/src/cmd/view.rs index 15deb75f66..2de91f2f22 100644 --- a/crates/engine/src/cmd/view.rs +++ b/crates/engine/src/cmd/view.rs @@ -458,24 +458,26 @@ fn block_polygons(s: &Session, o: &serde_json::Map) -> Result Option { let (spacing, coarsened) = o.spacing(); // Rings narrower than the spacing, with no area left once thinned (#2318). let narrow = (o.narrow() > 0).then(|| format!("{} ring(s) of '{layer}' narrower than {spacing:.0} m were left out of the block", o.narrow())); - let left = match o.dropped() { - 0 if !coarsened => return narrow, - 0 => String::new(), - n => format!(", and its {n} smallest ring(s) were left out"), + let stray = (o.stray() > 0) + .then(|| format!("{} hole(s) of '{layer}' lying outside their own polygon's outer ring were left out (not cut)", o.stray())); + let merged = match o.dropped() { + 0 if !coarsened => None, + n => { + let left = if n == 0 { String::new() } else { format!(", and its {n} smallest ring(s) were left out") }; + Some(format!( + "the outline of '{layer}' the block is cut to has too many corners: corners up to {spacing:.0} m apart were merged (less in smaller rings){left}, to stay under 65535 sides" + )) + } }; - let said = format!( - "the outline of '{layer}' the block is cut to has too many corners: corners up to {spacing:.0} m apart were merged (less in smaller rings){left}, to stay under 65535 sides" - ); - Some(match narrow { - Some(n) => format!("{said}; {n}"), - None => said, - }) + let said: Vec = [merged, narrow, stray].into_iter().flatten().collect(); + (!said.is_empty()).then(|| said.join("; ")) } /// The name of the polygon layer `name` for `what` (water, a block's walls), checked: a polygon @@ -746,7 +748,7 @@ fn terrain(s: &mut Session, p: &Value) -> CmdResult { // A polygon block's outline as drawn: its sides and how near its corners were let lie. if let Some((_, o)) = &outline { let (spacing, coarsened) = o.spacing(); - out["block"]["outline"] = json!({"sides": o.side_count(), "spacing": spacing, "coarsened": coarsened, "dropped": o.dropped(), "holes": o.holes(), "narrow": o.narrow()}); + out["block"]["outline"] = json!({"sides": o.side_count(), "spacing": spacing, "coarsened": coarsened, "dropped": o.dropped(), "holes": o.holes(), "stray": o.stray(), "narrow": o.narrow()}); } if matches!(t.source, TerrainSource::Layer(_)) && t.block.is_some() && dem_box.is_none() { out["block"]["pendingDem"] = json!(true); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d792a688d8..f65bf4d874 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -15586,6 +15586,10 @@ fn terrain_block_cut_to_polygons() { [[10.005, 45.005], [10.015, 45.005], [10.015, 45.015], [10.005, 45.015], [10.005, 45.005]], [[10.008, 45.008], [10.012, 45.008], [10.012, 45.012], [10.008, 45.012], [10.008, 45.008]], ]}}, + {"type": "Feature", "properties": {"nome": "e"}, "geometry": {"type": "Polygon", "coordinates": [ + [[10.005, 45.005], [10.015, 45.005], [10.015, 45.015], [10.005, 45.015], [10.005, 45.005]], + [[10.018, 45.008], [10.019, 45.008], [10.019, 45.009], [10.018, 45.009], [10.018, 45.008]], + ]}}, ]}); let data = base64::engine::general_purpose::STANDARD.encode(areas.to_string().as_bytes()); s.run("layer.addDataBytes", &json!({"fileName": "areas.geojson", "data": data})).unwrap(); @@ -15633,6 +15637,11 @@ fn terrain_block_cut_to_polygons() { let mut opened = Session::new(Project::default()); crate::cmd::project::reset_to(&mut opened, holed.project.clone()); assert!(!holed.notices.iter().chain(&opened.notices).any(|n| n.text.contains("hole")), "{:?}", opened.notices); + // A hole lying outside its own outer ring cuts nothing: left out, and said. + let v = holed.run("map.terrain", &json!({"layer": dem, "block": {"shape": {"layer": "bacias", "where": "nome = 'e'"}}})).unwrap(); + assert_eq!((&v["block"]["outline"]["holes"], &v["block"]["outline"]["stray"]), (&json!(0), &json!(1))); + let stray = "1 hole(s) of 'bacias' lying outside their own polygon's outer ring were left out"; + assert!(holed.notices.iter().any(|n| n.text.contains(stray)), "{:?}", holed.notices); // A saved block cut to a polygon off the DEM is kept as the project opens, and said. let mut far = s.project.clone(); if let Some(b) = far.maps[0].view.terrain.as_mut().and_then(|t| t.block.as_mut()) { diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 74d8209231..b885143cc5 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -369,7 +369,8 @@ fn clip_outline(m: [Coord; 3], o: &Outline) -> Vec> { // A hole wholly inside the triangle is cut from its polygon's part round it, joined to it // by a seam there and back from the part's nearest corner: the hole runs the other way, so // filled by winding it stays empty, and the seam's two edges, on no side, give no wall. A - // hole in no part of its polygon (one lying outside its own outer ring) cuts nothing. + // hole in no part of its polygon cuts nothing (one outside its own outer ring was already + // left out, [`Outline::from_polygons`]). for (ring, hole) in wells { let polygon = o.kind(ring).0; let Some(h) = hole.first().copied() else { continue }; @@ -1321,7 +1322,9 @@ pub(crate) fn draw_walls( // cover it and it shows only down the well. A hole with no stretch under the ground drawn // isn't in the picture: no floor. for sides in b.outline.iter().flat_map(|o| o.hole_sides()) { - let Some(depth) = edges.iter().filter(|e| sides.contains(&usize::from(e.side))).map(|e| e.depth).min_by(f64::total_cmp) else { + // Each side's stretches by binary search ([`of_side`]), not a scan of all of them. + let depth = sides.clone().filter_map(|s| u16::try_from(s).ok()).flat_map(|s| of_side(s).iter().map(|e| e.depth)); + let Some(depth) = depth.min_by(f64::total_cmp) else { continue; }; let mut floor = PathBuilder::new(); @@ -1732,6 +1735,13 @@ mod tests { let flat = ring(&[(20.0, 0.0), (30.0, 0.0), (25.0, 0.0)]); let alone = Outline::from_polygons(vec![vec![square.clone()], vec![flat, hole.clone()]]).expect("an outline"); assert_eq!((alone.side_count(), alone.holes(), alone.dropped()), (4, 0, 0)); + // One lying outside its own outer ring cuts nothing and makes no ground: left out, counted. + let stray = ring(&[(20.0, 20.0), (22.0, 20.0), (22.0, 22.0), (20.0, 22.0)]); + let o = Outline::from_polygons(vec![vec![square.clone(), stray]]).expect("an outline"); + assert_eq!((o.side_count(), o.holes(), o.stray()), (4, 0, 1)); + let [x0, y0, x1, y1] = o.extent(); + let b = Block { x0, y0, x1, y1, outline: Some(Arc::new(o)), ..unit_block() }; + assert!(pieces([Coord::new(19.0, 20.5), Coord::new(21.0, 20.5), Coord::new(19.0, 21.5)], &b).is_empty()); let o = Outline::from_polygons(vec![vec![square, hole]]).expect("an outline"); assert_eq!((o.side_count(), o.holes()), (8, 1)); assert!(o.contains(Coord::new(2.0, 2.0)) && !o.contains(Coord::new(5.0, 5.0))); diff --git a/crates/render/src/terrain/outline.rs b/crates/render/src/terrain/outline.rs index b57673ba56..81d501f34c 100644 --- a/crates/render/src/terrain/outline.rs +++ b/crates/render/src/terrain/outline.rs @@ -50,6 +50,8 @@ pub struct Outline { dropped: usize, /// How many holes the outline keeps, each cut as a well. holes: usize, + /// How many holes lay outside their own polygon's outer ring: left out, as they cut nothing. + stray: usize, /// How many rings with an area had none left once thinned (narrower than the spacing). narrow: usize, } @@ -117,12 +119,22 @@ impl Outline { pub(crate) fn from_polygons(polygons: Vec>>) -> Option { // Only rings with an area count: one without gives no ground and sets no spacing. Each // keeps its polygon's number and whether it is a hole; a polygon whose outer ring has no - // area gives no holes either. + // area gives no holes either. A hole outside its outer ring (an invalid polygon) would + // close on its own as ground ([`crate::block`]'s cut follows a polygon's rings): left out + // and counted. let (mut rings, mut kinds): (Vec>, Vec<(u32, bool)>) = (Vec::new(), Vec::new()); + let mut stray = 0; for (p, polygon) in polygons.into_iter().enumerate() { + let mut outer = 0; for (i, r) in polygon.into_iter().enumerate() { let r: Vec = r.into_iter().filter(|c| c.x.is_finite() && c.y.is_finite()).collect(); if r.len() >= 3 && area2(&r).abs() > 0.0 && area2(&r).is_finite() { + if i == 0 { + outer = rings.len(); + } else if !r.first().is_some_and(|c| within(&rings[outer], *c)) { + stray += 1; + continue; + } rings.push(r); kinds.push((p as u32, i > 0)); } else if i == 0 { @@ -159,7 +171,7 @@ impl Outline { // A hole whose outer ring was left out goes with it: alone it would cut ground no ring // holds. Counted with the ring: narrow here, past the sides below. let orphans = |t: &mut Vec<(usize, Vec)>| { - let outers: Vec = t.iter().filter(|(i, _)| !kinds[*i].1).map(|(i, _)| kinds[*i].0).collect(); + let outers: std::collections::HashSet = t.iter().filter(|(i, _)| !kinds[*i].1).map(|(i, _)| kinds[*i].0).collect(); t.retain(|(i, _)| !kinds[*i].1 || outers.contains(&kinds[*i].0)); }; orphans(&mut thinned); @@ -219,6 +231,7 @@ impl Outline { sides, rings: starts, holes: kept.iter().filter(|k| k.1).count(), + stray, kinds: kept, extent: [x0, y0, x1, y1], rows, @@ -251,6 +264,11 @@ impl Outline { self.holes } + /// How many holes lay outside their own polygon's outer ring (an invalid polygon): left out. + pub fn stray(&self) -> usize { + self.stray + } + /// Ring `r`'s polygon and whether it is a hole. pub(crate) fn kind(&self, r: u32) -> (u32, bool) { self.kinds.get(r as usize).copied().unwrap_or((r, false)) @@ -369,6 +387,17 @@ fn thin(ring: &[Coord], gap: f64) -> Option> { Some(out) } +/// Whether `p` lies inside `ring`, even-odd. +fn within(ring: &[Coord], p: Coord) -> bool { + let mut inside = false; + for (a, z) in ring.iter().zip(ring.iter().cycle().skip(1)) { + if (a.y > p.y) != (z.y > p.y) && p.x < a.x + (p.y - a.y) / (z.y - a.y) * (z.x - a.x) { + inside = !inside; + } + } + inside +} + /// Twice the signed area of `ring` (positive anticlockwise). fn area2(ring: &[Coord]) -> f64 { ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| a.x * b.y - b.x * a.y).sum() From e8f43125aedda09b0d1d9e3ca59a71ce913ea772 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 27 Nov 2026 13:30:56 -0300 Subject: [PATCH 3/4] test(render): a hole's seam across a notch fills no ground outside the polygon (#2318) A U whose east arm has a spike into the bay, with a hole in the west arm: the part's nearest corner to the hole is the spike's tip, so the seam crosses the bay. Filled by winding, as the frame fills a part, the seam's two edges cancel: the bay and the hole stay bare, and the walls are the outline's 15 sides, none on the seam. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/block.rs | 84 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index b885143cc5..2cd9e2f034 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -1771,6 +1771,90 @@ mod tests { assert!(b.beyond(4, Coord::new(5.0, 5.0)) > 0.0 && b.beyond(4, Coord::new(5.0, 7.0)) < 0.0); } + #[test] + fn a_polygon_blocks_hole_seam_across_a_notch_fills_no_ground_outside_the_polygon() { + // #2318: a U, its bay x 1 to 2 from y = 1 up, the east arm's inner side with a spike into + // the bay to (1.2, 5), and a hole in the west arm. Every corner of the hole is nearer the + // spike's tip than any corner of the west arm, so the seam from the part's nearest corner + // crosses the bay. Filled as the frame fills it (by winding), the seam's two edges cancel: + // the bay stays bare, the hole too, and the walls are the outline's sides only. + let ring = |c: &[(f64, f64)]| c.iter().map(|&(x, y)| Coord::new(x, y)).collect::>(); + let u = ring(&[ + (0.0, 0.0), + (3.0, 0.0), + (3.0, 10.0), + (2.0, 10.0), + (2.0, 5.2), + (1.2, 5.0), + (2.0, 4.8), + (2.0, 1.0), + (1.0, 1.0), + (1.0, 10.0), + (0.0, 10.0), + ]); + let hole = ring(&[(0.3, 4.8), (0.9, 4.8), (0.9, 5.2), (0.3, 5.2)]); + let o = Outline::from_polygons(vec![vec![u, hole.clone()]]).expect("an outline"); + assert_eq!((o.side_count(), o.holes()), (15, 1)); + let [x0, y0, x1, y1] = o.extent(); + let b = Block { x0, y0, x1, y1, outline: Some(Arc::new(o)), ..unit_block() }; + let o = b.outline.as_deref().expect("an outline"); + let parts = pieces([Coord::new(-5.0, -5.0), Coord::new(30.0, -5.0), Coord::new(-5.0, 30.0)], &b); + assert_eq!(parts.len(), 1); + // The U's 30 less the bay's 9, plus the spike's 0.16, less the hole's 0.24. + assert!((area(&parts) - 20.92).abs() < 1e-9, "{}", area(&parts)); + // The seam does run from the spike's tip, across the bay, to a corner of the hole. + let p = &parts[0]; + let tip = Coord::new(1.2, 5.0); + assert!(p.iter().zip(p.iter().cycle().skip(1)).any(|(a, z)| a.1 == tip && hole.contains(&z.1)), "{p:?}"); + // Drawn as the frame draws a part, 40 px a unit: every pixel more than 1.5 px from the + // outline is filled where the outline holds it and bare elsewhere (the bay, the hole). + let (k, m) = (40.0, 8.0); + let mut pm = Pixmap::new((3.0 * k + 2.0 * m) as u32, (10.0 * k + 2.0 * m) as u32).expect("a pixmap"); + let mut pb = PathBuilder::new(); + for (i, c) in p.iter().enumerate() { + let (x, y) = ((c.1.x * k + m) as f32, (c.1.y * k + m) as f32); + if i == 0 { pb.move_to(x, y) } else { pb.line_to(x, y) } + } + pb.close(); + let path = pb.finish().expect("a path"); + let mut paint = Paint { anti_alias: true, ..Paint::default() }; + paint.set_color_rgba8(0, 0, 0, 255); + pm.fill_path(&path, &paint, FillRule::Winding, Transform::identity(), None); + let off = |q: Coord| { + o.sides() + .iter() + .map(|s| { + let (dx, dy) = (s.z.x - s.a.x, s.z.y - s.a.y); + let u = (((q.x - s.a.x) * dx + (q.y - s.a.y) * dy) / (dx * dx + dy * dy)).clamp(0.0, 1.0); + (q.x - s.a.x - u * dx).hypot(q.y - s.a.y - u * dy) + }) + .fold(f64::INFINITY, f64::min) + }; + let (mut bay, mut wrong) = (0, Vec::new()); + for j in 0..pm.height() { + for i in 0..pm.width() { + let q = Coord::new((f64::from(i) + 0.5 - m) / k, (f64::from(j) + 0.5 - m) / k); + if off(q) * k <= 1.5 { + continue; + } + let alpha = pm.pixel(i, j).map_or(0, |c| c.alpha()); + let ground = o.contains(q); + bay += usize::from(!ground && q.x > 1.0 && q.x < 2.0 && q.y > 1.0 && q.y < 10.0); + if alpha != if ground { 255 } else { 0 } { + wrong.push((q.x, q.y, alpha)); + } + } + } + assert!(bay > 1000 && wrong.is_empty(), "{bay} {:?}", &wrong[..wrong.len().min(8)]); + // Its walls are the outline's 15 sides, none along the seam (it runs along none). + let mut out = Vec::new(); + edges(&b, p, &p.iter().map(|c| (c.1.x, c.1.y)).collect::>(), 1.0, &mut out); + let mut sides: Vec = out.iter().map(|e| e.side).collect(); + sides.sort_unstable(); + sides.dedup(); + assert_eq!(sides, (0..15).collect::>()); + } + #[test] fn a_polygon_block_cuts_a_triangle_across_its_inner_corner_to_the_part_inside() { // #2318: an L, the square 10 a side without its north-east quarter (given clockwise: it is From d0fba37a685ddc7f3008d4ee48d26e5894b56095 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Fri, 27 Nov 2026 14:03:27 -0300 Subject: [PATCH 4/4] fix(render): a hole's floor is cut at the eye, and shows round the whole view (#2318) The floor dropped the hole's corners that project nowhere (at or behind the eye) and joined the rest across the hole: a hole reaching past the eye of a tilted view lost its floor. Its ring is now cut at the near limit (`Camera::near_v` at the base's rise) before it is projected, keeping the crossing points. A hole with no stretch of wall under the drawn ground had no floor, also when the view lies wholly inside it. It now gets one when the view's centre is in the hole, fogged at the centre's depth. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/block.rs | 43 ++++++++++++++++++++--- crates/render/src/lib.rs | 71 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 110 insertions(+), 4 deletions(-) diff --git a/crates/render/src/block.rs b/crates/render/src/block.rs index 2cd9e2f034..1284b0c3d5 100644 --- a/crates/render/src/block.rs +++ b/crates/render/src/block.rs @@ -1319,16 +1319,51 @@ pub(crate) fn draw_walls( let mut dirty: Option = None; // A polygon block's wells: each hole's floor at the base, in the walls' colour as shaded at // their foot facing away from the light, drawn first, so the ground and walls in front of it - // cover it and it shows only down the well. A hole with no stretch under the ground drawn - // isn't in the picture: no floor. + // cover it and it shows only down the well, fogged at its nearest stretch. A hole with no + // stretch under the ground drawn is in the picture only when the view lies wholly inside it, + // its centre in the hole: fogged there (depth 1, [`rustgis_map::Camera::depth_scale`]). for sides in b.outline.iter().flat_map(|o| o.hole_sides()) { // Each side's stretches by binary search ([`of_side`]), not a scan of all of them. let depth = sides.clone().filter_map(|s| u16::try_from(s).ok()).flat_map(|s| of_side(s).iter().map(|e| e.depth)); - let Some(depth) = depth.min_by(f64::total_cmp) else { + let around = || { + let c = cam.center; + sides.clone().map(|i| b.side(i)).fold(false, |inside, (_, a, z)| { + inside ^ ((a.y > c.y) != (z.y > c.y) && c.x < a.x + (c.y - a.y) / (z.y - a.y) * (z.x - a.x)) + }) + }; + let Some(depth) = depth.min_by(f64::total_cmp).or_else(|| around().then_some(1.0)) else { + continue; + }; + // Its ring in ground px raised to the base, cut to what stands in front of the eye + // ([`rustgis_map::Camera::near_v`]): a corner behind it projects nowhere, and leaving it + // out would join its neighbours across the floor. Where an edge crosses the limit, its + // place and rise are taken along it. A corner that still projects nowhere: no floor. + let raised = |m: Coord| { + let (u, v) = cam.ground_px(m); + (u, v, (b.base / ground.per_unit(m) / cam.res.max(1e-9)).clamp(-1e7, 1e7)) + }; + let ring: Vec<(f64, f64, f64)> = sides.map(|i| raised(b.side(i).1)).collect(); + let ahead = |p: (f64, f64, f64)| cam.near_v(p.2, h) - p.1; + let mut cut = Vec::with_capacity(ring.len() + 2); + for (i, &a) in ring.iter().enumerate() { + let q = ring[(i + 1) % ring.len()]; + let (da, dq) = (ahead(a), ahead(q)); + if da >= 0.0 { + cut.push(a); + } + if (da >= 0.0) != (dq >= 0.0) { + let t = da / (da - dq); + cut.push((a.0 + (q.0 - a.0) * t, a.1 + (q.1 - a.1) * t, a.2 + (q.2 - a.2) * t)); + } + } + let project = |p: &(f64, f64, f64)| { + cam.project_raised(p.0, p.1, p.2, w, h).map(|(x, y)| (x * k, y * k)).filter(|p| p.0.is_finite() && p.1.is_finite()) + }; + let Some(corners) = cut.iter().map(project).collect::>>().filter(|c| c.len() >= 3) else { continue; }; let mut floor = PathBuilder::new(); - for (i, p) in sides.filter_map(|i| foot(b.side(i).1)).enumerate() { + for (i, p) in corners.into_iter().enumerate() { if i == 0 { floor.move_to(pt(p).0, pt(p).1) } else { floor.line_to(pt(p).0, pt(p).1) } } floor.close(); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index df53479346..230515e7f2 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -11539,6 +11539,77 @@ mod tests { assert_eq!(px(&holed, at(600.0, 600.0, 500.0)), px(&plain, at(600.0, 600.0, 500.0))); } + #[test] + fn a_polygon_blocks_hole_shows_its_floor_reaching_behind_the_eye_or_round_the_whole_view() { + // #2318: flat ground 500 m high cut to a polygon whose hole, 2 km wide, runs from 1 km + // north of the view's centre to 8 km south, past the eye of a view tilted 60°. The hole's + // southern corners project nowhere; down the well, the centre's floor still shows at the + // base in the walls' sandy brown. + use rustgis_data::raster::{ColorHint, Crs, GeoTransform, Raster}; + let gt = GeoTransform { origin_x: -10_000.0, origin_y: 10_000.0, pixel_width: 20.0, pixel_height: -20.0 }; + let dem = + Raster::new("dem", 1000, 1000, vec![vec![500.0; 1000 * 1000]], gt, Crs::WebMercator, None, ColorHint::Gray, "Float32").unwrap(); + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + m.add_raster("dem", rustgis_map::RasterLayer::from_path(dem, "dem.tif")); + let deg = |x: f64, y: f64| rustgis_geom::merc_to_lonlat(Coord::new(x, y)); + let rect = |x: f64, s: f64, n: f64| [(-x, s), (x, s), (x, n), (-x, n), (-x, s)].iter().map(|&(x, y)| deg(x, y)).collect::>(); + let mut d = Dataset::new("area", GeometryType::Polygon, vec![Field::new("name", FieldType::Text)]); + d.push( + Some(Geometry::Polygon(vec![vec![rect(3000.0, -9000.0, 3000.0), rect(1000.0, -8000.0, 1000.0)]])), + vec![Value::Text("holed".into())], + ); + d.push( + Some(Geometry::Polygon(vec![vec![rect(9500.0, -9500.0, 9500.0), rect(8000.0, -8000.0, 8000.0)]])), + vec![Value::Text("wide".into())], + ); + m.add_dataset(d); + let camera = Camera { center: Coord::new(0.0, 0.0), res: 10.0, bearing: 0.0, pitch: 60.0 }; + let view = View { width: 400.0, height: 300.0, pixels_per_point: 1.0, camera, sky: false }; + let shape = rustgis_map::view::BlockShape::Polygon { layer: "area".into(), filter: Some("name = 'holed'".into()) }; + m.view.terrain = Some(rustgis_map::view::Terrain { + source: rustgis_map::view::TerrainSource::Layer("dem".into()), + exaggeration: 1.0, + block: Some(rustgis_map::view::TerrainBlock { + extent: None, + depth: Some(1000.0), + walls: rustgis_map::view::BLOCK_WALLS, + walls_layer: None, + water: None, + shape, + }), + water: None, + }); + let g = terrain::Ground::of(&m, &camera).expect("terrain"); + let per_unit = g.per_unit(Coord::new(0.0, 0.0)); + let base = |x: f64, y: f64| { + let (u, v) = camera.ground_px(Coord::new(x, y)); + camera.project_raised(u, v, -500.0 / per_unit / camera.res, view.width, view.height) + }; + // The hole's southern corners are behind the eye, its northern ones in front of it. + assert!(base(-1000.0, -8000.0).is_none() && base(1000.0, -8000.0).is_none()); + assert!(base(-1000.0, 1000.0).is_some() && base(1000.0, 1000.0).is_some()); + let floor_at = |m: &mut Map, view: &View| { + let r = render(m, view).expect("a frame"); + let (u, v) = view.camera.ground_px(Coord::new(0.0, 0.0)); + let p = view.camera.project_raised(u, v, -500.0 / per_unit / view.camera.res, view.width, view.height).expect("in view"); + r.pixmap.pixel(p.0 as u32, p.1 as u32).expect("in the frame").demultiply() + }; + let sandy = |c: tiny_skia::ColorU8| c.red() > c.green() && c.green() > c.blue() + 8 && c.red() < 140; + let floor = floor_at(&mut m, &view); + assert!(sandy(floor), "{floor:?}"); + // Seen nearly from above, wholly inside a hole 16 km across with none of its sides in + // view: the floor still shows. + if let Some(rustgis_map::view::BlockShape::Polygon { filter, .. }) = + m.view.terrain.as_mut().and_then(|t| t.block.as_mut()).map(|b| &mut b.shape) + { + *filter = Some("name = 'wide'".into()); + } + let camera = Camera { pitch: 10.0, ..camera }; + let floor = floor_at(&mut m, &View { camera, ..view }); + assert!(sandy(floor), "{floor:?}"); + } + #[test] fn a_round_block_cuts_the_ground_to_its_circle_and_stands_its_wall_round_it() { // #2318: the circle in a 2 km box over flat ground 500 m high, seen from the south. Below