diff --git a/builder/wasm/wasm_size_guard.py b/builder/wasm/wasm_size_guard.py index 69d996ec3..15a550d03 100644 --- a/builder/wasm/wasm_size_guard.py +++ b/builder/wasm/wasm_size_guard.py @@ -32,9 +32,9 @@ # the sidewalks' slabs with their ends, rings and kerbs, and the portal line's levels with the cover's sides. # The owner allows about 60 kB of code growth for the crossing block, stated in its pull request and recorded here. # The built tunnel ends (obc-trailview-parts) with their open stretches and the approaches to their openings add -# about 36 kB gzipped; measured on that build with wasm-pack 0.15.0 and rustc 1.99.0, which gives the build before it -# about 5 kB more than CI. -GROUND_PLAN_MEASURED = {"gzipped": 828_795, "raw_wasm": 2_129_601} +# about 36 kB gzipped; the openings of a pair's mate (the parts' `mouths`) about 2 kB more, measured in CI with +# wasm-pack 0.15.0 and rustc 1.100.0. +GROUND_PLAN_MEASURED = {"gzipped": 831_313, "raw_wasm": 2_133_837} # The owner's margin: compiler and dependency updates move the size by a few kilobytes and must not fail # unrelated pull requests; real growth past the margin still fails. Raw gets the same fraction as gzipped. # A pull request that changes the bridge's code records its own CI size here; the margin is only for toolchain @@ -46,9 +46,10 @@ } # Measured in CI on the build of the tunnel parts' arch, tube, boxes and underpasses, with a tile's volumes built once -# and selected per node, with wasm-pack 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by the same -# fraction. -PARTS_MEASURED = {"gzipped": 125_922, "raw_wasm": 293_466} +# and selected per node, and the pair, the rim, the closed free end and the cut of two tubes that meet only where both +# are, with the closed cut of a head, with wasm-pack 0.15.0 and rustc 1.100.0. The margin is the ground plan's, raw by +# the same fraction. +PARTS_MEASURED = {"gzipped": 147_785, "raw_wasm": 335_603} PARTS_MARGIN = { "gzipped": GROUND_PLAN_MARGIN_GZIPPED, "raw_wasm": round(GROUND_PLAN_MARGIN_GZIPPED * PARTS_MEASURED["raw_wasm"] / PARTS_MEASURED["gzipped"]), diff --git a/builder/web/src/lib/trailview/structures/parts.ts b/builder/web/src/lib/trailview/structures/parts.ts index 4a360741d..5df07d33b 100644 --- a/builder/web/src/lib/trailview/structures/parts.ts +++ b/builder/web/src/lib/trailview/structures/parts.ts @@ -136,10 +136,10 @@ export function partStamps(list: Feature[], tile: Node, lines: Line[]): PartStam }; for (const { kind, tags } of list) { if (kind !== 'tunnel-end') continue; - for (const [way, shift] of [[tags.way, tags.shift], [tags.mate_way, tags.mate_shift]]) { + for (const [way, shift, collar] of [[tags.way, tags.shift, tags.collar], [tags.mate_way, tags.mate_shift, tags.mate_collar]]) { // `way` is in the frame of the ground plan, 16 units to a world unit. const [x, y] = way?.split(' ').map(Number) ?? []; - for (const [line, end] of at.get(`${x / 16},${y / 16}`) ?? []) stop(line, end, Number(shift) + Number(tags.collar) + COVER_START_M); + for (const [line, end] of at.get(`${x / 16},${y / 16}`) ?? []) stop(line, end, Number(shift) + Number(collar) + COVER_START_M); } } return out; diff --git a/host/obc-data-steps/src/planner.rs b/host/obc-data-steps/src/planner.rs index a31e1dd22..2e1c6d5dd 100644 --- a/host/obc-data-steps/src/planner.rs +++ b/host/obc-data-steps/src/planner.rs @@ -71,7 +71,7 @@ pub static PLANNER_SNOW: Layer = whole("planner/snow", 2, &[&WEB_PLANNER]); /// holds what the stamp worker makes of the tiles; `stamp_version` of `specs/trailview-tiles.md` says /// which stamp code made it. pub static PLANNER_TRAILVIEW_FEATURES: Layer = - Layer { revision: 35, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) }; + Layer { revision: 36, ..whole("planner/trailview-features", 4, &[&WEB_PLANNER]) }; /// The TrailView ruleset, `rules.json` of `specs/trailview-tiles.md`. Its format is `format` of /// `rules.json`, `FORMAT` of `tools/trailview/rules.py`. pub static PLANNER_TRAILVIEW_RULES: Layer = diff --git a/host/obc-ground-plan/src/openings.rs b/host/obc-ground-plan/src/openings.rs index d8cfd0e26..8138c181f 100644 --- a/host/obc-ground-plan/src/openings.rs +++ b/host/obc-ground-plan/src/openings.rs @@ -1,6 +1,6 @@ //! The built tunnel ends of a cell's input (`obc-trailview-parts`): the openings that its ground reaches. -use obc_trailview_parts::{built_ends, Chord, End, Rules}; +use obc_trailview_parts::{mouths, Chord, End, Rules}; use crate::frame::GlobalPoint; use crate::graph::OpenEnd; @@ -48,19 +48,15 @@ pub fn built(input: &CellInput) -> Built { _ => {} } } - let built = built_ends(&ends, &chords, rules); let [x0, y0, x1, y1] = input.key.grown(); - let (mut open, mut mouths) = (Vec::new(), Vec::new()); - for (end, _) in ends.iter().zip(&built).filter(|(_, &b)| b) { - mouths.push(Mouth { at: end.at.map(|v| v * FRAME), into: end.way_in(), half_m: end.half }); - let ways = [Some((end.way, end.shift)), end.mate_way.zip(end.mate_shift)]; - for (way, shift_m) in ways.into_iter().flatten() { - if (x0..=x1).contains(&way[0]) && (y0..=y1).contains(&way[1]) { - open.push(OpenEnd { way: GlobalPoint { x: way[0], y: way[1] }, shift_m }); - } + let (mut open, mut out) = (Vec::new(), Vec::new()); + for m in mouths(&ends, &chords, rules) { + out.push(Mouth { at: m.at.map(|v| v * FRAME), into: m.into, half_m: m.half }); + if (x0..=x1).contains(&m.way[0]) && (y0..=y1).contains(&m.way[1]) { + open.push(OpenEnd { way: GlobalPoint { x: m.way[0], y: m.way[1] }, shift_m: m.shift }); } } - Built { open, mouths } + Built { open, mouths: out } } #[cfg(test)] @@ -220,7 +216,7 @@ mod tests { #[test] fn a_chain_with_an_end_that_is_not_built_keeps_its_tunnel_way() { - let (graph, mesh) = build(&input(Some("arch free"))); + let (graph, mesh) = build(&input(Some("arch none"))); let (develop_graph, develop) = build(&input(None)); assert_eq!((&graph.ways, &graph.samples), (&develop_graph.ways, &develop_graph.samples)); assert_eq!(mesh.to_bytes(), develop.to_bytes()); diff --git a/host/obc-trailview-features/src/parts/ladder.rs b/host/obc-trailview-features/src/parts/ladder.rs index c984879b0..dd3ccf31b 100644 --- a/host/obc-trailview-features/src/parts/ladder.rs +++ b/host/obc-trailview-features/src/parts/ladder.rs @@ -15,17 +15,19 @@ use super::{along_dir, built_openings, counts, distance, first_way_m, left_of, o pub use obc_trailview_parts::Part as Kind; /// The numbers of a drawn opening (Plan 8 of the design): metres, `left` and `right` per metre out from the frame's -/// outer edge, and in a pair the mate's opening and the metres to its axis to the left; `height` is the inside height -/// of the tube's chord there. +/// outer edge, and in a pair the mate's opening, the metres to its axis to the left and its collar; `height` is the +/// inside height of the tube's chord there; `heading` is square to its frame line, into the tube of the opening farther +/// in. #[derive(Clone, Debug, PartialEq)] pub(crate) struct Numbers { + pub heading: f64, pub height: f64, pub collar: f64, pub face: f64, pub left: Vec, pub right: Vec, pub foot: f64, - pub mate: Option<(usize, f64)>, + pub mate: Option<(usize, f64, f64)>, } /// An opening's decision: every kind that fits in the order of the rungs, the part of the end (the first; also the @@ -260,15 +262,23 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me rung[i] = Some(r); kinds[i] = k; } - // Rung 5: the pairs, nearest first, each end in one pair at most. + // Rung 5: the pairs, nearest first, each end in one pair at most. A pair is one part of two chains, so each of them + // has a part at both of its ends. let mut mate: Vec> = vec![None; n]; let is_hill = |i: usize| hill.contains(&i); + // The opening at each end of each tube. + let mut at_end: Vec<[Option; 2]> = vec![[None; 2]; tubes.len()]; + for (i, o) in openings.iter().enumerate() { + at_end[o.tube][o.end].get_or_insert(i); + } + let whole: Vec = at_end.iter().map(|e| e.iter().all(|i| i.is_some_and(|i| !kinds[i].is_empty()))).collect(); for x in &near { let (a, c) = (x.a, x.b); if !is_hill(a) || !is_hill(c) || mate[a].is_some() || mate[c].is_some() { continue; } - if tubes[openings[a].tube].rail != tubes[openings[c].tube].rail { + let (ta, tc) = (openings[a].tube, openings[c].tube); + if tubes[ta].rail != tubes[tc].rail || !whole[ta] || !whole[tc] { continue; } mate[a] = Some(c); @@ -369,17 +379,17 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me let refitted = (0..n).filter(|&i| kinds[i].first().copied() != before[i]).count(); // The floor of each tube with a part, from opening to opening; an end with no opening holds the end vertex. Its // chord at an opening gives the opening its inside height. - let spans: Vec> = (0..tubes.len()) - .map(|t| { - let at = |end: usize| openings.iter().position(|o| o.tube == t && o.end == end); - let with = [at(0), at(1)].into_iter().flatten().any(|i| !kinds[i].is_empty()); - let s0 = at(0).map_or(0.0, |i| openings[i].s); - let s1 = at(1).map_or(tubes[t].curve.len, |i| openings[i].s); + let spans: Vec> = (tubes.iter().zip(&at_end)) + .map(|(t, &[a, z])| { + let with = [a, z].into_iter().flatten().any(|i| !kinds[i].is_empty()); + let s0 = a.map_or(0.0, |i| openings[i].s); + let s1 = z.map_or(t.curve.len, |i| openings[i].s); (with && s1 - s0 > 1e-6).then_some([s0, s1]) }) .collect(); let (floors, floor_metrics) = floor::floors(tubes, &spans, (&half, &height), input); let end_height = |o: &Opening| floors[o.tube].as_ref().map_or(height[o.tube], |f| f.end_height(o.end)); + let heights: Vec = openings.iter().map(end_height).collect(); // The numbers of each drawn opening. let mut ends: Vec = Vec::with_capacity(n); for i in 0..n { @@ -387,9 +397,8 @@ pub(crate) fn decide(tubes: &[Tube], openings: &mut [Opening], input: &Input, me // A pair has one record, at the opening of the lower feature id. let drawn = mate[i].is_none_or(|m| (openings[i].way_id, i) < (openings[m].way_id, m)); let m = Measured { sites: &sites, rights: &rights, cover: &cover, moved: &moved }; - let h = end_height(&openings[i]); let numbers = (kind.filter(|_| drawn)) - .map(|kind| numbers(i, kind, (mate[i], far_of[i]), &m, (openings, tubes), (&half, h), input)); + .map(|kind| numbers(i, kind, (mate[i], far_of[i]), &m, (openings, tubes), (&half, &heights), input)); ends.push(End { kinds: kinds[i].clone(), kind, rung: rung[i].unwrap_or_default(), numbers }); } let shown = |e: &End| match e.kind { @@ -424,15 +433,15 @@ struct Measured<'a> { moved: &'a [f64], } -/// The numbers of drawn opening i of `kind` (Plan 8) with the inside height `h` there: its frame is its own, or in a -/// pair the frame line of the opening farther in, which holds both. +/// The numbers of drawn opening i of `kind` (Plan 8), with the inside height of each opening: its frame is its own, or +/// in a pair the frame line of the opening farther in, which holds both. fn numbers( i: usize, kind: Kind, (mate, far): (Option, usize), m: &Measured, (openings, tubes): (&[Opening], &[Tube]), - (half, h): (&[f64], f64), + (half, heights): (&[f64], &[f64]), input: &Input, ) -> Numbers { let Measured { sites, rights, cover, moved } = *m; @@ -456,8 +465,11 @@ fn numbers( .filter_map(ground) .collect(); let highest = frame.iter().copied().fold(f64::NEG_INFINITY, f64::max); - let mut face = (h + b.shell_m + b.band_m).max(highest - floor + b.coping_m); - face = face.min(h + b.shell_m + b.face_over_crown_max_m); + // The wall holds its band over the higher crown of the frame's tubes, and fits the ground up to its cap over the + // lower. + let crowns = members.iter().map(|&k| openings[k].floor - floor + heights[k] + b.shell_m); + let (low, high) = crowns.fold((f64::INFINITY, f64::NEG_INFINITY), |(l, h), c| (l.min(c), h.max(c))); + let mut face = (high + b.band_m).max((highest - floor + b.coping_m).min(low + b.face_over_crown_max_m)); // A deck over the frame line or its wing walls: its underside lies over the floor (a way that goes on from the // opening on a deck lies at the floor, not over it). for &(x, under) in &site.decks { @@ -489,22 +501,37 @@ fn numbers( let (left, right) = (wing(hi, 1.0), wing(lo, -1.0)); let collar_of = |k: usize| cover[k].map(|d| (d - moved[k]).max(0.0)); let half_chain = t.curve.len / 2.0; - let collar = match kind { - Kind::Pair => members.iter().filter_map(|&k| collar_of(k)).fold(0.0, f64::max), - Kind::Arch | Kind::Rock => collar_of(i).expect("an arch is covered within its collar"), - Kind::Box => collar_of(i).unwrap_or(f64::INFINITY).min(half_chain), - Kind::Free => collar_of(i).unwrap_or(f64::INFINITY).min(b.free_max_m).min(half_chain), - }; - // The lowest ground under the frame, its wing walls and the collar. - let own = sites[i].as_ref().expect("a measured opening"); + // Each tube of a pair has its own collar. + let collars: Vec = (members.iter()) + .map(|&k| match kind { + Kind::Pair | Kind::Arch | Kind::Rock => collar_of(k).expect("an arch is covered within its collar"), + Kind::Box => collar_of(k).unwrap_or(f64::INFINITY).min(half_chain), + Kind::Free => collar_of(k).unwrap_or(f64::INFINITY).min(b.free_max_m).min(half_chain), + }) + .collect(); + // The lowest ground under the frame, its wing walls and the collars, and the floors. let (from, to) = (lo - right.len() as f64, hi + left.len() as f64); let under = (from.ceil() as i64..=to.floor() as i64).filter_map(|x| ground(x as f64)); - let collar_ground = (own.stations.iter()) - .skip(moved[i].round() as usize) - .take(collar.ceil() as usize + 1) - .flat_map(|st| st.iter().flatten().copied()); - let lowest = under.chain(collar_ground).fold(floor, f64::min); - let mate = mate.map(|m| (m, axis(m) - axis(i))); + let collar_ground = members.iter().zip(&collars).flat_map(|(&k, collar)| { + let site = sites[k].as_ref().expect("a measured opening"); + (site.stations.iter()) + .skip(moved[k].round() as usize) + .take(collar.ceil() as usize + 1) + .flat_map(|st| st.iter().flatten().copied()) + }); + let floors = members.iter().map(|&k| openings[k].floor); + let lowest = under.chain(collar_ground).chain(floors).fold(floor, f64::min); + let mate = mate.map(|m| (m, axis(m) - axis(i), collars[1])); let numbers = if kind == Kind::Free { (Vec::new(), Vec::new()) } else { (left, right) }; - Numbers { height: h, collar, face, left: numbers.0, right: numbers.1, foot: lowest - b.foot_m - floor, mate } + let heading = openings[far].heading(); + Numbers { + heading, + height: heights[i], + collar: collars[0], + face, + left: numbers.0, + right: numbers.1, + foot: lowest - b.foot_m - floor, + mate, + } } diff --git a/host/obc-trailview-features/src/parts/mod.rs b/host/obc-trailview-features/src/parts/mod.rs index afc21c139..be59a3206 100644 --- a/host/obc-trailview-features/src/parts/mod.rs +++ b/host/obc-trailview-features/src/parts/mod.rs @@ -548,7 +548,7 @@ fn records(tubes: &[Tube], openings: &[Opening], decided: &ladder::Decided, inpu let look = if kind == Kind::Rock { "rock" } else { input.rules.groups[tubes[o.tube].group].look.as_str() }; t.insert("look".into(), look.into()); t.insert("part".into(), kind.name().into()); - t.insert("heading".into(), format!("{}", (o.heading() * 1000.0).round() / 1000.0)); + t.insert("heading".into(), format!("{}", (n.heading * 1000.0).round() / 1000.0)); t.insert("collar".into(), num(n.collar)); if kind != Kind::Free { t.insert("face".into(), num(n.face)); @@ -558,10 +558,11 @@ fn records(tubes: &[Tube], openings: &[Opening], decided: &ladder::Decided, inpu t.insert("foot".into(), num(n.foot)); t.insert("way".into(), format!("{} {}", o.way[0], o.way[1])); t.insert("shift".into(), num(o.shift)); - if let Some((mate, m)) = n.mate.as_ref().map(|(i, m)| (&openings[*i], *m)) { + if let Some((mate, m, collar)) = n.mate.map(|(i, m, collar)| (&openings[i], m, collar)) { t.insert("mate".into(), num(m)); t.insert("mate_way".into(), format!("{} {}", mate.way[0], mate.way[1])); t.insert("mate_shift".into(), num(mate.shift)); + t.insert("mate_collar".into(), num(collar)); } let part = Part { outer: false, points: vec![o.p], z: Some(vec![o.floor]), plan: None }; features.push(("tunnel-end", t, part)); diff --git a/host/obc-trailview-features/src/parts/tests.rs b/host/obc-trailview-features/src/parts/tests.rs index 65444c4fa..209eed5e7 100644 --- a/host/obc-trailview-features/src/parts/tests.rs +++ b/host/obc-trailview-features/src/parts/tests.rs @@ -207,13 +207,15 @@ fn each_rung_gives_its_kinds_in_the_order_of_the_rungs() { #[test] fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { use Kind::*; - // Two road tunnels 20 m apart under one ridge; the second starts 3 m farther in. A footway 2.5 m beside the first - // lies in its tube. + // Two road tunnels 20 m apart under one ridge, which rises half as fast over the second; the second starts 3 m + // farther in. A footway 2.5 m beside the first lies in its tube. let mut case = Case::default(); let a = case.tunnel(&ROAD, (0.0, 200.0), 0.0); let b = case.tunnel(&ROAD, (3.0, 200.0), 20.0); let foot = case.tunnel(&FOOT, (0.0, 200.0), 2.5); - let placed = case.place(&site(&ridge(200.0, 1.0), &[], false), &mut Vec::new()); + let (steep, gentle) = (ridge(200.0, 1.0), ridge(200.0, 0.5)); + let ground = |p: [f64; 2]| if p[1] < 10.0 { steep(p) } else { gentle(p) }; + let placed = case.place(&site(&ground, &[], false), &mut Vec::new()); assert_eq!(of(&placed, a), vec![(vec![Pair, Arch, Free], "hill"); 2]); assert_eq!(of(&placed, b), vec![(vec![Pair, Arch, Free], "hill"); 2]); assert_eq!(of(&placed, foot), vec![(vec![], "same tube"); 2]); @@ -223,9 +225,12 @@ fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { assert_eq!(ends.len(), 2); let west = ends.iter().find(|t| t["mate"] == "20").expect("the west pair"); assert_eq!((west["part"].as_str(), west["shift"].as_str(), west["mate_shift"].as_str()), ("pair", "3", "0")); - assert!(ends.iter().any(|t| t["mate"] == "-20" && t["shift"] == "0")); - // A pair is not built yet: the device keeps the moved stretch a tunnel, and so does the measure of the numbers. - assert_eq!(placed.metrics["measured_again"].as_u64(), Some(0)); + let east = ends.iter().find(|t| t["mate"] == "-20" && t["shift"] == "0").expect("the east pair"); + // Each tube has its own collar: the hill over the second comes later, and the first moved 3 m in. + assert_eq!((west["collar"].as_str(), west["mate_collar"].as_str()), ("4", "9")); + assert_eq!((east["collar"].as_str(), east["mate_collar"].as_str()), ("7", "12")); + // A pair is built: the device opens the moved stretch, so the measure reads the four openings near it again. + assert_eq!(placed.metrics["measured_again"].as_u64(), Some(4)); // The first tube widens to the far edge of the footway and its margin. let foot_half = widths().way("tunnel", &tags(&FOOT), false).half_m; assert_eq!(west["half"], num(2.5 + foot_half + 0.6)); @@ -239,6 +244,18 @@ fn a_pair_has_one_frame_line_and_a_way_in_a_wider_tube_has_no_part() { assert_eq!(of(&placed, a), [(vec![Arch, Free], "hill")]); assert_eq!(of(&placed, b)[0], (vec![Arch, Free], "hill")); assert_eq!(placed.metrics["pairs_that_do_not_reach"].as_u64(), Some(1)); + // A pair is one part of two chains: where the second chain forks in the hill, so that its end there has no part, + // the two are no pair. + let mut case = Case::default(); + let a = case.tunnel(&ROAD, (0.0, 200.0), 0.0); + let b = case.tunnel(&ROAD, (3.0, 200.0), 20.0); + for n in [60.0, -20.0] { + case.ways.push(("tunnel", tags(&ROAD), vec![part(&[[200.0, 20.0], [210.0, n]], &[500.0; 2])])); + } + let placed = case.place(&site(&ridge(200.0, 1.0), &[], false), &mut Vec::new()); + assert_eq!(of(&placed, a)[0], (vec![Arch, Free], "hill")); + assert_eq!(of(&placed, b)[0], (vec![Arch, Free], "hill")); + assert_eq!(placed.tags[&b]["parts"], "arch none"); } #[test] diff --git a/host/obc-trailview-parts/src/arch.rs b/host/obc-trailview-parts/src/arch.rs index db72c77bc..63d4ecf1a 100644 --- a/host/obc-trailview-parts/src/arch.rs +++ b/host/obc-trailview-parts/src/arch.rs @@ -1,19 +1,22 @@ -//! The arch: a head wall on the frame line, with a frame round the opening and wings whose tops follow the rows of -//! the bake; the outer shell of the part; and the dark face in the opening. +//! The head of a part at its opening. An arch: a head wall on the frame line, with a frame round the opening and wings +//! whose tops follow the rows of the bake; the two openings of a pair have one. A rim: the head wall of an opening in +//! the rock and of a free tube end hugs the opening. Then the outer shell of the part and the dark face in the opening. +//! A free end covered at its opening ends in the hill, closed by a dark face, with no head. use crate::boxes; -use crate::mesh::{flagged, flat, outline, Builder, Corner, Station, VOID}; -use crate::tube::{self, direction, inward, spring, Net}; -use crate::Section; +use crate::mesh::{flagged, flat, outline, Builder, Clip, Corner, Station, VOID}; +use crate::tube::{self, cut_face, direction, inward, spring, top_at, Net}; +use crate::{Part, Section}; /// A piece of the shell: its start and end station across to the left of the way in, its chord's height and section, /// and the chord and its vertex at the end. pub type Piece = (Station, Station, f64, Section, usize, usize); -/// The pieces of the shell of end e: per chord from the back of the head wall to `to` metres in. +/// The pieces of the shell of end e: per chord from the back of the head wall, or from the frame line of a closed end, +/// to `to` metres in. pub fn collar(net: &Net, e: usize, to: f64) -> Vec { let design = &net.rules.design; - let from = design.face_m - design.recess_m; + let from = if net.closed(e) { 0.0 } else { design.face_m - design.recess_m }; let mut out = Vec::new(); for (c, forward, start) in net.walk(e, to) { let chord = &net.chords[c]; @@ -30,16 +33,58 @@ pub fn collar(net: &Net, e: usize, to: f64) -> Vec { out } -/// The top of the head wall `t` metres across to the left of its axis, over the opening's floor: `face` over the -/// frame, then the rows of the wings, a value per metre out from the frame's outer edge `edge`. A wing's top is at most -/// a line that falls to its coping's height `coping` at the end of its row: `slope` metres per metre, or more steeply -/// where the row is too short to fall from `face` at the frame's edge. So the top goes on from the head wall with no -/// step, and where the ground goes on past the row, the coping goes into it and no high face ends the wall. -fn top(end: &crate::End, edge: f64, (coping, slope): (f64, f64), t: f64) -> f64 { - let (row, d) = if t > edge { - (&end.left, t - edge) - } else if t < -edge { - (&end.right, -t - edge) +/// Whether end e's head is a rim that hugs its opening, not a head wall with wings. +fn rim(net: &Net, e: usize) -> bool { + matches!(net.ends[e].part, Part::Rock | Part::Free) +} + +/// The metres to the left of end e's axis of the outer edges of its frame: of its opening, or of both openings of a +/// pair. +fn edges(net: &Net, e: usize) -> (f64, f64) { + let shell = net.rules.ladder.bake.shell_m; + let edge = half_at(net, e) + shell; + match (net.mate[e], net.ends[e].mate.map(|m| m.across)) { + (Some(m), Some(a)) => { + let other = half_at(net, m) + shell; + ((-edge).min(a - other), edge.max(a + other)) + } + _ => (-edge, edge), + } +} + +/// The inside half-width of end e's tube at its opening. +fn half_at(net: &Net, e: usize) -> f64 { + net.opening(e).map_or(net.ends[e].half, |(c, _)| net.chords[c].half) +} + +/// The outline of end e's rim, round its opening's outline grown by the frame and the shell. +fn rim_outline(net: &Net, e: usize) -> Vec { + let (end, design) = (&net.ends[e], &net.rules.design); + let grow = design.frame_m + net.rules.ladder.bake.shell_m; + let sp = spring(net, end.section, end.height); + outline(end.section, half_at(net, e) + grow, end.height + grow, sp, design.arch_segments) +} + +/// The metres to the left of end e's axis of the two ends of its head: of its rim, or of its head wall with its wings. +pub fn wide(net: &Net, e: usize) -> (f64, f64) { + if rim(net, e) { + let o = rim_outline(net, e); + return (o[0][0], o[o.len() - 1][0]); + } + let (end, (lo, hi)) = (&net.ends[e], edges(net, e)); + (lo - end.right.len() as f64, hi + end.left.len() as f64) +} + +/// The top of a head wall `t` metres across to the left of its axis, over the opening's floor: `face` over the frame +/// from `lo` to `hi`, then the rows of the wings, a value per metre out. A wing's top is at most a line that falls to +/// its coping's height `coping` at the end of its row: `slope` metres per metre, or more steeply where the row is too +/// short to fall from `face` at the frame's edge. So the top goes on from the head wall with no step, and where the +/// ground goes on past the row, the coping goes into it and no high face ends the wall. +fn top(end: &crate::End, (lo, hi): (f64, f64), (coping, slope): (f64, f64), t: f64) -> f64 { + let (row, d) = if t > hi { + (&end.left, t - hi) + } else if t < lo { + (&end.right, lo - t) } else { return end.face; }; @@ -53,83 +98,175 @@ fn top(end: &crate::End, edge: f64, (coping, slope): (f64, f64), t: f64) -> f64 along.min(coping + slope.max((end.face - coping) / len) * (len - d)) } -/// The faces of the arch at end e: its head wall, the sill, the reveal and the frame round the opening, the dark face -/// in it, and the shell of its collar. The head wall and the shell go down to one level (`boxes::foot`); the sill lies `lift_m` under the floor, under the road of the tube and of the ground. Faces that meet share -/// the corners of their edges. +/// End e's opening outline grown by `grow`, from the sill up its side to a corner at the floor's height there, where +/// the tube's wall stands on the floor, and on over its top. +fn grown(net: &Net, e: usize, grow: f64) -> Vec { + let Some((c, _)) = net.opening(e) else { return Vec::new() }; + let (chord, design) = (&net.chords[c], &net.rules.design); + let pieces = tube::floor_pieces(net, chord); + let sp = spring(net, chord.section, chord.height); + let o = outline(chord.section, chord.half + grow, chord.height + grow, sp, design.arch_segments); + let (first, last) = (o[0][0], o[o.len() - 1][0]); + let sides = |x: f64, top: f64| [[x, -design.lift_m], [x, top]]; + let mut out = sides(first, pieces[0].2).to_vec(); + out.extend_from_slice(&o[1..o.len() - 1]); + out.extend(sides(last, pieces[pieces.len() - 1].2).into_iter().rev()); + out +} + +/// Where end e's head ends at another part: on each side, the nearest built tube that crosses its frame line within +/// reach of the head, or whose opening's approach crosses it within `pair_max_m` of the opening, and whose room +/// overlaps the head from its foot to its top (`Net::meets` with the head's metres across and heights): the metres +/// across to the middle between the two tubes' walls, and the side (1 to the left). The mate of a pair crosses it at +/// its opening; the approach keeps a head out of the way to an opening behind it. +fn head_cuts(net: &Net, e: usize, foot: f64) -> Vec<(f64, f64)> { + let Some((c, _)) = net.opening(e) else { return Vec::new() }; + let (end, chord, (design, bake)) = (&net.ends[e], &net.chords[c], (&net.rules.design, &net.rules.ladder.bake)); + let (right, left) = wide(net, e); + let st = net.frame(e, 0.0); + let up = [foot - st.z, end.face.max(chord.height + design.frame_m + bake.shell_m)]; + let meet = tube::Meet { across: [-right, left], past: tube::MEET_PAST_M, approach: bake.pair_max_m, up: Some(up) }; + let cuts = net.meets(c, &st, meet); + cuts.into_iter().flatten().map(|cut| (cut.x, cut.axis.signum())).collect() +} + +/// The faces of the head at end e: its head wall or rim, the sill, the reveal and the frame round the opening, the dark +/// face in it, and the shell of its collar. The head and the shell go down to one level (`boxes::foot`); the sill lies +/// `lift_m` under the floor, under the road of the tube and of the ground. Faces that meet share the corners of their +/// edges. Each opening of a pair draws the head wall of both with its own hole, on its side of the middle between their +/// walls, and closes the reveal where the two holes differ there. pub fn faces f64>(b: &mut Builder, net: &Net, e: usize) { let end = &net.ends[e]; - let Some((c, _)) = net.opening(e) else { return }; + let Some((c, k)) = net.opening(e) else { return }; let chord = &net.chords[c]; let look = &net.rules.looks[&end.look]; let (design, bake) = (&net.rules.design, &net.rules.ladder.bake); - let (n, sill, foot) = (design.arch_segments, -design.lift_m, boxes::foot(net, e)); - let (half, edge) = (chord.half, chord.half + bake.shell_m); + let (sill, foot) = (-design.lift_m, boxes::foot(net, e)); + let half = chord.half; let sp = spring(net, chord.section, chord.height); - let pieces = tube::floor_pieces(net, chord); - // An outline of the opening grown by `grow`, from the sill up its side to a corner at the floor's height there, - // where the tube's wall stands on the floor, and on over its top. - let grown = |grow: f64| { - let o = outline(chord.section, half + grow, chord.height + grow, sp, n); - let (first, last) = (o[0][0], o[o.len() - 1][0]); - let sides = |x: f64, top: f64| [[x, sill], [x, top]]; - let mut out = sides(first, pieces[0].2).to_vec(); - out.extend_from_slice(&o[1..o.len() - 1]); - out.extend(sides(last, pieces[pieces.len() - 1].2).into_iter().rev()); - out - }; - let (inner, hole) = (grown(0.0), grown(design.frame_m)); - let (front, ring, back) = - (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); let reach = boxes::reach(net, e); let shell = collar(net, e, reach.shell); - let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); let into = end.way_in(); let (inward_, outward) = (flat(into), flat([-into[0], -into[1]])); - let wide = (-(edge + end.right.len() as f64), edge + end.left.len() as f64); - let top = |t: f64| top(end, edge, (bake.coping_m, design.wing_slope), t); - let wall = Wall { top: &top, wide, edge, foot, coping: bake.coping_m, face: look.face, cope: look.coping }; - // The sill is split where the pieces of the floor meet the front of the tube. - let hw = hole[0][0].abs(); - let sills: Vec = - [-hw].into_iter().chain(pieces.iter().map(|p| p.0)).chain([pieces[pieces.len() - 1].1, hw]).collect(); - let front_top = wall.face(b, &front, &hole, &sills, outward); - // The back's hole is the outside of the collar's shell, which goes on from it. - let back_top = wall.face(b, &back, &tube::shell_outline(net, section, half, h, foot - back.z), &[], inward_); - b.strip((&front, &front_top), (&back, &back_top), look.coping, [0.0, 0.0, 1.0]); - for t in [wide.0, wide.1] { - wall.column( - b, - (&front, t, &wall.side(&front, t, &[])), - (&back, t, &wall.side(&back, t, &[])), - front.out([t.signum(), 0.0]), - ); - } - // The sill from the front to the frame line, the reveal, and the frame round the opening. - for w in sills.windows(2) { - let line = [[w[0], sill], [w[1], sill]]; - b.strip((&front, &line), (&ring, &line), look.face, [0.0, 0.0, 1.0]); - } - for k in 0..hole.len() - 1 { - b.strip( - (&front, &hole[k..k + 2]), - (&ring, &hole[k..k + 2]), - look.face, - front.out(inward(hole[k], hole[k + 1], sp)), + if net.closed(e) { + closed(b, net, (e, c, k), foot); + } else { + let pieces = tube::floor_pieces(net, chord); + let (inner, hole) = (grown(net, e, 0.0), grown(net, e, design.frame_m)); + let (front, ring, back) = + (net.frame(e, -design.recess_m), net.frame(e, 0.0), net.frame(e, design.face_m - design.recess_m)); + let (h, section) = shell.first().map_or((chord.height, chord.section), |p| (p.2, p.3)); + let cuts = head_cuts(net, e, foot); + b.clip( + (cuts.iter()) + .map(|&(x, side)| { + let x = x + side * tube::OVERLAP_M; + let (p, q, r) = (front.at([x, 0.0]), back.at([x, 0.0]), front.at([x + side, 0.0])); + Clip { a: [p[0], p[1]], b: [q[0], q[1]], away: [r[0] - p[0], r[1] - p[1]], bound: None } + }) + .collect(), ); - b.strip((&ring, &hole[k..k + 2]), (&ring, &inner[k..k + 2]), look.frame, outward); - } - // The dark face in the opening, which the viewer draws where the terrain is coarse. - let dark = flagged(net.rules.inside.void, VOID); - let st = net.frame(e, design.void_m); - let centre = b.at(&st, [0.0, chord.height / 2.0], dark); - let rim: Vec = inner.iter().map(|&c| b.at(&st, c, dark)).collect(); - for k in 0..rim.len() { - b.triangle(centre, rim[k], rim[(k + 1) % rim.len()], outward); + let wide = wide(net, e); + let (rim, edges) = (rim(net, e), edges(net, e)); + let rim_line = rim_outline(net, e); + // The rows of a pair are over the floor of its record's opening, the end of the input before its mate. + let record = net.mate[e].filter(|&m| m < e).map_or(0.0, |m| net.ends[m].z - end.z); + let top = |t: f64| { + if rim { + top_at(&rim_line, t).unwrap_or(0.0) + } else { + top(end, edges, (bake.coping_m + record, design.wing_slope), t) + } + }; + let (edges, coping, cope) = if rim { (wide, 0.0, look.face) } else { (edges, bake.coping_m, look.coping) }; + let wall = Wall { top: &top, wide, edges, foot, coping, face: look.face, cope }; + // The sill is split where the pieces of the floor meet the front of the tube. + let hw = hole[0][0].abs(); + let sills: Vec = + [-hw].into_iter().chain(pieces.iter().map(|p| p.0)).chain([pieces[pieces.len() - 1].1, hw]).collect(); + let front_top = wall.face(b, &front, &hole, &sills, outward); + // The back's hole is the outside of the collar's shell, which goes on from it. + let back_top = wall.face(b, &back, &tube::shell_outline(net, section, half, h, foot - back.z), &[], inward_); + b.strip((&front, &front_top), (&back, &back_top), cope, [0.0, 0.0, 1.0]); + for t in [wide.0, wide.1] { + wall.column( + b, + (&front, t, &wall.side(&front, t, &[])), + (&back, t, &wall.side(&back, t, &[])), + front.out([t.signum(), 0.0]), + ); + } + // The sill from the front to the frame line, the reveal, and the frame round the opening. + for w in sills.windows(2) { + let line = [[w[0], sill], [w[1], sill]]; + b.strip((&front, &line), (&ring, &line), look.face, [0.0, 0.0, 1.0]); + } + for k in 0..hole.len() - 1 { + b.strip( + (&front, &hole[k..k + 2]), + (&ring, &hole[k..k + 2]), + look.face, + front.out(inward(hole[k], hole[k + 1], sp)), + ); + b.strip((&ring, &hole[k..k + 2]), (&ring, &inner[k..k + 2]), look.frame, outward); + } + // The dark face in the opening, which the viewer draws where the terrain is coarse. + let dark = flagged(net.rules.inside.void, VOID); + let st = net.frame(e, design.void_m); + let centre = b.at(&st, [0.0, chord.height / 2.0], dark); + let rim_v: Vec = inner.iter().map(|&c| b.at(&st, c, dark)).collect(); + for k in 0..rim_v.len() { + b.triangle(centre, rim_v[k], rim_v[(k + 1) % rim_v.len()], outward); + } + b.clip(Vec::new()); + // At a cut, a face closes the head's section, facing the other part: from the foot to the top, but the hole + // from the front to the frame line and the room from there to the back. Where the other part's head stands + // on the same line, it lies in that head's wall. + for &(x, side) in &cuts { + // `max` and `min`, not `clamp`: its check of the bounds would bring the formatting of floats into the WASM. + let solid = |st: &Station, (lo, hi): (Option, Option)| { + let (foot, top) = (foot - st.z, top(x).max(foot - st.z)); + match lo.zip(hi).filter(|(l, h)| h > l) { + Some((l, h)) => [(foot, l.max(foot).min(top)), (h.max(foot).min(top), top)], + None => [(foot, top), (top, top)], + } + }; + let floor = pieces.iter().find(|p| x >= p.0 - 1e-9 && x <= p.1 + 1e-9).map(|p| p.2); + let hole_span = (top_at(&hole, x).map(|_| sill), top_at(&hole, x)); + let room_span = (floor, top_at(&inner, x)); + for (s0, s1, span) in [(&front, &ring, hole_span), (&ring, &back, room_span)] { + let (a, z) = (solid(s0, span), solid(s1, span)); + for i in 0..2 { + cut_face(b, (s0, s1), (x, a[i].0, a[i].1), (x, z[i].0, z[i].1), look.face, front.out([side, 0.0])); + } + } + } } - let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3)).collect(); + let run: Vec<_> = shell.iter().map(|p| (p.0, p.1, p.2, p.3, p.4)).collect(); tube::shell(b, net, &run, half, foot, look.shell, reach.then); if let Some(&(s, t, _, _, c, k)) = shell.last().filter(|_| reach.closed) { + b.clip(net.clips(c, (&s, &t)).iter().map(|m| m.clip).collect()); end_face(b, net, (c, k), &t, foot, look.shell, flat([t.x - s.x, t.y - s.y])); + b.clip(Vec::new()); + } +} + +/// The front of a closed end e at chord c's vertex k: the face that closes its shell on the frame line, and over the +/// inside of its tube a dark face that the viewer always draws, seen from inside. +fn closed f64>(b: &mut Builder, net: &Net, (e, c, k): (usize, usize, usize), foot: f64) { + let (end, chord) = (&net.ends[e], &net.chords[c]); + let (ring, into) = (net.frame(e, 0.0), net.ends[e].way_in()); + let look = &net.rules.looks[&end.look]; + end_face(b, net, (c, k), &ring, foot, look.shell, flat([-into[0], -into[1]])); + // The room's outline round, from the right wall's foot: up and over, down the left wall, back across the floor. + let (right, left) = room(net, (c, k)); + let mut round = right; + round.extend(left[1..left.len() - 1].iter().rev()); + let dark = net.rules.inside.void; + let centre = b.at(&ring, [0.0, chord.height / 2.0], dark); + let rim: Vec = round.iter().map(|&c| b.at(&ring, c, dark)).collect(); + for k in 0..rim.len() { + b.triangle(centre, rim[k], rim[(k + 1) % rim.len()], flat(into)); } } @@ -147,19 +284,29 @@ fn end_face f64>( out: [f64; 3], ) { let chord = &net.chords[c]; - let sp = spring(net, chord.section, chord.height); let shell = tube::shell_outline(net, chord.section, chord.half, chord.height, foot - t.z); + let n = shell.len(); + let (right, left) = room(net, (c, k)); + b.strip((t, &shell[..n - 1]), (t, &right), colour, out); + let bottom = [shell[0], shell[n - 1], shell[n - 2]]; + b.strip((t, &bottom), (t, &left), colour, out); +} + +/// The room of chord c at its vertex k, as the inside draws it there, in two runs from the right wall's foot to the +/// left spring: up the right wall and over the vault; across the floor (each piece's top, and both tops where two +/// pieces meet) and up the left wall. A wall has the spring of a lower chord that goes on there. +fn room(net: &Net, (c, k): (usize, usize)) -> (Vec, Vec) { + let chord = &net.chords[c]; + let sp = spring(net, chord.section, chord.height); let inner = outline(chord.section, chord.half, chord.height, sp, net.rules.design.arch_segments); let (n, pieces) = (inner.len(), tube::floor_pieces(net, chord)); let lower = net.lower(c, k).map(|l| spring(net, chord.section, l)); - // The inside's wall from the floor at `x` up to the spring, with the spring of a lower chord between. let wall = |x: f64, floor: f64| { let mut w = vec![[x, floor]]; w.extend(lower.filter(|&l| l > floor && l < sp).map(|l| [x, l])); w.push([x, sp]); w }; - // The floor from the right wall to the left: each piece's top, and both tops where two pieces meet. let mut floor: Vec = vec![[pieces[0].0, pieces[0].2]]; for w in pieces.windows(2) { floor.push([w[0].1, w[0].2]); @@ -169,11 +316,8 @@ fn end_face f64>( floor.dedup(); let right: Vec = wall(inner[0][0], pieces[0].2).into_iter().chain(inner[2..n - 1].iter().copied()).collect(); - let mut left = floor.clone(); - left.extend(wall(inner[n - 1][0], pieces[pieces.len() - 1].2).into_iter().skip(1)); - b.strip((t, &shell[..n - 1]), (t, &right), colour, out); - let bottom = [shell[0], shell[n - 1], shell[n - 2]]; - b.strip((t, &bottom), (t, &left), colour, out); + floor.extend(wall(inner[n - 1][0], pieces[pieces.len() - 1].2).into_iter().skip(1)); + (right, floor) } /// Whole metres from a to b, with a and b. @@ -192,12 +336,12 @@ fn metres(a: f64, b: f64) -> Vec { out } -/// A face of a head wall: its top over the opening's floor, flat out to `edge` across and per metre out past it, the -/// metres across of its two ends, the height of its foot, the depth of its coping and its colours. +/// A face of a head wall: its top over the opening's floor, flat or round between `edges` across and per metre out past +/// them, the metres across of its two ends, the height of its foot, the depth of its coping and its colours. struct Wall<'a> { top: &'a dyn Fn(f64) -> f64, wide: (f64, f64), - edge: f64, + edges: (f64, f64), foot: f64, coping: f64, face: u32, @@ -245,17 +389,17 @@ impl Wall<'_> { sills: &[f64], out: [f64; 3], ) -> Vec { - let (n, hw, foot, (wide, edge)) = (hole.len(), hole[0][0].abs(), self.foot - st.z, (self.wide, self.edge)); + let (n, hw, foot, (wide, edges)) = (hole.len(), hole[0][0].abs(), self.foot - st.z, (self.wide, self.edges)); // The side of the hole up to where its top starts. let rise = hole.iter().position(|p| p[0] != hole[0][0]).unwrap() - 1; let jamb: Vec = [foot].into_iter().chain(hole[..=rise].iter().map(|p| p[1])).collect(); let mut columns: Vec<(f64, Side)> = - (metres(wide.0, -edge).into_iter().filter(|&t| t < -hw)).map(|t| (t, self.side(st, t, &[]))).collect(); + (metres(wide.0, edges.0).into_iter().filter(|&t| t < -hw)).map(|t| (t, self.side(st, t, &[]))).collect(); columns.push((-hw, self.side(st, -hw, &jamb))); let over: Vec<(f64, Side)> = hole[rise..n - rise].iter().map(|p| (p[0], self.side(st, p[0], &[p[1]]))).collect(); let mut left = vec![(hw, self.side(st, hw, &jamb))]; - left.extend((metres(edge, wide.1).into_iter().filter(|&t| t > hw)).map(|t| (t, self.side(st, t, &[])))); + left.extend((metres(edges.1, wide.1).into_iter().filter(|&t| t > hw)).map(|t| (t, self.side(st, t, &[])))); for list in [&columns, &over, &left] { for w in list.windows(2) { self.column(b, (st, w[0].0, &w[0].1), (st, w[1].0, &w[1].1), out); diff --git a/host/obc-trailview-parts/src/boxes.rs b/host/obc-trailview-parts/src/boxes.rs index 54f3a61d6..15626e873 100644 --- a/host/obc-trailview-parts/src/boxes.rs +++ b/host/obc-trailview-parts/src/boxes.rs @@ -191,8 +191,8 @@ impl Line { } /// The boxes of built end e: the opening's, from the front of the head wall to the frame line, its outline grown to -/// the middle of the wall round it; then one per straight piece of the tube's axis out to its reach, each at the -/// middle of the wall of its section, its ends in the planes of the tube's rings there. +/// the middle of the wall round it, but at a closed end; then one per straight piece of the tube's axis out to its +/// reach, each at the middle of the wall of its section, its ends in the planes of the tube's rings there. pub fn boxes(net: &Net, e: usize) -> Vec<[f64; BOX]> { let Some((c0, _)) = net.opening(e) else { return Vec::new() }; let (end, design, bake) = (&net.ends[e], &net.rules.design, &net.rules.ladder.bake); @@ -207,20 +207,10 @@ pub fn boxes(net: &Net, e: usize) -> Vec<[f64; BOX]> { let sp = spring(net, first.section, first.height); let (roof, spring_at) = roof_of(front.z, first.height, sp, first.section, design.frame_m + wall); let (half, rise) = (first.half + design.frame_m + wall, (ring.z - front.z) / design.recess_m); - let mut out = vec![[ - front.x, - front.y, - into[0], - into[1], - design.recess_m, - half, - roof, - front.z + lift, - rise, - spring_at, - 0.0, - 0.0, - ]]; + let opening = + [front.x, front.y, into[0], into[1], design.recess_m, half, roof, front.z + lift, rise, spring_at, 0.0, 0.0]; + // A closed end has no opening. + let mut out = if net.closed(e) { Vec::new() } else { vec![opening] }; // The axis from the frame line: per chord of the walk its far vertex, with the height and section that end there. let reach = reach(net, e).boxes; let mut axis = vec![Axis { p: end.at, z: end.z, ring }]; diff --git a/host/obc-trailview-parts/src/footprint.rs b/host/obc-trailview-parts/src/footprint.rs index 306191dc9..f76bfc1c5 100644 --- a/host/obc-trailview-parts/src/footprint.rs +++ b/host/obc-trailview-parts/src/footprint.rs @@ -1,15 +1,15 @@ //! The ring that a part takes from the ground. -use crate::arch::collar; +use crate::arch::{collar, wide}; use crate::tube::Net; -/// The ring of end e, in world units, in order round it: the head wall and its wings from front to back, and the -/// collar's shell along its chords out to `collar`. +/// The ring of end e, in world units, in order round it: its head from front to back (the head wall of both openings +/// of a pair), and the collar's shell along its chords out to `collar`. pub fn ring(net: &Net, e: usize) -> Vec<[f64; 2]> { let end = &net.ends[e]; let (design, bake) = (&net.rules.design, &net.rules.ladder.bake); let edge = end.half + bake.shell_m; - let (wide_r, wide_l) = (-(edge + end.right.len() as f64), edge + end.left.len() as f64); + let (wide_r, wide_l) = wide(net, e); let (front, back) = (net.frame(e, -design.recess_m), net.frame(e, design.face_m - design.recess_m)); let xy = |p: [f64; 3]| [p[0], p[1]]; let mut out = vec![xy(front.at([wide_r, 0.0])), xy(front.at([wide_l, 0.0])), xy(back.at([wide_l, 0.0]))]; diff --git a/host/obc-trailview-parts/src/lib.rs b/host/obc-trailview-parts/src/lib.rs index 8597d34b0..b9f47aa9c 100644 --- a/host/obc-trailview-parts/src/lib.rs +++ b/host/obc-trailview-parts/src/lib.rs @@ -50,7 +50,7 @@ impl Part { } /// The kinds of part that the builder makes. A chain draws as parts only where both of its ends are of these kinds. -pub const BUILT: &[Part] = &[Part::Arch, Part::Box]; +pub const BUILT: &[Part] = &[Part::Arch, Part::Pair, Part::Rock, Part::Box, Part::Free]; /// Whether all ends of a chain are built; `None` is an end with no part of its own. pub fn built(ends: &[Option]) -> bool { @@ -123,12 +123,20 @@ pub struct End { pub left: Vec, pub right: Vec, pub foot: f64, - /// The metres to the left from its axis to the other tube of a pair. - pub mate: Option, + /// The other tube of a pair. + pub mate: Option, pub way: [i64; 2], pub shift: f64, - pub mate_way: Option<[i64; 2]>, - pub mate_shift: Option, +} + +/// The other tube of a pair: the metres to the left from the end's axis to its axis, and its `way`, `shift` and +/// `collar`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mate { + pub across: f64, + pub way: [i64; 2], + pub shift: f64, + pub collar: f64, } impl End { @@ -156,11 +164,18 @@ impl End { left: if walls { row(tags, "left")? } else { Vec::new() }, right: if walls { row(tags, "right")? } else { Vec::new() }, foot: number(tags, "foot")?, - mate: pair.then(|| number(tags, "mate")).transpose()?, + mate: pair + .then(|| -> Result { + Ok(Mate { + across: number(tags, "mate")?, + way: vertex(tags, "mate_way")?, + shift: number(tags, "mate_shift")?, + collar: number(tags, "mate_collar")?, + }) + }) + .transpose()?, way: vertex(tags, "way")?, shift: number(tags, "shift")?, - mate_way: pair.then(|| vertex(tags, "mate_way")).transpose()?, - mate_shift: pair.then(|| number(tags, "mate_shift")).transpose()?, }) } @@ -251,9 +266,9 @@ fn near(square: [f64; 4], points: &[[f64; 2]], reach: f64) -> bool { /// The faces of the parts that a square draws: of each built end whose point it holds, and of each chord of a built /// chain whose `a` it holds, so each face draws in one square. pub fn meshes(square: [f64; 4], ends: &[End], chords: &[Chord], rules: &Rules) -> Mesh { - let net = Net::new(ends, chords, rules); + let net = Net::new(ends, chords, rules).meeting(); let mut b = mesh::Builder::new(|p| net.daylight(p)); - for (e, end) in ends.iter().enumerate() { + for (e, end) in net.ends.iter().enumerate() { if net.built_end(e) && holds(square, end.at) { arch::faces(&mut b, &net, e); } @@ -272,7 +287,7 @@ pub fn volumes(ends: &[End], chords: &[Chord], rules: &Rules) -> Volumes { let net = Net::new(ends, chords, rules); let lift = rules.design.lift_m; let mut out = Volumes::default(); - for e in (0..ends.len()).filter(|&e| net.built_end(e)) { + for e in (0..net.ends.len()).filter(|&e| net.built_end(e)) { for words in boxes::boxes(&net, e) { out.boxes.extend(words); } @@ -302,15 +317,29 @@ pub fn near_volumes(square: [f64; 4], boxes: &[f64], floors: &[f64], rules: &Rul Volumes { boxes: boxes.flatten().copied().collect(), floors: floors.flatten().copied().collect() } } -/// Per end, whether it is built: its part and the chain of the chord at its opening are built. -pub fn built_ends(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec { +/// An opening of a built end, two of a pair: its point, its unit way into the tube and its inside half-width, and the +/// end vertex of its way and the metres along that way to it (`way`, `shift`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mouth { + pub at: [f64; 2], + pub into: [f64; 2], + pub half: f64, + pub way: [i64; 2], + pub shift: f64, +} + +/// The openings of the built ends. +pub fn mouths(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec { let net = Net::new(ends, chords, rules); - (0..ends.len()).map(|e| net.built_end(e)).collect() + (net.ends.iter().enumerate()) + .filter(|&(e, _)| net.built_end(e)) + .map(|(_, end)| Mouth { at: end.at, into: end.way_in(), half: end.half, way: end.way, shift: end.shift }) + .collect() } -/// Per built end, the ring that its part takes from the ground: round its head wall and wings, from front to back, +/// Per built end with an opening, the ring that its part takes from the ground: round its head, from front to back, /// and its collar. pub fn footprints(ends: &[End], chords: &[Chord], rules: &Rules) -> Vec> { let net = Net::new(ends, chords, rules); - (0..ends.len()).filter(|&e| net.built_end(e)).map(|e| footprint::ring(&net, e)).collect() + (0..net.ends.len()).filter(|&e| net.built_end(e) && !net.closed(e)).map(|e| footprint::ring(&net, e)).collect() } diff --git a/host/obc-trailview-parts/src/mesh.rs b/host/obc-trailview-parts/src/mesh.rs index 22ea90007..faec01fb2 100644 --- a/host/obc-trailview-parts/src/mesh.rs +++ b/host/obc-trailview-parts/src/mesh.rs @@ -1,6 +1,8 @@ //! Faces as the viewer's structure meshes hold them (`structures/mesh.ts`), and the stations and cross-sections that //! the parts sweep. +use std::collections::HashMap; + use crate::{metres_per_unit, Mesh, Section}; /// Words of a vertex: x, y (i32 world units), z (f32), colour and flags, across and half-width of a road face @@ -99,19 +101,69 @@ pub struct Paint { pub const PLAIN: Paint = Paint { across: 0.0, half: 0.0, sleepers: NO_SLEEPERS }; +/// A vertical plane through two world points in plan that takes off the faces on one side of it: the side of `away`, +/// a world direction. With a bound, only on the side of a second vertical plane: the plane through a world point square +/// to a world direction, on the side that the direction points to. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Clip { + pub a: [f64; 2], + pub b: [f64; 2], + pub away: [f64; 2], + pub bound: Option<([f64; 2], [f64; 2])>, +} + +impl Clip { + /// How far a world point lies outside the bound, in world units: negative where the clip holds. + fn outside(&self, p: [f64; 3]) -> f64 { + let Some((at, dir)) = self.bound else { return -1.0 }; + let l = libm::hypot(dir[0], dir[1]).max(f64::MIN_POSITIVE); + -((p[0] - at[0]) * dir[0] + (p[1] - at[1]) * dir[1]) / l + } + + /// How far a world point lies on the side that the plane takes off, in world units. + fn side(&self, p: [f64; 3]) -> f64 { + let n = [self.b[1] - self.a[1], self.a[0] - self.b[0]]; + let l = libm::hypot(n[0], n[1]).max(f64::MIN_POSITIVE); + let sign = if n[0] * self.away[0] + n[1] * self.away[1] >= 0.0 { 1.0 } else { -1.0 }; + sign * ((p[0] - self.a[0]) * n[0] + (p[1] - self.a[1]) * n[1]) / l + } +} + /// Collects faces. Each face is wound counter-clockwise seen from the side that `out` points to (east, north, up), -/// so the back faces cull. +/// so the back faces cull. The part of a face past the plane of a clip is not drawn. pub struct Builder f64> { words: Vec, indices: Vec, points: Vec<[f64; 3]>, + looks: Vec<(u32, Paint)>, daylight: L, + clips: Vec, + /// The vertex where the plane of clip k (one of at most four) cuts the edge between two vertices, by the lower + /// vertex and k, and the higher vertex. Its key and value have the types of `Net`'s map of openings, so the WASM + /// holds the code of one map of that type. + cuts: HashMap<(usize, usize), usize>, } impl f64> Builder { /// A builder whose vertices take their daylight from `daylight` of their world point. pub fn new(daylight: L) -> Self { - Builder { words: Vec::new(), indices: Vec::new(), points: Vec::new(), daylight } + Builder { + words: Vec::new(), + indices: Vec::new(), + points: Vec::new(), + looks: Vec::new(), + daylight, + clips: Vec::new(), + cuts: HashMap::new(), + } + } + + /// The clips of the faces from now on. + pub fn clip(&mut self, clips: Vec) { + debug_assert!(clips.len() <= 2, "a key of a cut vertex holds the planes of two clips"); + if clips != self.clips { + (self.clips, self.cuts) = (clips, HashMap::new()); + } } pub fn vertex(&mut self, p: [f64; 3], colour: u32, paint: Paint) -> u32 { @@ -127,9 +179,69 @@ impl f64> Builder { (light as f32).to_bits(), ]); self.points.push(p); + self.looks.push((colour, paint)); (self.points.len() - 1) as u32 } + /// The vertex where plane k cuts the edge from vertex i to j, which lie at `di` and `dj` past it. + fn cut(&mut self, k: usize, (i, di): (u32, f64), (j, dj): (u32, f64)) -> u32 { + let key = (i.min(j) as usize * 4 + k, i.max(j) as usize); + if let Some(&v) = self.cuts.get(&key) { + return v as u32; + } + let (u, p, q) = (di / (di - dj), self.points[i as usize], self.points[j as usize]); + let ((colour, a), z) = (self.looks[i as usize], self.looks[j as usize].1); + let mix = |a: f64, b: f64| a + (b - a) * u; + let paint = Paint { across: mix(a.across, z.across), half: a.half, sleepers: mix(a.sleepers, z.sleepers) }; + let v = self.vertex([mix(p[0], q[0]), mix(p[1], q[1]), mix(p[2], q[2])], colour, paint); + self.cuts.insert(key, v as usize); + v + } + + /// A convex polygon's parts on the near side of plane k and past it (more than a hundredth of a world unit), each + /// in the polygon's winding; where an edge crosses the plane, a vertex of both. + fn halves(&mut self, k: usize, poly: &[u32], past: impl Fn([f64; 3]) -> f64) -> (Vec, Vec) { + let d: Vec = poly.iter().map(|&v| past(self.points[v as usize]) - 0.01).collect(); + if d.iter().all(|&x| x <= 0.0) { + return (poly.to_vec(), Vec::new()); + } + if d.iter().all(|&x| x > 0.0) { + return (Vec::new(), poly.to_vec()); + } + let (mut near, mut far) = (Vec::with_capacity(poly.len() + 1), Vec::with_capacity(poly.len() + 1)); + for i in 0..poly.len() { + let j = (i + 1) % poly.len(); + if d[i] > 0.0 { &mut far } else { &mut near }.push(poly[i]); + if (d[i] > 0.0) != (d[j] > 0.0) { + let v = self.cut(k, (poly[i], d[i]), (poly[j], d[j])); + near.push(v); + far.push(v); + } + } + (near, far) + } + + /// A triangle in its winding, without its parts past the planes of the clips. Plane 2k is the cut of clip k, plane + /// 2k + 1 its bound; `clips` holds at most one clip per side, so a key of a cut vertex holds four planes. + fn emit(&mut self, t: [u32; 3]) { + let mut polys = vec![t.to_vec()]; + for k in 0..self.clips.len() { + let clip = self.clips[k]; + let mut next = Vec::with_capacity(polys.len() + 1); + for poly in polys { + let (held, free) = self.halves(2 * k + 1, &poly, |p| clip.outside(p)); + let (kept, _) = self.halves(2 * k, &held, |p| clip.side(p)); + next.extend([free, kept].into_iter().filter(|p| p.len() >= 3)); + } + polys = next; + } + for poly in polys { + for k in 1..poly.len() - 1 { + self.indices.extend([poly[0], poly[k], poly[k + 1]]); + } + } + } + pub fn at(&mut self, s: &Station, c: Corner, colour: u32) -> u32 { self.vertex(s.at(c), colour, PLAIN) } @@ -140,12 +252,13 @@ impl f64> Builder { if n.iter().all(|c| c.abs() < 1e-12) { return; } - let facing = n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0; - self.indices.extend(if facing { - [v[0], v[1], v[2], v[0], v[2], v[3]] + if n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0 { + self.emit([v[0], v[1], v[2]]); + self.emit([v[0], v[2], v[3]]); } else { - [v[0], v[2], v[1], v[0], v[3], v[2]] - }); + self.emit([v[0], v[2], v[1]]); + self.emit([v[0], v[3], v[2]]); + } } /// A triangle turned to face `out`. A triangle of no area makes no face. @@ -155,7 +268,7 @@ impl f64> Builder { return; } let facing = n[0] * out[0] + n[1] * out[1] + n[2] * out[2] >= 0.0; - self.indices.extend(if facing { [a, b, c] } else { [a, c, b] }); + self.emit(if facing { [a, b, c] } else { [a, c, b] }); } /// The faces between two polylines that run side by side from a common start to a common end: the corners `a` at @@ -192,8 +305,20 @@ impl f64> Builder { } } + /// The mesh of the faces, with the vertices that a face uses. pub fn mesh(self) -> Mesh { - Mesh { vertices: self.words, indices: self.indices } + let mut to = vec![u32::MAX; self.points.len()]; + let mut vertices = Vec::with_capacity(self.words.len()); + let indices = (self.indices.iter()) + .map(|&i| { + if to[i as usize] == u32::MAX { + to[i as usize] = (vertices.len() / WORDS) as u32; + vertices.extend_from_slice(&self.words[i as usize * WORDS..(i as usize + 1) * WORDS]); + } + to[i as usize] + }) + .collect(); + Mesh { vertices, indices } } /// The normal of a, b, c, d by their diagonals, in metres east, north and up. diff --git a/host/obc-trailview-parts/src/tests.rs b/host/obc-trailview-parts/src/tests.rs index 6844ba61c..ee393eb8a 100644 --- a/host/obc-trailview-parts/src/tests.rs +++ b/host/obc-trailview-parts/src/tests.rs @@ -149,7 +149,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { // Within the rounding of a box's words and of a sample: a millimetre. let tol = 1e-3; let (mut room, mut solid) = (0, 0); - for e in (0..ends.len()).filter(|&e| net.built_end(e)) { + for e in (0..net.ends.len()).filter(|&e| net.built_end(e)) { let list = boxes::boxes(&net, e); let small: Vec<[f64; BOX]> = list.iter().map(|b| shrunk(b, MARGIN_M)).collect(); let held = |boxes: &[[f64; BOX]], p: [f64; 3]| { @@ -161,7 +161,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { let first = &net.chords[c0]; let sp = tube::spring(&net, first.section, first.height); // The room: the opening's hole from the front of the head wall to the frame line. - for k in 0..=4 { + for k in (0..=4).filter(|_| !net.closed(e)) { let st = net.frame(e, -design.recess_m * (1.0 - k as f64 / 4.0)); for a in [-1.0, -0.5, 0.0, 0.5, 1.0] { let hw = first.half + design.frame_m; @@ -210,7 +210,7 @@ fn boxes_fit(name: &str, ends: &[End], chords: &[Chord]) -> (usize, usize) { } // Each box of the tube, grown by the margin: points of its sides, its floor and its roof, at shares 0 to 1 // between its end planes, inside the drawn shell. - let m = metres_per_unit(ends[e].at[1]); + let m = metres_per_unit(net.ends[e].at[1]); for (i, b) in list.iter().enumerate().skip(1) { let lu = mesh::left_of([b[2], b[3]]); let (depth, half, roof, floor, spring) = (b[4], b[5] + MARGIN_M, b[6] + MARGIN_M, b[7], b[9]); @@ -473,14 +473,15 @@ fn open_edges(mesh: &Mesh) -> (Edges, Edges) { fn not_closed(ends: &[End], chords: &[Chord]) -> (Edges, Edges) { let rules = Rules::embedded(); let net = Net::new(ends, chords, rules); - let feet: Vec = (0..ends.len()).filter(|&e| net.built_end(e)).map(|e| boxes::foot(&net, e)).collect(); - // Per end whose shell a face closes, the station of that face. - let faces: Vec = (0..ends.len()) - .filter(|&e| net.built_end(e)) + let built = || (0..net.ends.len()).filter(|&e| net.built_end(e)); + let feet: Vec = built().map(|e| boxes::foot(&net, e)).collect(); + // Per end whose shell a face closes, the station of that face; and the front of a closed end. + let faces: Vec = (built()) .filter_map(|e| { let r = boxes::reach(&net, e); arch::collar(&net, e, r.shell).last().filter(|_| r.closed).map(|p| p.1) }) + .chain(built().filter(|&e| net.closed(e)).map(|e| net.frame(e, 0.0))) .collect(); // Within the rounding of a vertex to whole world units. let at_foot = |p: [f64; 3]| feet.iter().any(|f| (p[2] - f).abs() < 1e-3); @@ -648,3 +649,325 @@ fn the_faces_along_a_tube_face_out_of_its_shell_and_into_its_room() { assert!(out > 20 && inside > 20, "{name}: {out} faces of the shell, {inside} inside"); } } + +/// A tube as one of `part` at both ends, of a way of `class`. +fn kind((mut ends, mut chords): (Vec, Vec), part: Part, class: &str) -> (Vec, Vec) { + for e in &mut ends { + e.part = part; + } + for c in &mut chords { + (c.ends, c.class) = ([Some(part); 2], class.into()); + } + (ends, chords) +} + +/// Two road tubes 40 m east from a pair at each end: the first on the line 0 m north, the second `apart` metres north +/// with its floor `dz` higher; each of two chords. +fn pair(apart: f64, dz: f64) -> (Vec, Vec) { + let pi = std::f64::consts::PI; + let mut ends = vec![end(0.0, 0.0, 500.0, 0.0, 6.0), end(40.0, 0.0, 500.2, pi, 3.0)]; + // Into the tubes from the west the second lies to the left, from the east to the right. + for (e, mate) in ends.iter_mut().zip([apart, -apart]) { + e.part = Part::Pair; + e.mate = Some(Mate { across: mate, way: [1, 1], shift: 0.0, collar: e.collar }); + } + let mut chords = [lane(0.0, 500.0), lane(apart, 500.0 + dz)].concat(); + chords.iter_mut().for_each(|c| c.ends = [Some(Part::Pair); 2]); + (ends, chords) +} + +/// The two chords of a road tube 40 m east on the line `north` metres north, its floor from z rising 0.5 %. +fn lane(north: f64, z: f64) -> Vec { + [(0.0, 20.0), (20.0, 40.0)] + .map(|(a, b)| chord([a, north, z + a * 0.005], [b, north, z + b * 0.005], 5.0, a)) + .to_vec() +} + +/// Road tubes as those of `pair`, on the lines `norths` metres north, with an arch at each end: no end has a mate. +fn row(norths: &[f64]) -> (Vec, Vec) { + let (mut ends, mut chords) = (Vec::new(), Vec::new()); + for &north in norths { + ends.extend([end(0.0, north, 500.0, 0.0, 6.0), end(40.0, north, 500.2, std::f64::consts::PI, 3.0)]); + chords.extend(lane(north, 500.0)); + } + for e in &mut ends { + e.part = Part::Arch; + } + for c in &mut chords { + c.ends = [Some(Part::Arch); 2]; + } + (ends, chords) +} + +/// The triangles of a mesh in metres east, north and up, but the dark faces of the openings and the lamps. +fn solid(mesh: &Mesh) -> Vec<[[f64; 3]; 3]> { + let point = |i: u32| { + let w = &mesh.vertices[i as usize * WORDS..]; + let p = metric([w[0] as i32 as f64, w[1] as i32 as f64]); + [p[0], p[1], f32::from_bits(w[2]) as f64] + }; + let shown = |i: u32| (mesh.vertices[i as usize * WORDS + 3] >> 24) & (mesh::VOID | mesh::LAMP) == 0; + mesh.indices.chunks(3).filter(|t| shown(t[0])).map(|t| [point(t[0]), point(t[1]), point(t[2])]).collect() +} + +/// The first face that a ray from `o` along `d` meets within `far` metres: its distance, and whether the ray meets its +/// front, or the front of a face at the same distance (two faces back to back). +fn hit(faces: &[[[f64; 3]; 3]], o: [f64; 3], d: [f64; 3], far: f64) -> Option<(f64, bool)> { + let sub = |a: [f64; 3], b: [f64; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + let cross = + |a: [f64; 3], b: [f64; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let mut best: Option<(f64, bool)> = None; + for [a, b, c] in faces { + let (e1, e2) = (sub(*b, *a), sub(*c, *a)); + let p = cross(d, e2); + let det = dot(e1, p); + if det.abs() < 1e-12 { + continue; + } + let tv = sub(o, *a); + let (u, q) = (dot(tv, p) / det, cross(tv, e1)); + let (v, t) = (dot(d, q) / det, dot(e2, q) / det); + if u < -1e-9 || v < -1e-9 || u + v > 1.0 + 1e-9 || t <= 1e-6 || t > far { + continue; + } + let front = dot(cross(e1, e2), d) < 0.0; + best = match best { + Some(b) if (t - b.0).abs() < 1e-6 => Some((b.0, b.1 || front)), + Some(b) if b.0 < t => Some(b), + _ => Some((t, front)), + }; + } + best +} + +#[test] +fn the_tubes_of_a_pair_or_side_by_side_are_one_room_and_their_heads_end_between() { + let rules = Rules::embedded(); + let frame = rules.design.frame_m; + // Tubes 7 m apart, 4.5 m wide each: their rooms overlap by 2 m, so they are cut in the middle; with the second's + // floor 0.8 m higher, faces close the steps there. Tubes 10.5 m apart do not overlap. Arches that are no pair end + // their head walls at the middle too, the middle tube of three on both sides. + let cases: [(&[f64], f64, bool); 5] = [ + (&[0.0, 7.0], 0.0, true), + (&[0.0, 7.0], 0.8, true), + (&[0.0, 10.5], 0.0, true), + (&[0.0, 10.5], 0.0, false), + (&[0.0, 7.0, 14.0], 0.0, false), + ]; + for (norths, dz, paired) in cases { + let name = format!("tubes at {norths:?} m north, the second {dz} m higher, a pair: {paired}"); + let (ends, chords) = if paired { pair(norths[1], dz) } else { row(norths) }; + let (room, box_points) = boxes_fit(&name, &ends, &chords); + assert!(room > 200 && box_points > 100, "{name}: {room} room samples, {box_points} box samples"); + let mesh = meshes([0.0, 0.0, 1.07e9, 1.07e9], &ends, &chords, rules); + let faces = solid(&mesh); + let o = tube::outline_of(&Net::new(&ends, &chords, rules), 0); + // A point's tube, the nearest; and its floor at the opening. + let of = |north: f64| { + let i = (0..norths.len()).min_by(|&i, &j| (north - norths[i]).abs().total_cmp(&(north - norths[j]).abs())); + let i = i.unwrap(); + (norths[i], if i == 1 { 500.0 + dz } else { 500.0 }) + }; + let middles: Vec = norths.windows(2).map(|w| (w[0] + w[1]) / 2.0).collect(); + // Each tube's room up to the middles: no face lies in it. A face in a middle lies within the rounding of its + // vertices to world units. + let inside = |p: [f64; 3]| { + let (axis, z) = of(p[1]); + let (x, up) = (p[1] - axis, p[2] - z - p[0] * 0.005); + middles.iter().all(|m| (p[1] - m).abs() >= 0.05) + && p[0] > 0.5 + && p[0] < 39.5 + && x.abs() < 4.45 + && up > 0.25 + && tube::top_at(&o, x).is_some_and(|t| up < t - 0.05) + }; + for f in &faces { + let c = [0, 1, 2].map(|k| (f[0][k] + f[1][k] + f[2][k]) / 3.0); + assert!(!inside(c), "{name}: a face in the room at {c:?}"); + } + // From inside the room, every way across meets the front of a face: the room is closed at the middles. + let (first, last) = (norths[0], norths[norths.len() - 1]); + let mut from = vec![(first - 3.0, 1.0), (last + 3.0, 1.0)]; + for &n in norths { + from.extend([(n - 2.5, 4.0), (n, 2.5), (n + 2.5, 4.0)]); + } + for (north, up) in from { + let z = of(north).1; + for k in 0..24 { + let a = (k as f64 * 15.0 + 7.0).to_radians(); + let d = [0.0, libm::cos(a), libm::sin(a)]; + let got = hit(&faces, [20.0, north, z + 0.1 + up], d, 30.0); + assert!(got.is_some_and(|h| h.1), "{name}: from {north} m north, {up} m up, at {a} rad: {got:?}"); + } + } + // One head wall: in front of the frame line, a ray east meets its front between two holes, but none in a hole; + // where the holes overlap, they are one opening. + for &north in &middles { + let got = hit(&faces, [-3.0, north, 501.0], [1.0, 0.0, 0.0], 10.0); + if norths[1] - norths[0] < 2.0 * (4.5 + frame) { + assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the middle of one opening: {got:?}"); + } else { + assert!(got.is_some_and(|h| h.1 && h.0 < 3.0), "{name}: the head wall between the holes: {got:?}"); + } + } + for &north in norths { + let got = hit(&faces, [-3.0, north, 502.5], [1.0, 0.0, 0.0], 10.0); + assert!(got.is_none_or(|h| h.0 > 3.5), "{name}: the hole at {north} m north: {got:?}"); + } + } +} + +#[test] +fn a_rim_hugs_its_opening_and_a_covered_free_end_is_closed() { + let rules = Rules::embedded(); + let d = &rules.design; + let (shell, frame) = (rules.ladder.bake.shell_m, d.frame_m); + // An opening in the rock and a free tube end: the head is a rim round the opening, 0.95 m wide, with no wings. + for (name, (ends, chords)) in [ + ("rock", kind(bent(30.0, 20.0), Part::Rock, "footway")), + ("free", kind(tube(), Part::Free, "primary")), + ("closed", kind(tube(), Part::Free, "primary")), + ] { + let mut ends = ends; + if name == "closed" { + ends[0].collar = 0.0; + } + let (room, box_points) = boxes_fit(name, &ends, &chords); + assert!(room > 100 && box_points > 50, "{name}: {room} room samples, {box_points} box samples"); + let (open, crowded) = not_closed(&ends, &chords); + assert!(open.is_empty(), "{name}: {} open edges, the first {:?}", open.len(), &open[..open.len().min(4)]); + assert!( + crowded.is_empty(), + "{name}: {} crowded edges, the first {:?}", + crowded.len(), + &crowded[..crowded.len().min(4)] + ); + let net = Net::new(&ends, &chords, rules); + let ring = footprints(&ends, &chords, rules); + let (at, st) = (ends[0].at, net.frame(0, 0.0)); + let (l, m) = (mesh::left_of(ends[0].way_in()), metres_per_unit(at[1])); + let across = |p: [f64; 2]| ((p[0] - at[0]) * l[0] + (p[1] - at[1]) * l[1]) * m; + if name == "closed" { + // No opening: its first box starts on the frame line, no daylight comes from it, and it has no ring. + assert_eq!(boxes::boxes(&net, 0)[0][..2], at); + assert_eq!(net.daylight(st.at([0.0, 2.0])), 0.0); + assert_eq!(ring.len(), 1); + } else { + // The ring's head: from the front's right end to its left end and back, then the back's right end. + let head = [ring[0][0], ring[0][1], ring[0][2], ring[0][ring[0].len() - 1]]; + let wide = head.iter().map(|&p| across(p).abs()).fold(0.0, f64::max); + let half = 4.5; + assert!(wide <= half + frame + shell + 1e-6, "{name}: the ring reaches {wide} m across"); + } + } +} + +/// Arches at both ends of road tubes along polylines of metres east and north at the floor 500 m: an end at the first +/// vertex leads along the first chord, one at the last vertex back along the last. +fn tubes(lines: &[&[[f64; 2]]]) -> (Vec, Vec) { + let (mut ends, mut chords) = (Vec::new(), Vec::new()); + for line in lines { + let n = line.len(); + let heading = |a: [f64; 2], b: [f64; 2]| libm::atan2(-(b[1] - a[1]), b[0] - a[0]); + ends.push(end(line[0][0], line[0][1], 500.0, heading(line[0], line[1]), 6.0)); + ends.push(end(line[n - 1][0], line[n - 1][1], 500.0, heading(line[n - 1], line[n - 2]), 6.0)); + let mut along = 0.0; + for w in line.windows(2) { + chords.push(chord([w[0][0], w[0][1], 500.0], [w[1][0], w[1][1], 500.0], 5.0, along)); + along += libm::hypot(w[1][0] - w[0][0], w[1][1] - w[0][1]); + } + } + (ends, chords) +} + +#[test] +fn two_tubes_meet_only_where_both_are_and_a_cut_head_is_closed() { + let rules = Rules::embedded(); + let faces_of = + |(ends, chords): &(Vec, Vec)| solid(&meshes([0.0, 0.0, 1.07e9, 1.07e9], ends, chords, rules)); + let north = [0.0, 1.0, 0.0]; + // Staggered openings: a tube 7 m north starts 3 m after the first, so their rooms overlap from there on. Before + // it, the first tube keeps its wall; after it, a way north meets the second's far wall; a way west in the first's + // wall, from the second's room, meets the face that closes the first's shell where its cut begins. + let staggered = tubes(&[&[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], &[[3.0, 7.0], [10.0, 7.0], [40.0, 7.0]]]); + let faces = faces_of(&staggered); + for east in [0.5, 1.5, 2.5, 2.95] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "staggered, {east} m east: {got:?}"); + } + for east in [5.0, 15.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 > 11.0), "staggered, {east} m east: {got:?}"); + } + for up in [1.0, 2.0] { + let got = hit(&faces, [6.0, 4.7, 500.0 + up], [-1.0, 0.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 3.2), "staggered, the first's shell {up} m up: {got:?}"); + } + // A tube beside the first for 20 m that turns away north: past the turn, the first keeps its wall. + let away = tubes(&[&[[0.0, 0.0], [100.0, 0.0]], &[[0.0, 7.0], [20.0, 7.0], [50.0, 40.0]]]); + let faces = faces_of(&away); + for east in [30.0, 60.0, 90.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 5.1), "turns away, {east} m east: {got:?}"); + } + assert!(hit(&faces, [10.0, 0.0, 502.5], north, 30.0).is_some_and(|h| h.1 && h.0 > 11.0), "turns away, 10 m east"); + // A path tube whose axis lies 3 m from a road tube's, in the road's room: the middle lies past the path's axis. A + // way up from either room meets a vault, and a way north from the path's axis meets its far wall. + let mut inner = tubes(&[&[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], &[[0.0, 3.0], [10.0, 3.0], [40.0, 3.0]]]); + for e in &mut inner.0[2..] { + (e.half, e.height) = (0.9, 2.6); + } + for c in &mut inner.1[2..] { + (c.half, c.height) = (0.9, 2.6); + } + let faces = faces_of(&inner); + for east in [2.0, 10.0, 30.0] { + for y in [-2.0, 0.0, 2.0, 3.0] { + let p = [east, y, 501.0]; + assert!(hit(&faces, p, [0.0, 0.0, 1.0], 30.0).is_some_and(|h| h.1), "a path in a road's room: up at {p:?}"); + } + let got = hit(&faces, [east, 3.0, 501.0], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 < 1.0), "a path in a road's room: north at {east} m: {got:?}"); + } + // A pair whose tubes run 25 degrees apart from one frame line, their rooms overlapping there: both find one plane, + // so a way north from the first meets the second's far wall, and a way up anywhere between their axes meets a + // vault. + let t = libm::tan(25f64.to_radians()); + let mut angled = tubes(&[ + &[[0.0, 0.0], [10.0, 0.0], [40.0, 0.0]], + &[[0.0, 7.0], [10.0, 7.0 + 10.0 * t], [40.0, 7.0 + 40.0 * t]], + ]); + angled.0.remove(2); + angled.0[0].part = Part::Pair; + angled.0[0].mate = Some(Mate { across: 7.0, way: [1, 1], shift: 0.0, collar: 6.0 }); + angled.1.iter_mut().for_each(|c| c.ends = [Some(Part::Pair), Some(Part::Arch)]); + let faces = faces_of(&angled); + for east in [1.0, 2.0, 3.0] { + let got = hit(&faces, [east, 0.0, 502.5], north, 30.0); + assert!(got.is_some_and(|h| h.1 && h.0 > 11.0), "angled, {east} m east: {got:?}"); + for k in 0..=20 { + let p = [east, 2.0 + 0.2 * f64::from(k), 500.5]; + assert!(hit(&faces, p, [0.0, 0.0, 1.0], 30.0).is_some_and(|h| h.1), "angled: a way up at {p:?}"); + } + } + // Two arches on one frame line, the first's head wall 2 m taller: over the lower wall, a way to the taller one + // meets the face that closes it at the middle. + let mut taller = row(&[0.0, 7.0]); + taller.0[0].face = 9.1; + let faces = faces_of(&taller); + for up in [7.6, 8.6] { + let got = hit(&faces, [0.15, 7.0, 500.0 + up], [0.0, -1.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "taller, {up} m up: {got:?}"); + } + // Two arches whose frame lines lie 3 m apart: the first's tube crosses the second's line, and the second's approach + // the first's, so both heads end at the middle, closed: a way over the first's tube meets the second's head, a way + // in the second's approach meets the first's head, both at the middle; the way into the second meets no face. + let faces = faces_of(&staggered); + let got = hit(&faces, [3.15, 0.0, 506.2], north, 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "frame lines apart, the second's head: {got:?}"); + let got = hit(&faces, [0.15, 7.0, 506.2], [0.0, -1.0, 0.0], 30.0); + assert!(got.is_some_and(|h| h.1 && (h.0 - 3.5).abs() < 0.2), "frame lines apart, the first's head: {got:?}"); + let got = hit(&faces, [-5.0, 7.0, 502.0], [1.0, 0.0, 0.0], 30.0); + assert!(got.is_none(), "frame lines apart, the way into the second: {got:?}"); +} diff --git a/host/obc-trailview-parts/src/tube.rs b/host/obc-trailview-parts/src/tube.rs index 6133d040b..6f0a10967 100644 --- a/host/obc-trailview-parts/src/tube.rs +++ b/host/obc-trailview-parts/src/tube.rs @@ -3,8 +3,8 @@ use std::collections::HashMap; -use crate::mesh::{flagged, flat, left_of, outline, Builder, Corner, Paint, Station, BORE, LAMP, PAINT}; -use crate::{built, metres_per_unit, Bore, Chord, End, Rules, Section}; +use crate::mesh::{flagged, flat, left_of, outline, Builder, Clip, Corner, Paint, Station, BORE, LAMP, PAINT}; +use crate::{built, metres_per_unit, Bore, Chord, End, Mate, Part, Rules, Section}; /// An end's point lies within this of the vertex of its tube's chord. const END_M: f64 = 0.5; @@ -35,9 +35,12 @@ pub fn direction(c: &Chord) -> ([f64; 2], f64) { /// The chords of a tile by their vertices, and per end the chord vertex at its opening. pub struct Net<'a> { - pub ends: &'a [End], + /// The ends of the input, then per pair an end at the opening of its mate. + pub ends: Vec, pub chords: &'a [Chord], pub rules: &'a Rules, + /// Per end, the other end of its pair. + pub mate: Vec>, at: HashMap<[u64; 2], Vec>, /// Per end, the chord and vertex at its opening, where its chain is built. opening: Vec>, @@ -45,36 +48,132 @@ pub struct Net<'a> { end_at: HashMap<(usize, usize), usize>, /// Per end, the rise of its floor per metre in, over its first `face_m`. slope: Vec, + /// Per chord, its tube: the chords that its vertices join; made by `meeting`. + tube: Vec, + /// The built chords by the cells (`CELL_M`) that they come within reach of; a cell's key is its two indices' bits, + /// so the WASM holds the code of one map of that type. Made by `meeting`. + cells: HashMap<[u64; 2], Vec>, + /// The world units of a cell. + cell: f64, } +/// Where a station across chord c meets another tube (`Net::meets`), on one side: the metres across the station to +/// the middle between their walls and to the other's axis on its line, the other's chord, and the other's floor (a +/// world height) and its metres across from its axis at that middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Cut { + pub x: f64, + pub axis: f64, + pub other: usize, + pub floor: f64, + pub across: f64, +} + +/// Where a piece of a tube meets another tube on one side: the clip that takes off the other's side, the stations +/// that bound the stretch where both meet with their cuts, and the station where the clip ends inside the piece. +#[derive(Clone, Copy, Debug)] +pub struct Meeting { + pub clip: Clip, + pub from: (Station, Cut), + pub to: (Station, Cut), + pub end: Option, +} + +/// How a part looks for other tubes from a station's line (`Net::meets`): the metres across to each side (to the right, +/// to the left); the metres past the planes of the other's rings, and on from a ring at an opening along the line of +/// its approach; and the heights over the station's floor that the part's faces span, or None for a room. +#[derive(Clone, Copy, Debug)] +pub struct Meet { + pub across: [f64; 2], + pub past: f64, + pub approach: f64, + pub up: Option<[f64; 2]>, +} + +/// The side of a cell of `Net::cells`, in metres. +const CELL_M: f64 = 16.0; +/// Two tubes that meet at a cut each run this far past it: two world units, as each vertex is rounded to one. +pub const OVERLAP_M: f64 = 0.05; +/// A station meets a tube this far past the planes of its rings: the two openings of a pair lie on one frame line within +/// the rounding of their record. +pub const MEET_PAST_M: f64 = 0.1; +/// Halvings of a piece to find where another tube starts or ends on it: to a millimetre of a 10 m chord. +const MEET_HALVES: usize = 14; + impl<'a> Net<'a> { - pub fn new(ends: &'a [End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { + pub fn new(inputs: &[End], chords: &'a [Chord], rules: &'a Rules) -> Net<'a> { let mut at: HashMap<[u64; 2], Vec> = HashMap::new(); for (c, chord) in chords.iter().enumerate() { for k in 0..2 { at.entry(key(vertex(chord, k))).or_default().push(c); } } - let mut opening = vec![None; ends.len()]; - let mut end_at = HashMap::new(); - for (e, end) in ends.iter().enumerate() { - let m = metres_per_unit(end.at[1]); + // The chord vertex nearest a point, within `END_M`. + let nearest = |p: [f64; 2]| { + let m = metres_per_unit(p[1]); let gap = |c: usize, k: usize| { let v = vertex(&chords[c], k); - libm::hypot(v[0] - end.at[0], v[1] - end.at[1]) * m + libm::hypot(v[0] - p[0], v[1] - p[1]) * m }; - let nearest = + let near = (0..chords.len()).flat_map(|c| [(c, 0), (c, 1)]).min_by(|x, y| gap(x.0, x.1).total_cmp(&gap(y.0, y.1))); - if let Some((c, k)) = nearest.filter(|&(c, k)| gap(c, k) <= END_M) { - if built(&[Some(end.part)]) && built(&chords[c].ends) { - opening[e] = Some((c, k)); - end_at.insert((c, k), e); - } + near.filter(|&(c, k)| gap(c, k) <= END_M) + }; + let mut ends = inputs.to_vec(); + let mut mate = vec![None; ends.len()]; + for (e, end) in inputs.iter().enumerate() { + let Some(other) = end.mate.filter(|_| end.part == Part::Pair) else { continue }; + let (l, m) = (left_of(end.way_in()), metres_per_unit(end.at[1])); + let p = [end.at[0] + l[0] * other.across / m, end.at[1] + l[1] * other.across / m]; + let Some((c, k)) = nearest(p) else { continue }; + let (chord, z) = (&chords[c], vertex(&chords[c], k)[2]); + mate[e] = Some(ends.len()); + mate.push(Some(e)); + // Its numbers over its own floor. + let up = |v: f64| v + end.z - z; + ends.push(End { + at: p, + z, + section: chord.section, + half: chord.half, + height: chord.height, + face: up(end.face), + left: end.left.iter().map(|&v| up(v)).collect(), + right: end.right.iter().map(|&v| up(v)).collect(), + foot: up(end.foot), + collar: other.collar, + mate: Some(Mate { across: -other.across, way: end.way, shift: end.shift, collar: end.collar }), + way: other.way, + shift: other.shift, + ..end.clone() + }); + } + let mut opening: Vec> = (ends.iter()) + .map(|end| nearest(end.at).filter(|&(c, _)| built(&[Some(end.part)]) && built(&chords[c].ends))) + .collect(); + // A pair is built where both of its openings are. + for e in 0..ends.len() { + if mate[e].is_some_and(|m| opening[m].is_none()) || (ends[e].part == Part::Pair && mate[e].is_none()) { + opening[e] = None; } } - let mut net = Net { ends, chords, rules, at, opening, end_at, slope: vec![0.0; ends.len()] }; + let end_at = (0..ends.len()).filter_map(|e| opening[e].map(|o| (o, e))).collect(); + let n = ends.len(); + let mut net = Net { + ends, + chords, + rules, + mate, + at, + opening, + end_at, + slope: vec![0.0; n], + tube: Vec::new(), + cells: HashMap::new(), + cell: 1.0, + }; let run = rules.design.face_m; - net.slope = (0..ends.len()).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - ends[e].z) / s)).collect(); + net.slope = (0..n).map(|e| net.floor_at(e, run).map_or(0.0, |(s, z)| (z - net.ends[e].z) / s)).collect(); net } @@ -190,33 +289,31 @@ impl<'a> Net<'a> { out } - /// The share of daylight at a world point: over the openings whose section over the tube's floor, grown by the shell - /// and a metre to each side, holds the point from the front of the head wall to `daylight_m` in, `1 − smoothstep(0, daylight_m, - /// m)` of the metres m in from the frame line, the largest; 0 with none. + /// The share of daylight at a world point: over the openings (not the closed ends) whose section over the tube's + /// floor, grown by the shell and a metre to each side, holds the point from the front of the head wall to + /// `daylight_m` in, `1 − smoothstep(0, daylight_m, m)` of the metres m in from the frame line, the largest; 0 with + /// none. pub fn daylight(&self, p: [f64; 3]) -> f64 { let (shell, reach, front) = (self.rules.ladder.bake.shell_m, self.rules.design.daylight_m, self.rules.design.recess_m); let mut most: f64 = 0.0; - for (e, end) in self.ends.iter().enumerate() { + for (e, end) in self.ends.iter().enumerate().filter(|&(e, _)| !self.closed(e)) { let (d, m) = (end.way_in(), metres_per_unit(end.at[1])); let l = left_of(d); - let mates = [Some(0.0), end.mate]; - for q in mates.iter().flatten().map(|a| [end.at[0] + l[0] * a / m, end.at[1] + l[1] * a / m]) { - let (dx, dy) = (p[0] - q[0], p[1] - q[1]); - let (along, beside) = ((dx * d[0] + dy * d[1]) * m, (dx * l[0] + dy * l[1]) * m); - if beside.abs() > end.half + shell + 1.0 || along < -front || along > reach { - continue; - } - // Over the tube's floor at that metre; in front of the frame line, over the frame's. - let floor = if along > 0.0 { - self.floor_at(e, along).map_or(end.z, |f| f.1) - } else { - end.z + self.slope[e] * along - }; - if (end.foot..=end.height + shell).contains(&(p[2] - floor)) { - let t = (along / reach).clamp(0.0, 1.0); - most = most.max(1.0 - t * t * (3.0 - 2.0 * t)); - } + let (dx, dy) = (p[0] - end.at[0], p[1] - end.at[1]); + let (along, beside) = ((dx * d[0] + dy * d[1]) * m, (dx * l[0] + dy * l[1]) * m); + if beside.abs() > end.half + shell + 1.0 || along < -front || along > reach { + continue; + } + // Over the tube's floor at that metre; in front of the frame line, over the frame's. + let floor = if along > 0.0 { + self.floor_at(e, along).map_or(end.z, |f| f.1) + } else { + end.z + self.slope[e] * along + }; + if (end.foot..=end.height + shell).contains(&(p[2] - floor)) { + let t = (along / reach).clamp(0.0, 1.0); + most = most.max(1.0 - t * t * (3.0 - 2.0 * t)); } } most @@ -240,6 +337,196 @@ impl<'a> Net<'a> { pub fn opening(&self, e: usize) -> Option<(usize, usize)> { self.opening[e] } + + /// Whether end e is a free end covered at its opening: its tube ends in the hill there, with no opening. + pub fn closed(&self, e: usize) -> bool { + self.ends[e].part == Part::Free && self.ends[e].collar <= 0.0 + } + + /// The same net, ready for `meets`: the tube of each chord (one walk over the vertices, a union of the chords at + /// each) and the cells of the built chords. + pub fn meeting(mut self) -> Self { + let n = self.chords.len(); + let mut parent: Vec = (0..n).collect(); + let root = |p: &mut Vec, mut i: usize| { + while p[i] != i { + p[i] = p[p[i]]; + i = p[i]; + } + i + }; + for list in self.at.values() { + let r = root(&mut parent, list[0]); + for &c in &list[1..] { + let o = root(&mut parent, c); + if o != r { + parent[o] = r; + } + } + } + self.tube = (0..n).map(|i| root(&mut parent, i)).collect(); + // The cells of the built chords, each grown by the farthest reach of a tube's cut. + let Some(first) = self.chords.first() else { return self }; + let m = metres_per_unit(first.a[1]); + self.cell = CELL_M / m; + let shell = self.rules.ladder.bake.shell_m; + let reach = 2.0 * self.chords.iter().map(|c| c.half + shell).fold(0.0, f64::max) / m; + let cell = self.cell; + let at = |v: f64| libm::floor(v / cell) as i64; + for (c, chord) in self.chords.iter().enumerate().filter(|&(_, ch)| built(&ch.ends)) { + let lo = [chord.a[0].min(chord.b[0]) - reach, chord.a[1].min(chord.b[1]) - reach]; + let hi = [chord.a[0].max(chord.b[0]) + reach, chord.a[1].max(chord.b[1]) + reach]; + for x in at(lo[0])..=at(hi[0]) { + for y in at(lo[1])..=at(hi[1]) { + self.cells.entry([x as u64, y as u64]).or_default().push(c); + } + } + } + self + } + + /// Where the line of a station across chord c meets another built tube, on each side (to the right, to the left) + /// the nearest, as `meet` looks: where the other's chord crosses the line between the planes of its rings (or past + /// them), within the own part's metres across from its axis and the other's half and shell; where the other's room + /// overlaps the heights that the own faces span (a head), or where its floor lies within half their heights of the + /// station's (a room). The cut is at the middle between the two tubes' walls, measured square to each tube's own + /// chord, so both find one plane at any angle. A tube meets another for its inside and shell with the reach of its + /// shell; a head with the reach of its wall, and so where the other or the approach of its opening crosses its + /// frame line. Needs `meeting`. + pub fn meets(&self, c: usize, st: &Station, meet: Meet) -> [Option; 2] { + let reach = meet.across; + let (own, shell) = (&self.chords[c], self.rules.ladder.bake.shell_m); + let m = metres_per_unit(st.y); + let cell = |dx: i64, dy: i64| { + [(libm::floor(st.x / self.cell) as i64 + dx) as u64, (libm::floor(st.y / self.cell) as i64 + dy) as u64] + }; + // The cells round the station's, where a reach passes the cell's growth. + let ring = i64::from(reach.iter().fold(0.0f64, |r, &x| r.max(x)) > own.half + shell + 1e-9); + let mut seen: Vec = Vec::new(); + for dx in -ring..=ring { + for dy in -ring..=ring { + seen.extend( + self.cells.get(&cell(dx, dy)).into_iter().flatten().filter(|&&o| self.tube[o] != self.tube[c]), + ); + } + } + seen.sort_unstable(); + seen.dedup(); + let unit = |d: [f64; 2]| { + let l = libm::hypot(d[0], d[1]).max(f64::MIN_POSITIVE); + [d[0] / l, d[1] / l] + }; + let dot = |a: [f64; 2], b: [f64; 2]| a[0] * b[0] + a[1] * b[1]; + let (own_dir, line) = (unit([own.b[0] - own.a[0], own.b[1] - own.a[1]]), [st.ax, st.ay]); + let mut best: [Option; 2] = [None, None]; + for o in seen { + let other = &self.chords[o]; + // The station's line meets the chord: st + x·across = a + u·(b − a). + let (dx, dy) = (other.b[0] - other.a[0], other.b[1] - other.a[1]); + let det = dx * st.ay - st.ax * dy; + if det.abs() < 1e-12 { + continue; + } + let (px, py) = (other.a[0] - st.x, other.a[1] - st.y); + let (x, u) = ((dx * py - dy * px) / det, (st.ax * py - st.ay * px) / det); + let side = usize::from(x > 0.0); + let floor_at = |u: f64| other.a[2] + u.clamp(0.0, 1.0) * (other.b[2] - other.a[2]); + // The other tube runs between the planes of its two rings: at an opening its frame line, at a bend the mitre. + let o_dir = unit([dx, dy]); + let crossing = st.at([x, 0.0]); + let between = |k: usize, into: f64| { + let r = self.ring(o, k); + let n = unit([r.ay, -r.ax]); + let n = if dot(n, o_dir) * into >= 0.0 { n } else { [-n[0], -n[1]] }; + let on = if self.end_at.contains_key(&(o, k)) { meet.approach } else { 0.0 }; + dot([crossing[0] - r.x, crossing[1] - r.y], n) * m >= -(meet.past + on) + }; + let df = floor_at(u) - st.z; + let level = match meet.up { + Some([lo, hi]) => df < hi && df + other.height > lo, + None => df.abs() <= (own.height + other.height) / 2.0, + }; + if x.abs() > reach[side] + other.half + shell + || !level + || best[side].is_some_and(|b| b.axis.abs() <= x.abs()) + || !between(0, 1.0) + || !between(1, -1.0) + { + continue; + } + // Signed metres from each tube's axis toward the other: linear along the station's line. + let mut na = unit(left_of(own_dir)); + if dot(na, line) * x < 0.0 { + na = [-na[0], -na[1]]; + } + let mut nb = unit(left_of(o_dir)); + if dot(nb, [st.x - other.a[0], st.y - other.a[1]]) < 0.0 { + nb = [-nb[0], -nb[1]]; + } + let (a0, ka) = (dot([st.x - own.a[0], st.y - own.a[1]], na) * m, dot(line, na) * m); + let (b0, kb) = (dot([st.x - other.a[0], st.y - other.a[1]], nb) * m, dot(line, nb) * m); + if (ka - kb).abs() <= 1e-9 { + continue; + } + let middle = (b0 - a0 + own.half - other.half) / (ka - kb); + let p = [st.x + middle * st.ax, st.y + middle * st.ay]; + let len = libm::hypot(dx, dy).max(f64::MIN_POSITIVE); + let along = dot([p[0] - other.a[0], p[1] - other.a[1]], o_dir) / len; + let across = (b0 + kb * middle).abs(); + best[side] = Some(Cut { x: middle, axis: x, other: o, floor: floor_at(along), across }); + } + best + } + + /// Where station s and t across chord c meet another tube for its inside and shell (`meets` with the reach of its + /// shell): on each side, the clip that takes off the other's side between the two stations' cuts. Where only one + /// station meets it, the clip holds from that station to where the other tube starts or ends on the piece (found + /// by halves, with no metres past its rings), and no farther. + pub fn clips(&self, c: usize, (s, t): (&Station, &Station)) -> Vec { + let reach = self.chords[c].half + self.rules.ladder.bake.shell_m; + let at = |u: f64, side: usize, past: f64| { + let st = s.mix(t, u); + let meet = Meet { across: [reach; 2], past, approach: 0.0, up: None }; + self.meets(c, &st, meet)[side].map(|cut| (st, cut)) + }; + let mut out = Vec::new(); + for side in 0..2 { + let ends = (at(0.0, side, MEET_PAST_M), at(1.0, side, MEET_PAST_M)); + let (from, to, end) = match ends { + (Some(a), Some(z)) => (a, z, None), + (None, None) => continue, + (a, z) => { + // From the station that meets, halves to the last point that still meets. + let (mut lo, mut hi) = if a.is_some() { (0.0, 1.0) } else { (1.0, 0.0) }; + for _ in 0..MEET_HALVES { + let mid = (lo + hi) / 2.0; + if at(mid, side, 0.0).is_some() { + lo = mid; + } else { + hi = mid; + } + } + let Some(last) = at(lo, side, 0.0) else { continue }; + let first = a.or(z).expect("one station meets"); + if (lo - if a.is_some() { 0.0 } else { 1.0 }).abs() * direction(&self.chords[c]).1 < MEET_PAST_M { + continue; + } + (first, last, Some(last.0)) + } + }; + // Toward the other's side of the own axis: where a narrow tube lies in a wide one's room, the middle lies + // past the narrow one's axis. + let away = [from.0.ax * from.1.axis.signum(), from.0.ay * from.1.axis.signum()]; + // The two tubes overlap by `OVERLAP_M` at the plane, so the rounding of their vertices opens no gap there. + let l = libm::hypot(away[0], away[1]).max(f64::MIN_POSITIVE); + let d = OVERLAP_M / metres_per_unit(s.y) / l; + let shift = |p: [f64; 3]| [p[0] + away[0] * d, p[1] + away[1] * d]; + let (a, z) = (shift(from.0.at([from.1.x, 0.0])), shift(to.0.at([to.1.x, 0.0]))); + let bound = end.map(|e| ([e.x, e.y], [from.0.x - e.x, from.0.y - e.y])); + out.push(Meeting { clip: Clip { a, b: z, away, bound }, from, to, end }); + } + out + } } /// The floor of a tube across: per piece from the right, its metres across and the height of its top. A road or a @@ -291,6 +578,47 @@ pub fn inward(a: Corner, b: Corner, spring: f64) -> Corner { [-(a[0] + b[0]), -(a[1] + b[1] - 2.0 * spring)] } +/// The top of an outline at `x` across, the highest of its segments there; None outside it. +pub fn top_at(o: &[Corner], x: f64) -> Option { + let mut top: Option = None; + for w in o.windows(2) { + let (p, q) = (w[0], w[1]); + let (lo, hi) = (p[0].min(q[0]), p[0].max(q[0])); + if x < lo - 1e-9 || x > hi + 1e-9 { + continue; + } + let y = if hi - lo < 1e-12 { p[1].max(q[1]) } else { p[1] + (q[1] - p[1]) * (x - p[0]) / (q[0] - p[0]) }; + top = Some(top.map_or(y, |t: f64| t.max(y))); + } + top +} + +/// The face in the plane of a cut from station s to station t: at each, from the height `lo` up to `hi` at `x` across; +/// nothing where `hi` is not over `lo`. +pub fn cut_face f64>( + b: &mut Builder, + (s, t): (&Station, &Station), + at_s: (f64, f64, f64), + at_t: (f64, f64, f64), + colour: u32, + out: [f64; 3], +) { + let side = |(x, lo, hi): (f64, f64, f64)| [[x, lo], [x, hi.max(lo)]]; + if at_s.2 > at_s.1 + 1e-6 || at_t.2 > at_t.1 + 1e-6 { + b.strip((s, &side(at_s)), (t, &side(at_t)), colour, out); + } +} + +/// Where two spans at a cut differ: of the own span from `lo` to `hi`, the part under the other's span and the part +/// over it, each (lo, hi); the whole own span where the other has none. +pub fn steps((lo, hi): (f64, f64), other: Option<(f64, f64)>) -> [(f64, f64); 2] { + match other { + // `max` and `min`, not `clamp`: its check of the bounds would bring the formatting of floats into the WASM. + Some((olo, ohi)) => [(lo, olo.max(lo).min(hi)), (ohi.max(lo).min(hi), hi)], + None => [(lo, hi), (hi, hi)], + } +} + /// The corners of a wall from its foot to its spring at `x`, with the spring of a lower section that goes on at that /// ring between: the step face there meets the wall at it. fn wall_side(x: f64, foot: f64, spring: f64, lower: Option) -> Vec { @@ -313,6 +641,9 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { let sp = spring(net, chord.section, chord.height); let bore = |colour: u32| flagged(colour, BORE); let across = |c: Corner| s.mix(&t, 0.5).out(c); + // Of two tubes that meet, each draws its side of the middle between their walls. + let meetings = net.clips(c, (&s, &t)); + b.clip(meetings.iter().map(|m| m.clip).collect()); // A box section is cast: its rock bore is lined. let cast = chord.section == Section::Box; let (wall, vault) = match bore_of { @@ -369,9 +700,10 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { for k in 0..2 { step(b, net, c, k, &o, vault); } - // At an opening, the front of the floor goes down to the sill, `lift_m` under the floor. Each side of a piece has - // a corner at the top of each piece beside it, which is the corner of a face there. - for (k, r) in [(0, &s), (1, &t)].into_iter().filter(|(k, _)| net.opening_at(c, *k)) { + // At an opening (not a closed end), the front of the floor goes down to the sill, `lift_m` under the floor. Each + // side of a piece has a corner at the top of each piece beside it, which is the corner of a face there. + let open = |k: usize| net.end_at(c, k).is_some_and(|e| !net.closed(e)); + for (k, r) in [(0, &s), (1, &t)].into_iter().filter(|(k, _)| open(*k)) { let out = flat(if k == 0 { [-d[0], -d[1]] } else { d }); for &(a0, a1, top) in &pieces { let side = |x: f64| { @@ -384,15 +716,41 @@ pub fn inside f64>(b: &mut Builder, net: &Net, c: usize) { b.strip((r, &side(a0)), (r, &side(a1)), bore(inside.walk), out); } } - if bore_of != Bore::Road { - return; + if bore_of == Bore::Road { + lamps(b, net, c, (&s, &t)); } - // A lamp under the crown where the metres along pass a multiple of the spacing. + b.clip(Vec::new()); + // At a cut, a face closes the room where the other tube's floor is higher or its roof lower. + let span = |st: &Station, cut: &Cut| { + let f = |p: &[(f64, f64, f64)], x: f64| p.iter().find(|q| x >= q.0 - 1e-9 && x <= q.1 + 1e-9).map(|q| q.2); + let own = f(&pieces, cut.x).zip(top_at(&o, cut.x))?; + let other = &net.chords[cut.other]; + let mut oo = inside_outline(net, other); + let (op, m) = (floor_pieces(net, other), oo.len() - 1); + (oo[0][1], oo[m][1]) = (op[0].2, op[op.len() - 1].2); + let (xl, df) = (cut.across, cut.floor - st.z); + Some(steps(own, f(&op, xl).zip(top_at(&oo, xl)).map(|(lo, hi)| (lo + df, hi + df)))) + }; + for m in &meetings { + let ((s, cs), (t, ct)) = (m.from, m.to); + if let (Some([ls, us]), Some([lt, ut])) = (span(&s, &cs), span(&t, &ct)) { + let out = across([-cs.axis.signum(), 0.0]); + cut_face(b, (&s, &t), (cs.x, ls.0, ls.1), (ct.x, lt.0, lt.1), bore(inside.walk), out); + cut_face(b, (&s, &t), (cs.x, us.0, us.1), (ct.x, ut.0, ut.1), bore(vault), out); + } + } +} + +/// The lamps of chord c of a road bore, from ring s to ring t: one under the crown where the metres along pass a multiple +/// of the spacing. +fn lamps f64>(b: &mut Builder, net: &Net, c: usize, (s, t): (&Station, &Station)) { + let (chord, design, inside) = (&net.chords[c], &net.rules.design, &net.rules.inside); + let length = direction(chord).1; let mut at = (chord.along / design.lamp_spacing_m).ceil() * design.lamp_spacing_m; while at < chord.along + length { let m = at - chord.along; let (p, q) = (((m - design.lamp_m / 2.0) / length).max(0.0), ((m + design.lamp_m / 2.0) / length).min(1.0)); - let (sp, sq) = (s.mix(&t, p), s.mix(&t, q)); + let (sp, sq) = (s.mix(t, p), s.mix(t, q)); let up = chord.height - LAMP_DROP_M; let light = flagged(inside.lamp, LAMP); let v = [ @@ -428,14 +786,18 @@ pub struct Meets { pub lower: Option<(f64, Section)>, } -/// The outer shell of a run of pieces, each its start and end station and its chord's height and section, with the -/// inside half-width `half`; its walls go down to the world height `foot`. Where two pieces of different height meet, -/// a face closes the step, facing the lower one; so too after the last piece where a lower shell goes on (`meets`). -/// There the walls have a corner at the foot of the shell that goes on. +/// A piece of a run of shell: its start and end station, its chord's height and section, and the chord. +pub type Run = (Station, Station, f64, Section, usize); + +/// The outer shell of a run of pieces, with the inside half-width `half`; its walls go down to the world height `foot`. +/// Where two pieces of different height meet, a face closes the step, facing the lower one; so too after the last piece +/// where a lower shell goes on (`meets`). There the walls have a corner at the foot of the shell that goes on. Of two +/// tubes that meet, each draws its side of the middle between their walls, and a face closes the step where its shell +/// is the higher there. pub fn shell f64>( b: &mut Builder, net: &Net, - pieces: &[(Station, Station, f64, Section)], + pieces: &[Run], half: f64, foot: f64, colour: u32, @@ -444,7 +806,32 @@ pub fn shell f64>( let last = |i: usize| i + 1 == pieces.len(); let next_of = |i: usize| pieces.get(i + 1).map(|p| (p.2, p.3)).or(meets.lower.filter(|_| last(i))); let outer = |st: &Station, h: f64, section: Section| shell_outline(net, section, half, h, foot - st.z); - for (i, (s, t, h, section)) in pieces.iter().enumerate() { + for (i, &(ref s, ref t, ref h, ref section, c)) in pieces.iter().enumerate() { + let meetings = net.clips(c, (s, t)); + // Where a clip ends inside the piece, a face closes the shell past the middle, toward the clip. It lies on the + // clip's bound, so it draws unclipped. + b.clip(Vec::new()); + for m in &meetings { + if let Some(e) = m.end { + let out = flat([m.from.0.x - e.x, m.from.0.y - e.y]); + end_section(b, net, c, (*h, *section, half, foot), &e, (m.to.1.x, m.from.1.axis.signum()), colour, out); + } + } + b.clip(meetings.iter().map(|m| m.clip).collect()); + for m in &meetings { + let ((ms, cs), (mt, ct)) = (m.from, m.to); + // The other tube's shell top at the cut, over this station's floor. + let top = |st: &Station, cut: &Cut| { + let own = top_at(&outer(st, *h, *section), cut.x)?; + let other = &net.chords[cut.other]; + let o = shell_outline(net, other.section, other.half, other.height, foot - cut.floor); + Some((own, top_at(&o, cut.across)? + cut.floor - st.z)) + }; + if let (Some((os, xs)), Some((ot, xt))) = (top(&ms, &cs), top(&mt, &ct)) { + let out = ms.mix(&mt, 0.5).out([cs.axis.signum(), 0.0]); + cut_face(b, (&ms, &mt), (cs.x, xs.min(os), os), (ct.x, xt.min(ot), ot), colour, out); + } + } let (sp, top) = (spring(net, *section, *h), shell_spring(net, *section, *h)); let (os, ot) = (outer(s, *h, *section), outer(t, *h, *section)); let n = os.len(); @@ -481,6 +868,60 @@ pub fn shell f64>( b.strip((t, &tall[j..j + 2]), (t, &low[j..j + 2]), colour, toward); } } + b.clip(Vec::new()); +} + +/// The face at station `st` across chord c that closes a shell where its clip ends: the shell's section past the +/// middle `x` on the side `side` (1 to the left), between its outside and its room, from its foot up; facing `out`. +#[allow(clippy::too_many_arguments)] +fn end_section f64>( + b: &mut Builder, + net: &Net, + c: usize, + (h, section, half, foot): (f64, Section, f64, f64), + st: &Station, + (x, side): (f64, f64), + colour: u32, + out: [f64; 3], +) { + let chord = &net.chords[c]; + // In the frame mirrored to the side, so the part past the middle runs to rising metres across. + let mirror = |o: Vec| { + let mut m: Vec = o.into_iter().map(|p| [side * p[0], p[1]]).collect(); + if side < 0.0 { + m.reverse(); + } + m + }; + let xm = side * x; + let base = foot - st.z; + let shell = mirror(shell_outline(net, section, half, h, base)); + let Some(top) = top_at(&shell, xm) else { return }; + let past = |o: &[Corner]| o.iter().copied().filter(|p| p[0] > xm + 1e-9).collect::>(); + let mut outside = vec![[xm, top]]; + outside.extend(past(&shell)); + outside.push([xm, base]); + let pieces = floor_pieces(net, chord); + let mut room = inside_outline(net, chord); + let n = room.len(); + (room[0][1], room[n - 1][1]) = (pieces[0].2, pieces[pieces.len() - 1].2); + let room = mirror(room); + let mut floor: Vec = pieces.iter().flat_map(|p| [[p.0, p.2], [p.1, p.2]]).collect(); + floor.dedup(); + let floor = mirror(floor); + let inner = match (top_at(&room, xm), floor.iter().rev().find(|p| p[0] <= xm + 1e-9)) { + (Some(roof), Some(&[_, level])) => { + let mut i = vec![[xm, roof]]; + i.extend(past(&room)); + i.extend(past(&floor).into_iter().rev()); + i.push([xm, level]); + i.dedup(); + i + } + _ => vec![[xm, top], [xm, base]], + }; + let back = |o: Vec| o.into_iter().map(|p| [side * p[0], p[1]]).collect::>(); + b.strip((st, &back(outside)), (st, &back(inner)), colour, out); } #[cfg(test)] diff --git a/specs/trailview-features.md b/specs/trailview-features.md index cba4848b5..e39df0e4d 100644 --- a/specs/trailview-features.md +++ b/specs/trailview-features.md @@ -588,8 +588,9 @@ Each opening takes the first kind of part that fits, by these rungs in order: the floor of the tube, as for every part. A short chain under a building only has no part. 4. An end that meets no way and is covered at its opening: `free`. 5. An end whose first covered metre lies within `collar_max_m`: `pair` where an opening of another chain of the same - family (rail or not) at that rung lies within `pair_max_m` and `pair_max_deg` (the nearest pairs first, each - opening in one pair); else `rock` for a group with `rock` covered within `rock_cover_max_m`; else `arch`. + family (rail or not) at that rung lies within `pair_max_m` and `pair_max_deg`, and each of the two chains has a + part at both of its ends (the nearest pairs first, each opening in one pair); else `rock` for a group with `rock` + covered within `rock_cover_max_m`; else `arch`. 6. Else `free`. The two openings of a pair lie on the frame line of the opening farther in: the other one moves in along its way to @@ -603,17 +604,16 @@ other. The numbers, in metres over the floor of the opening unless named: - `collar`: the metres to the first covered metre. For `box` it is at most half the chain. For `free` it is at most - `free_max_m` and half the chain, and that limit where no metre is covered. For `pair` it is the larger of the - two tubes. + `free_max_m` and half the chain, and that limit where no metre is covered. Each tube of a pair has its own. - `face`: the highest ground on the frame line plus `coping_m`, at least `height` + `shell_m` + `band_m`, at most `height` + `shell_m` + `face_over_crown_max_m`, and at most the underside of a deck over the frame line or its wing - walls less `coping_m`. A deck is over them where that lies over the floor: a way that goes on from the opening on a + walls less `coping_m`. In a pair, the least is over the higher crown of the two tubes and the most over the lower. A deck is over them where that lies over the floor: a way that goes on from the opening on a deck is not. So a deck can make `face` lower than `height` + `shell_m`. - `left`, `right`: a row of wall tops, one per metre out from the outer edge of the frame, the ground plus `coping_m`, from `coping_m` up to `face`. A row ends before the first metre whose ground lies under the floor + `wing_ground_m`, or at `wing_max_m`, and has one value at least. `left` is to the left of the way into the tube. -- `foot`: the lowest ground under the frame, its wing walls and its collar, less `foot_m`. The floor counts as ground - there, so `foot` is at most −`foot_m`. +- `foot`: the lowest ground under the frame, its wing walls and its collars, less `foot_m`. The floors count as + ground there, so `foot` is at most −`foot_m`. The tags, numbers in metres with at most 2 decimals, the values of a row separated by a space: @@ -627,14 +627,14 @@ The tags, numbers in metres with at most 2 decimals, the values of a row separat | `along` | tube | The metres along the stroke of its way at the first vertex | | `ends` | tube | The parts of the chain's two ends, the end behind the first vertex first: `arch`, `pair`, `rock`, `box`, `free`, or `none` for an end with no part of its own | | `part` | end | `arch`, `pair`, `rock`, `box` or `free` | -| `heading` | end | Radians from x to y of world coordinates, into the tube, three decimals | +| `heading` | end | Radians from x to y of world coordinates, into the tube, three decimals; of `pair`, into the tube of the opening farther in, square to the frame line | | `collar` | end | The collar; of `free`, the length of its shell | | `face`, `left`, `right` | end | Not on `free` | | `foot` | end | | | `way` | end | The end vertex of the way of the opening, `x y` in the frame of the ground plan (2^34 units per side): the point that each zoom-13 tile holds, a quarter unit times 32, or a whole unit times 128 on a way with no alignment | | `shift` | end | The metres along that way from `way` to the opening; 0 where it did not move | | `mate` | `pair` | The metres to the left from its axis to the axis of the other tube | -| `mate_way`, `mate_shift` | `pair` | `way` and `shift` of the other opening | +| `mate_way`, `mate_shift`, `mate_collar` | `pair` | `way`, `shift` and `collar` of the other opening | Each `tunnel-tube` has the two vertices of one chord of the tube from opening to opening, in the rising metres along the stroke of its way, so a tile that holds a piece of the tube holds whole records. A chain end with no opening