diff --git a/HANDOFF.md b/HANDOFF.md index 9f0c6ad..1aded3c 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -117,7 +117,7 @@ The full process is in [CONTRIBUTING.md](CONTRIBUTING.md): issue first → branc ## 6. Testing -- `cargo test --workspace` — 145 tests: 122 core, 1 relay, 22 app, of which three app tests need the network and are skipped unless asked for (`cargo test -p velopopuli -- --ignored`); `npx tsc --noEmit` for the page. CI runs all of them. +- `cargo test --workspace` — 154 tests: 130 core, 1 relay, 23 app, of which four app tests need the network and are skipped unless asked for (`cargo test -p velopopuli -- --ignored`); `npx tsc --noEmit` for the page. CI runs all of them. - **The smoke harness** is how most visual and end-to-end checking has been done: a debug build that rides (or opens a screen) by itself, saves pictures and the visible text, and quits. All the `VP_SMOKE_*` switches are documented in [Building and testing](docs/developers/building-and-testing.md#the-smoke-harness). The most useful: `VP_SMOKE_AT` (start part-way), `VP_SMOKE_CAM=3` (overhead — good for junctions), `VP_SMOKE_WINDOW=1` (whole window with HUD), `VP_SMOKE_CLIP=6` (frames for a demo clip), `VP_SMOKE_SURFACE`, `VP_SKIP_OVERPASS`, `VP_SMOKE_REPORT`. With `"nativeRenderer": true` in the data folder's `settings.json`, the native renderer's own frame is saved too, as `.native.png` — the only way to see it, since window snapshots capture just the web view. - The ride-start diagnostics line `[ride] surfaces … trails … berms … fords … widths …` shows what the map matching decided; a smoke run also prints each berm and ford. - Good test routes: Bourg d'Oisans → Alpe d'Huez (town, river, hairpins — route it with BRouter); the Trouée d'Arenberg (OSM track "Drève des Boules d'Hérin", `surface=sett`); Meylan near Grenoble (roundabouts); any city crossing (viaducts). For trails, around Finale Ligure: graded singletrack and switchbacks (berms), Ponte dell'Acqua (OSM way 143650465, a log bridge), Strada Valle del Bosco (way 113195224, a ford over the Rio dell'Ericeto); a hike near Chamonix (grades estimated from `sac_scale`); a field near Chartres (the off-map dirt track). A test route is two files in the data folder: `data/routes.json` and `data/route-.json` (`{name, gpx}`). @@ -143,6 +143,7 @@ CI also builds every push to `main`; installers can be downloaded from the run's 5a. Virtual gears — built (keyboard, Bluetooth remotes, OpenBikeControl controllers, on-screen buttons, rider-defined gear sets); next: Di2 and Zwift Click/Play shifters, Zwift Hub native shifting, and feeling it on real trainers. 6. Native renderer: verify HUD in a real window, measure release-build overhead, then Windows/Linux hosts. 7. **Stretch — self-hosted group servers and clubs.** Design agreed in discussion: no central server; identity is a keypair created on the device (no accounts), friends lists stored locally and exchanged by friend codes/QR including the friend's home server address, clubs run their own server (the relay plus a small database: members, invites, scheduled rides, shared routes, leaderboards), optional community server, federation later. Package the relay as a Docker image with `wss://`. Leaderboards can't be cheat-proof (power comes from the rider's device). +7a. **Riding a real road, not a closed course** (README roadmap). Road rides look like a race circuit: `barriers.rs` lines every road ride with crowd barriers, and the ridden road is its own ribbon (`World::road`) that `roads.rs`'s other roads don't join. Aim: a choice in ride setup between **Closed race** (today's course, barriers and all) and **Road ride**: open roads (no barriers; kerbs, pavements, verges and mapped boundaries at the edge instead), junctions that join the ribbon as one surface with give-way/stop lines, the ridden road marked like the rest of the network (lanes, cycle lanes, widths at junctions), roadside furniture from the map (fingerposts, street lights, bus stops, parked cars), keeping to the country's side of the road, and optional light traffic. 8. More OpenStreetMap detail: roof shapes, other land cover, mapped leaf types (`leaf_type` needs Overpass; the vector tiles only say "forest"), squares. ## 9. Decisions and the reasons for them diff --git a/README.md b/README.md index ec8a478..6a11b64 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Free and open source ([GPLv3](LICENSE)) for **Windows, macOS and Linux**. Writte - **Herne Hill Velodrome, built in.** The 450 m outdoor track in south London where the 1948 Olympic track events were raced, at its real place: banked to 26° in the bends, painted with the côte d'azur and the sprinters' and stayers' lines, and ringed by the railing and floodlights, with the 2018 pavilion, the bleachers, the club's containers and canopy, and the junior track in the middle. Ride it anticlockwise as raced, or clockwise. It is the same track as OpenBikeNet's `herne-hill-450` route. - **A closed road, race-day style.** The road you ride is set apart from the map's road network: steel crowd barriers line both sides (with banners on some, each section standing on its feet and leaning with the road on hills, and orange netting round the outside of tight hairpins instead), its surface is the real one — tarmac, concrete slabs, cobbles, gravel or dirt — and so is its width: a 7 m main road, a 5 m village street, a 3 m farm track. Both come from OpenStreetMap's tags for the roads along the route (`surface`, `width`, `lanes`, and the road class), or are guessed from the road class when those can't be fetched. Where the route leaves the mapped roads for 100 m or more — across a field, along an unmapped trail — it becomes a dirt track. Widths change gradually, and buildings, signs, other riders and the barriers all follow them. Ride the Arenberg trench on its setts and the Strade Bianche on white gravel — and feel them: rougher surfaces roll heavier, so you slow down on screen and the trainer gets harder. - **Mountain-bike trails.** Where the route follows an unpaved path, a bridleway, a walking trail or a trail graded for mountain bikes (OpenStreetMap's `mtb:scale`, S0–S6, or estimated from the hiking grade), you ride a narrow earth singletrack with no barriers, the HUD shows the grade, and the harder the grade the heavier it rolls — on screen and on the trainer. -- **Find a route in the app.** Search for a place, click waypoints on the map and get a route along bike-friendly roads with real elevation (BRouter), or pick one of eight famous climbs (Alpe d'Huez, Mont Ventoux, Stelvio, Galibier, Tourmalet, Mortirolo, Zoncolan, Box Hill). Pick from the **signposted road routes** (OpenStreetMap cycle routes, local to national) or **waymarked MTB routes** mapped in the area on screen, or, with Strava connected, from **your Strava routes**. With Dreeve connected, any ride you've done can be imported as a route. +- **Find a route in the app.** Search for a place, click waypoints on the map and get a route with real elevation (BRouter), in six styles from road bike to gravel and mountain bike, a different one for each section if you like. Drag the route to change it, or let the app **make a loop** of the distance you want. See what it's made of before you ride: surfaces, main roads and lanes, the climbs, and how long it'll take. Or pick one of eight famous climbs (Alpe d'Huez, Mont Ventoux, Stelvio, Galibier, Tourmalet, Mortirolo, Zoncolan, Box Hill). Pick from the **signposted road routes** (OpenStreetMap cycle routes, local to national) or **waymarked MTB routes** mapped in the area on screen, or, with Strava connected, from **your Strava routes**. With Dreeve connected, any ride you've done can be imported as a route. - **Smart trainer control.** Gradient simulation or ERG mode, over Bluetooth FTMS, Tacx FE-C-over-Bluetooth, or ANT+ FE-C. The gradient "feel" scales the real slope, softens descents and caps the steepest pitch (so a 15% ramp is rideable on any trainer). Shift your bike's own gears as normal, or set up **virtual gears** — your own chainrings and cassette or a preset — and shift with keys, a Bluetooth remote, a handlebar controller or on-screen buttons. - **Structured workouts on any route.** Import Zwift `.zwo`, `.erg` or `.mrc` files, or use the built-in sessions (endurance, sweet spot, threshold, VO₂max, over-unders, sprints and an FTP ramp test). The trainer holds each target in ERG while the route scrolls by; adjust the intensity or skip a step mid-ride. - **Fitness tracking.** Power curve (5 s to 1 h), an FTP estimate you can apply in one click, power zones on the HUD, and a training-load chart of fitness, fatigue and form. @@ -67,7 +67,7 @@ Be aware of what has and has not been proven: | Laps on loop routes | Unit-tested in `crates/core`: lap counting, distance ridden, climbs and segments timed on every lap, bests kept from the fastest lap, ghosts off. Smoke-run on Linux with the three.js renderer: the lap HUD, and riders, road and barriers across the line. **Not yet** run with the native renderer (macOS). FIT lap messages and ending the ride on the workout are not done | | Group-ride relay | Tested in-process (`cargo test -p velopopuli-relay`) and with two app instances riding together through a local relay | | Fan and lights | Requests checked against a pretend device for Home Assistant, Shelly and a webhook; not tried with real plugs | -| Route finder, famous climbs | All eight climbs planned through the live BRouter service and checked against their known length and height gain | +| Route finder, famous climbs | All eight climbs planned through the live BRouter service and checked against their known length and height gain. Loops, sections and the surface breakdown are unit-tested, and a 40 km loop was made through the live service and checked in the smoke harness. Dragging the route and the undo list have **not yet** been tried by riders | | Waymarked MTB routes | Listed and joined from the live Overpass API around Finale Ligure (a 23 km route joined with no gaps); the joining is unit-tested. The screen itself was only type-checked, not clicked through | | Strava segments and ghosts from Strava | Matching is unit-tested; segments and ghost imports haven't yet been confirmed against the live API | | Signposted road routes | Listed from the live Overpass API (UK National Cycle Network and regional routes); clipping a long route to the area searched is unit-tested | @@ -209,6 +209,22 @@ Your browser opens for approval. The key and tokens are stored in the system key - More from OpenStreetMap: mapped roof shapes, other land cover (farmland, rock, glaciers), mapped leaf types, squares and car parks - Wahoo legacy protocol and steering; Di2 and Zwift Click/Play controllers as shifters for virtual gears without a bridge +### Riding a real road, not a closed course + +A road ride today looks like a race on a closed circuit: crowd barriers line both sides, and the road ridden is a strip of its own that the map's other roads don't join. That suits a race, but not every ride. The plan is a choice when you set up a ride: + +- **Closed race:** the course as it is now, closed to traffic, with crowd barriers, netting on the hairpins and the road to yourself. +- **Road ride:** riding your bike on the real road network, as below. + +For a road ride: + +- **Open roads.** No crowd barriers. In their place, the real roadside: kerbs and pavements in towns, grass verges in the country, and the mapped hedges, walls and fences right up to the edge, with gateways and driveways in them. +- **Junctions that join up.** Side roads meet the road being ridden as one surface, with give-way and stop lines, breaks in the centre line, and markings at roundabouts and crossings. +- **One road network.** The road ridden is drawn like every other road on the map, with its markings from the map: lanes, cycle lanes, bus lanes, and the width changing at junctions. +- **Life by the roadside.** Fingerposts at junctions pointing to the next places, street lights, bus stops, post boxes, and parked cars on town streets. +- **Riding on your side of the road.** Keeping to the left or right as the country drives, with the rider's line through corners, rather than riding down the middle. +- **Other road users.** Optional light traffic: other cyclists and the odd car on the roads around you, crossing at junctions. + ### Stretch: self-hosted group-ride servers Group rides already go through a small relay anyone can run (`crates/relay`; CI builds it for every platform). The stretch goal is to make running your own server for a club or group of friends a first-class option: diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 6389c0f..9d36298 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -10,6 +10,7 @@ pub mod gamify; pub mod gearing; pub mod gpx; pub mod physics; +pub mod planner; pub mod ride; pub mod segments; pub mod types; diff --git a/crates/core/src/planner.rs b/crates/core/src/planner.rs new file mode 100644 index 0000000..4e81430 --- /dev/null +++ b/crates/core/src/planner.rs @@ -0,0 +1,348 @@ +//! Planning a route on the map: the sections between waypoints as BRouter returns them, +//! joined into one line, with what each stretch is (its surface and the kind of way), a +//! breakdown of the whole route, an estimate of how long it takes to ride, and loops. +//! +//! Fetching is the app's job (`src-tauri/src/geo.rs`); everything here works on the replies. + +use serde::Serialize; + +use crate::gpx::{haversine, RawPoint, Route}; +use crate::physics::{step_speed, PhysicsParams}; +use crate::world::Surface; + +/// The routing styles offered, as BRouter profile names. The first is the default. +pub const STYLES: [&str; 6] = ["fastbike", "fastbike-verylowtraffic", "gravel", "trekking", "safety", "mtb"]; + +/// The style to route with: `style` when it's one of [`STYLES`], otherwise the default. +pub fn style(style: &str) -> &'static str { + STYLES.iter().find(|s| **s == style).copied().unwrap_or(STYLES[0]) +} + +/// One routed section, or several joined. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Leg { + /// `[lat, lon]` and the height when the router knew it. + pub points: Vec<([f64; 2], Option)>, + /// Stretches of the same way, in order: each runs from the previous one's `to` (or the + /// first point) to the point at index `to`, with that way's OpenStreetMap tags. + pub stretches: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Stretch { + pub to: usize, + pub tags: String, +} + +impl Leg { + /// Length in metres. + pub fn length(&self) -> f64 { + self.points.windows(2).map(|w| haversine(w[0].0[0], w[0].0[1], w[1].0[0], w[1].0[1])).sum() + } + + /// The part from point `from` to point `to`, both included. + pub fn slice(&self, from: usize, to: usize) -> Leg { + let to = to.min(self.points.len().saturating_sub(1)); + let mut stretches = Vec::new(); + for s in &self.stretches { + if s.to <= from { + continue; + } + stretches.push(Stretch { to: s.to.min(to) - from, tags: s.tags.clone() }); + if s.to >= to { + break; + } + } + Leg { points: self.points[from..=to].to_vec(), stretches } + } + + pub fn raw_points(&self) -> Vec { + self.points.iter().map(|&([lat, lon], ele)| RawPoint { lat, lon, ele }).collect() + } +} + +/// Reads one BRouter reply in `format=geojson`: the line, and the tags of each way along it +/// (the `messages` table, one row where each way ends). +pub fn parse_brouter(json: &str) -> Result { + let v: serde_json::Value = serde_json::from_str(json).map_err(|_| "The route planner sent something unexpected.".to_string())?; + let feature = &v["features"][0]; + let points: Vec<([f64; 2], Option)> = feature["geometry"]["coordinates"] + .as_array() + .ok_or("The route planner found no route.")? + .iter() + .filter_map(|c| Some(([c[1].as_f64()?, c[0].as_f64()?], c.get(2).and_then(serde_json::Value::as_f64)))) + .collect(); + if points.len() < 2 { + return Err("The route planner found no route.".into()); + } + let mut stretches = Vec::new(); + if let Some(rows) = feature["properties"]["messages"].as_array() { + let header: Vec<&str> = rows.first().and_then(|h| h.as_array()).map(|h| h.iter().filter_map(|c| c.as_str()).collect()).unwrap_or_default(); + let col = |name: &str| header.iter().position(|h| *h == name); + if let (Some(lon), Some(lat), Some(tags)) = (col("Longitude"), col("Latitude"), col("WayTags")) { + // Rows give their end point in millionths of a degree; find it along the line. + let key = |p: [f64; 2]| ((p[0] * 1e6).round() as i64, (p[1] * 1e6).round() as i64); + let mut at = 0; + for row in rows.iter().skip(1).filter_map(|r| r.as_array()) { + let cell = |i: usize| row.get(i).and_then(|c| c.as_str()).unwrap_or(""); + let (Ok(x), Ok(y)) = (cell(lon).parse::(), cell(lat).parse::()) else { continue }; + if let Some(k) = (at..points.len()).find(|&k| key(points[k].0) == (y, x)) { + if k > at { + stretches.push(Stretch { to: k, tags: cell(tags).to_string() }); + at = k; + } + } + } + } + } + // Whatever the table didn't reach (or a reply without one) is a stretch of unknown way. + let last = points.len() - 1; + if stretches.last().is_none_or(|s| s.to < last) { + stretches.push(Stretch { to: last, tags: String::new() }); + } + Ok(Leg { points, stretches }) +} + +/// The sections end to end, the shared point where they meet kept once. +pub fn join(legs: &[Leg]) -> Leg { + let mut out = Leg::default(); + for leg in legs { + let offset = out.points.len().saturating_sub(1); + let skip = usize::from(!out.points.is_empty()); + out.points.extend(leg.points.iter().skip(skip).copied()); + for (k, s) in leg.stretches.iter().filter(|s| s.to > 0).enumerate() { + match out.stretches.last_mut() { + // The same way carrying on across the join is one stretch, as it was before cutting. + Some(last) if k == 0 && last.tags == s.tags => last.to = s.to + offset, + _ => out.stretches.push(Stretch { to: s.to + offset, tags: s.tags.clone() }), + } + } + } + out +} + +/// What a stretch's surface is, as far as the map says. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, PartialOrd, Ord)] +#[serde(rename_all = "camelCase")] +pub enum SurfaceClass { + Paved, + Cobbles, + Gravel, + Dirt, + Unknown, +} + +/// What kind of way a stretch is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, PartialOrd, Ord)] +#[serde(rename_all = "camelCase")] +pub enum WayClass { + MainRoad, + MinorRoad, + CyclePath, + Track, + Path, +} + +fn tag<'a>(tags: &'a str, key: &str) -> Option<&'a str> { + tags.split(' ').find_map(|kv| kv.split_once('=').filter(|(k, _)| *k == key).map(|(_, v)| v)) +} + +/// The surface and the kind of way, from a stretch's tags. A road with no surface mapped is +/// taken to be paved, as the 3D world does; a track or path with none is unknown. A track's +/// grade stands in for its surface when that's missing. +pub fn classify(tags: &str) -> (SurfaceClass, WayClass) { + let highway = tag(tags, "highway").unwrap_or(""); + let road = highway.trim_end_matches("_link"); + let way = match road { + "motorway" | "trunk" | "primary" | "secondary" => WayClass::MainRoad, + "tertiary" | "unclassified" | "residential" | "living_street" | "service" | "road" => WayClass::MinorRoad, + "cycleway" => WayClass::CyclePath, + "path" | "footway" | "bridleway" if tag(tags, "bicycle") == Some("designated") => WayClass::CyclePath, + "track" => WayClass::Track, + _ => WayClass::Path, + }; + let tracktype = || match tag(tags, "tracktype") { + Some("grade1") => SurfaceClass::Paved, + Some("grade2" | "grade3") => SurfaceClass::Gravel, + Some("grade4" | "grade5") => SurfaceClass::Dirt, + _ => SurfaceClass::Unknown, + }; + let surface = match tag(tags, "surface").and_then(Surface::from_osm) { + Some(Surface::Asphalt | Surface::Concrete) => SurfaceClass::Paved, + Some(Surface::Cobbles) => SurfaceClass::Cobbles, + Some(Surface::Gravel) => SurfaceClass::Gravel, + Some(Surface::Dirt) => SurfaceClass::Dirt, + None if matches!(way, WayClass::MainRoad | WayClass::MinorRoad) => SurfaceClass::Paved, + None if way == WayClass::Track => tracktype(), + None => SurfaceClass::Unknown, + }; + (surface, way) +} + +impl SurfaceClass { + /// How much harder it rolls than tarmac, as the ride will feel it (unknown counts as tarmac). + pub fn rolling_factor(self) -> f64 { + match self { + SurfaceClass::Paved | SurfaceClass::Unknown => Surface::Asphalt.rolling_factor(), + SurfaceClass::Cobbles => Surface::Cobbles.rolling_factor(), + SurfaceClass::Gravel => Surface::Gravel.rolling_factor(), + SurfaceClass::Dirt => Surface::Dirt.rolling_factor(), + } + } +} + +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Share { + pub class: T, + pub metres: f64, +} + +/// A run of the same surface and kind of way, for drawing on the map. +#[derive(Debug, Clone, Serialize, PartialEq)] +pub struct Run { + pub surface: SurfaceClass, + pub way: WayClass, + /// Where it starts and ends along the route, in metres. + pub from: f64, + pub to: f64, + /// `[lat, lon]`, thinned. + pub line: Vec<[f64; 2]>, +} + +#[derive(Debug, Clone, Serialize, PartialEq, Default)] +pub struct Breakdown { + /// Each surface and each kind of way with how much of the route it is, largest first. + pub surfaces: Vec>, + pub ways: Vec>, + pub runs: Vec, +} + +/// How much of the route is each surface and each kind of way, and where. Lines are thinned +/// to about `max_points` points in all. +pub fn breakdown(leg: &Leg, max_points: usize) -> Breakdown { + let n = leg.points.len(); + if n < 2 { + return Breakdown::default(); + } + let mut along = vec![0.0; n]; + for i in 1..n { + along[i] = along[i - 1] + haversine(leg.points[i - 1].0[0], leg.points[i - 1].0[1], leg.points[i].0[0], leg.points[i].0[1]); + } + let stride = (n / max_points.max(2)).max(1); + let mut runs: Vec = Vec::new(); + let mut start = 0; + for s in &leg.stretches { + let end = s.to.min(n - 1); + if end <= start { + continue; + } + let (surface, way) = classify(&s.tags); + let points = |from: usize| (from..=end).filter(move |&i| i == from || i == end || (i - from).is_multiple_of(stride)); + match runs.last_mut() { + Some(r) if r.surface == surface && r.way == way => { + r.to = along[end]; + r.line.extend(points(start).skip(1).map(|i| leg.points[i].0)); + } + _ => runs.push(Run { surface, way, from: along[start], to: along[end], line: points(start).map(|i| leg.points[i].0).collect() }), + } + start = end; + } + let mut surfaces: Vec> = Vec::new(); + let mut ways: Vec> = Vec::new(); + for r in &runs { + let metres = r.to - r.from; + match surfaces.iter_mut().find(|s| s.class == r.surface) { + Some(s) => s.metres += metres, + None => surfaces.push(Share { class: r.surface, metres }), + } + match ways.iter_mut().find(|s| s.class == r.way) { + Some(s) => s.metres += metres, + None => ways.push(Share { class: r.way, metres }), + } + } + surfaces.sort_by(|a, b| b.metres.total_cmp(&a.metres)); + ways.sort_by(|a, b| b.metres.total_cmp(&a.metres)); + Breakdown { surfaces, ways, runs } +} + +/// The joined line thinned to about `max_points`, always keeping the points where sections +/// meet; and, for each of those, its index in the thinned line (so a click on the line can be +/// put in the right section). +pub fn outline(leg: &Leg, section_ends: &[usize], max_points: usize) -> (Vec<[f64; 2]>, Vec) { + let n = leg.points.len(); + let stride = (n / max_points.max(2)).max(1); + let mut line = Vec::new(); + let mut ends = Vec::new(); + for i in 0..n { + let end = section_ends.contains(&i); + if end || i % stride == 0 || i == n - 1 { + if end { + ends.push(line.len()); + } + line.push(leg.points[i].0); + } + } + (line, ends) +} + +/// How long the route takes at a steady `power`, with the ride's own physics: the route's +/// gradients and heights, and the rolling resistance of each stretch's surface (`rolling` +/// gives the factor at a distance along the route). Seconds. +pub fn ride_time(route: &Route, power: f64, params: &PhysicsParams, rolling: impl Fn(f64) -> f64) -> f64 { + const DT: f64 = 0.5; + // Up a wall at low power the model would crawl for ever; nobody rides slower than this. + const SLOWEST: f64 = 1.2; + let (mut v, mut d, mut t) = (0.0f64, 0.0f64, 0.0f64); + while d < route.total && t < 7.0 * 86_400.0 { + let pos = route.sample_at(d); + let here = PhysicsParams { crr: params.crr * rolling(d), ..*params }; + v = step_speed(v, power, pos.grade, pos.ele, &here, DT).max(SLOWEST); + d += v * DT; + t += DT; + } + t +} + +/// The rolling factor along a joined line's stretches, as a lookup by distance along the +/// route (scaled to the route's own length, which differs a little after resampling). +pub fn rolling_lookup(breakdown: &Breakdown, route_total: f64) -> impl Fn(f64) -> f64 + '_ { + let line_total = breakdown.runs.last().map_or(1.0, |r| r.to).max(1.0); + let scale = line_total / route_total.max(1.0); + move |d: f64| { + let at = d * scale; + breakdown.runs.iter().find(|r| at <= r.to).map_or(1.0, |r| r.surface.rolling_factor()) + } +} + +/// BRouter makes a loop through points about this far from the start; the loop it rides is +/// roughly this many times as long. +const LOOP_PER_RADIUS: f64 = 6.4; + +/// The radius to ask BRouter for, for a loop of about `distance` metres. +pub fn round_trip_radius(distance: f64) -> f64 { + (distance / LOOP_PER_RADIUS).clamp(500.0, 60_000.0) +} + +/// Waypoints along a loop so it can be edited like any planned route: about one every +/// `spacing` metres (between 4 and 12 of them), the start again at the end. Each is given +/// with its index in the loop's points, so the sections between them can be reused as they are. +pub fn loop_waypoints(leg: &Leg, spacing: f64) -> Vec<(usize, [f64; 2])> { + let n = leg.points.len(); + if n < 2 { + return Vec::new(); + } + let total = leg.length(); + let count = ((total / spacing.max(1.0)).round() as usize).clamp(4, 12); + let mut out = vec![(0, leg.points[0].0)]; + let mut along = 0.0; + let mut next = 1; + for i in 1..n { + along += haversine(leg.points[i - 1].0[0], leg.points[i - 1].0[1], leg.points[i].0[0], leg.points[i].0[1]); + if next < count && along >= total * next as f64 / count as f64 && i < n - 1 { + out.push((i, leg.points[i].0)); + next += 1; + } + } + out.push((n - 1, leg.points[n - 1].0)); + out +} diff --git a/crates/core/tests/planner.rs b/crates/core/tests/planner.rs new file mode 100644 index 0000000..5c1da37 --- /dev/null +++ b/crates/core/tests/planner.rs @@ -0,0 +1,139 @@ +use velopopuli_core::gpx::{build_route, RawPoint}; +use velopopuli_core::physics::PhysicsParams; +use velopopuli_core::planner::*; + +/// A BRouter-style reply: points going east along a parallel, and a messages table whose +/// rows end at the given point indices with the given tags. +fn reply(n: usize, rows: &[(usize, &str)]) -> String { + let point = |i: usize| -> (f64, f64) { (-3.0 + i as f64 * 0.001, 50.5) }; + let coords: Vec = (0..n).map(|i| format!("[{:.6},{:.6},{}]", point(i).0, point(i).1, 10 + i)).collect(); + let mut messages = vec![r#"["Longitude","Latitude","Elevation","Distance","CostPerKm","ElevCost","TurnCost","NodeCost","InitialCost","WayTags","NodeTags","Time","Energy"]"#.to_string()]; + for (i, tags) in rows { + let (lon, lat) = point(*i); + messages.push(format!(r#"["{}","{}","10","100","1000","0","0","0","0","{tags}","","1","1"]"#, (lon * 1e6).round() as i64, (lat * 1e6).round() as i64)); + } + format!( + r#"{{"type":"FeatureCollection","features":[{{"type":"Feature","properties":{{"messages":[{}]}},"geometry":{{"type":"LineString","coordinates":[{}]}}}}]}}"#, + messages.join(","), + coords.join(",") + ) +} + +#[test] +fn reads_a_routed_section_and_its_ways() { + let leg = parse_brouter(&reply(6, &[(2, "highway=residential"), (4, "highway=track tracktype=grade2")])).unwrap(); + assert_eq!(leg.points.len(), 6); + assert_eq!(leg.points[0].0, [50.5, -3.0]); + assert_eq!(leg.points[3].1, Some(13.0)); + // The table stops at point 4; the last stretch is of unknown way. + let ends: Vec<(usize, &str)> = leg.stretches.iter().map(|s| (s.to, s.tags.as_str())).collect(); + assert_eq!(ends, vec![(2, "highway=residential"), (4, "highway=track tracktype=grade2"), (5, "")]); + assert!(parse_brouter("{}").is_err()); + assert!(parse_brouter("not json").is_err()); +} + +#[test] +fn sections_join_end_to_end_and_slice_back_apart() { + let a = parse_brouter(&reply(4, &[(3, "highway=primary")])).unwrap(); + let mut b = a.clone(); + b.stretches[0].tags = "highway=cycleway".into(); + let joined = join(&[a.clone(), b.clone()]); + // The point where they meet is kept once. + assert_eq!(joined.points.len(), 7); + assert_eq!(joined.stretches.iter().map(|s| s.to).collect::>(), vec![3, 6]); + assert_eq!(joined.slice(0, 3), a); + assert_eq!(joined.slice(3, 6).stretches, b.stretches); + assert_eq!(join(&[joined.slice(0, 2), joined.slice(2, 5), joined.slice(5, 6)]), joined); +} + +#[test] +fn stretches_are_classified_by_surface_and_way() { + use SurfaceClass::*; + use WayClass::*; + assert_eq!(classify("highway=residential maxspeed=50"), (Paved, MinorRoad)); + assert_eq!(classify("highway=primary surface=sett"), (Cobbles, MainRoad)); + assert_eq!(classify("highway=secondary_link"), (Paved, MainRoad)); + assert_eq!(classify("highway=track tracktype=grade2"), (Gravel, Track)); + assert_eq!(classify("highway=track"), (Unknown, Track)); + assert_eq!(classify("highway=track surface=asphalt"), (Paved, Track)); + assert_eq!(classify("highway=cycleway surface=asphalt"), (Paved, CyclePath)); + assert_eq!(classify("highway=path bicycle=designated"), (Unknown, CyclePath)); + assert_eq!(classify("highway=path surface=ground"), (Dirt, Path)); + assert_eq!(classify(""), (Unknown, Path)); +} + +#[test] +fn breakdown_adds_up_to_the_route() { + let leg = parse_brouter(&reply(11, &[(3, "highway=residential"), (5, "highway=residential surface=asphalt"), (8, "highway=track tracktype=grade3"), (10, "highway=primary")])).unwrap(); + let b = breakdown(&leg, 1000); + // The two residential stretches are one run. + assert_eq!(b.runs.len(), 3); + assert_eq!(b.runs[0].line.len(), 6); + let total = leg.length(); + let sum = |v: &[f64]| v.iter().sum::(); + assert!((sum(&b.surfaces.iter().map(|s| s.metres).collect::>()) - total).abs() < 0.01); + assert!((sum(&b.ways.iter().map(|s| s.metres).collect::>()) - total).abs() < 0.01); + // Largest first: 7 of the 10 steps are paved. + assert_eq!(b.surfaces[0].class, SurfaceClass::Paved); + assert!((b.surfaces[0].metres / total - 0.7).abs() < 0.01); + assert_eq!(b.ways.iter().map(|w| w.class).collect::>(), vec![WayClass::MinorRoad, WayClass::Track, WayClass::MainRoad]); + // Thinned to a point budget, runs still join up. + let thin = breakdown(&leg, 3); + assert_eq!(thin.runs[0].line.first(), Some(&leg.points[0].0)); + assert_eq!(thin.runs.last().unwrap().line.last(), Some(&leg.points[10].0)); +} + +#[test] +fn the_outline_keeps_the_points_where_sections_meet() { + let leg = parse_brouter(&reply(101, &[(100, "highway=residential")])).unwrap(); + let (line, ends) = outline(&leg, &[0, 37, 100], 10); + assert!(line.len() <= 15); + assert_eq!(ends.len(), 3); + assert_eq!(line[ends[0]], leg.points[0].0); + assert_eq!(line[ends[1]], leg.points[37].0); + assert_eq!(line[ends[2]], leg.points[100].0); +} + +#[test] +fn loops_become_editable_waypoints() { + // A square loop about 4.4 km round. + let corners = [[50.5, -3.0], [50.5, -2.9845], [50.51, -2.9845], [50.51, -3.0], [50.5, -3.0]]; + let mut points = Vec::new(); + for w in corners.windows(2) { + for k in 0..20 { + let t = k as f64 / 20.0; + points.push(([w[0][0] + (w[1][0] - w[0][0]) * t, w[0][1] + (w[1][1] - w[0][1]) * t], None)); + } + } + points.push((corners[4], None)); + let leg = Leg { stretches: vec![Stretch { to: points.len() - 1, tags: String::new() }], points }; + let wps = loop_waypoints(&leg, 1000.0); + assert!((4..=13).contains(&wps.len())); + assert_eq!(wps[0], (0, corners[0])); + assert_eq!(*wps.last().unwrap(), (leg.points.len() - 1, corners[4])); + assert!(wps.windows(2).all(|w| w[0].0 < w[1].0)); + // Cut at the waypoints and joined again, the loop is unchanged. + let parts: Vec = wps.windows(2).map(|w| leg.slice(w[0].0, w[1].0)).collect(); + assert_eq!(join(&parts), leg); + assert!((round_trip_radius(64_000.0) - 10_000.0).abs() < 1.0); +} + +#[test] +fn ride_time_follows_the_physics_and_the_surface() { + let raw: Vec = (0..=100).map(|i| RawPoint { lat: 50.5, lon: -3.0 + i as f64 * 0.0014, ele: Some(20.0) }).collect(); + let route = build_route("Flat", &raw).unwrap(); + let params = PhysicsParams { mass: 84.0, crr: 0.004, cda: 0.32, max_speed: 80.0 / 3.6 }; + let flat = ride_time(&route, 200.0, ¶ms, |_| 1.0); + // About 34 km/h at 200 W on the flat, plus a few seconds to get going. + let expected = route.total / (33.9 / 3.6); + assert!((flat - expected).abs() < 15.0, "{flat} vs {expected}"); + let gravel = ride_time(&route, 200.0, ¶ms, |_| 2.5); + assert!(gravel > flat * 1.07); +} + +#[test] +fn unknown_styles_fall_back_to_the_default() { + assert_eq!(style("gravel"), "gravel"); + assert_eq!(style("fastbike-verylowtraffic"), "fastbike-verylowtraffic"); + assert_eq!(style("car-fast"), "fastbike"); +} diff --git a/docs/developers/architecture.md b/docs/developers/architecture.md index 6923866..d01b6d9 100644 --- a/docs/developers/architecture.md +++ b/docs/developers/architecture.md @@ -19,7 +19,7 @@ ┌──────────────────────────────────────────────────────────────────────────┐ │ crates/core/ (pure computation, no I/O) │ │ gpx · physics · ride · workout · fitness · gamify · segments · fit │ -│ gearing · waymarked · velodrome · devices (protocols) · world (3D) │ +│ gearing · waymarked · planner · velodrome · devices · world (3D) │ └──────────────────────────────────────────────────────────────────────────┘ ``` @@ -41,6 +41,7 @@ crates/core/src/ segments.rs Other rides and segments matched onto the route; ghosts; photos → The ride fit.rs FIT activity encoder → The ride waymarked.rs Signposted and MTB route relations joined into one line → Routes + planner.rs Planned sections joined; surfaces and ways; loops; ride time → Routes velodrome.rs Built-in tracks (Herne Hill) as routes → Routes types.rs Settings and stored shapes shared with the app devices/ Bluetooth and ANT+ protocols, OpenBikeControl, the sensor hub → Devices diff --git a/docs/developers/building-and-testing.md b/docs/developers/building-and-testing.md index 68d548c..a50e08b 100644 --- a/docs/developers/building-and-testing.md +++ b/docs/developers/building-and-testing.md @@ -26,7 +26,7 @@ A full debug build plus a universal release build need about 10 GB in `target/`. ## Tests -There are 145 tests: 122 for the core, 1 for the relay and 22 for the app. `cargo test --workspace` runs all but three, which need the network and run only when asked for (`cargo test -p velopopuli -- --ignored`). +There are 154 tests: 130 for the core, 1 for the relay and 23 for the app. `cargo test --workspace` runs all but four, which need the network and run only when asked for (`cargo test -p velopopuli -- --ignored`). | Where | What it covers | |---|---| @@ -56,6 +56,7 @@ VP_DATA_DIR=/tmp/vp VP_SMOKE=/tmp/vp/shot.png target/debug/velopopuli | `VP_DATA_DIR` | Use this folder for all data. It works without `VP_SMOKE` too, for a separate test profile. | | `VP_SMOKE` | Path of the picture to save (the 3D canvas). Also writes `.txt` with the screen's text and the ride state. | | `VP_SMOKE_SCREEN` | `ride` (the default), `home`, `explore`, `workouts`, `devices`, `history` or `settings` | +| `VP_SMOKE_PLAN` | On `explore`, plan through `lat,lon;lat,lon;…`, or make a loop with `loop:lat,lon,km` | | `VP_SMOKE_SCROLL` | Scroll to the section with this heading before capturing (e.g. `Gears` on Settings) | | `VP_SMOKE_MS` | How long to run before capturing (default 9000). Give maps and terrain longer. | | `VP_SMOKE_WINDOW` | Also save the whole window, HUD included, as `.window.png` (macOS) | diff --git a/docs/developers/connectors-and-services.md b/docs/developers/connectors-and-services.md index c0a5681..be8dd2f 100644 --- a/docs/developers/connectors-and-services.md +++ b/docs/developers/connectors-and-services.md @@ -85,7 +85,7 @@ There's no clock sync or prediction: a rider is drawn where they last said they [`geo.rs`](../../src-tauri/src/geo.rs): - **Place search:** [Nominatim](https://nominatim.openstreetmap.org), up to 8 results. -- **Planning:** [BRouter](https://brouter.de) with the waypoints and a profile (`fastbike`, `trekking`, `safety`, `mtb`), returning a GPX with heights. +- **Planning:** [BRouter](https://brouter.de), one request per section between waypoints, each in its own profile, as GeoJSON with heights and way tags. Sections are kept in memory, so an edit only re-plans what changed. Loops use BRouter's round-trip mode. See [Routes](routes.md#planning-on-the-map). - **Famous climbs** (`CLASSICS`): eight climbs as start and finish points, planned through BRouter. - **Waymarked routes:** Overpass (see [Routes](routes.md#waymarked-routes)). diff --git a/docs/developers/routes.md b/docs/developers/routes.md index ff1f29c..35d6b10 100644 --- a/docs/developers/routes.md +++ b/docs/developers/routes.md @@ -67,7 +67,8 @@ Alpe d'Huez (about 13.8 km at 8.1%) scores about 112,000: HC. Each climb becomes | Source | How | Code | |---|---|---| | **A GPX file** | **Import GPX…** or dragging files on. The route is built once to check it, then the GPX text is stored. | `routes_import_dialog`, `routes_import_text`, `import_gpx` in `commands.rs` | -| **Planned on the map** | Waypoints go to [BRouter](https://brouter.de), which returns a GPX with heights. Profiles: `fastbike`, `trekking`, `safety`, `mtb`. | `geo_plan` → `geo::plan` | +| **Planned on the map** | Each section between waypoints goes to [BRouter](https://brouter.de) in its own style, and comes back with heights and the tags of every way (see [Planning on the map](#planning-on-the-map)) | `geo_plan` → `geo::plan`, [`planner.rs`](../../crates/core/src/planner.rs) | +| **A loop** | BRouter's round-trip mode, turned into waypoints | `geo_round_trip` → `geo::round_trip` | | **Place search** | [Nominatim](https://nominatim.openstreetmap.org) | `geo_search` → `geo::search` | | **Famous climbs** | Eight start and finish points (`geo::CLASSICS`), planned through BRouter like any route | `geo_classics` | | **Signposted road routes, MTB routes** | OpenStreetMap route relations (`route=bicycle`, `route=mtb`) in the area on the map, through Overpass | `geo_waymarked_routes`, `geo_waymarked_route`, [`waymarked.rs`](../../crates/core/src/waymarked.rs) | @@ -76,6 +77,33 @@ Alpe d'Huez (about 13.8 km at 8.1%) scores about 112,000: HC. Each climb becomes | **Built in** | The Demo Loop (`demo_route`, a synthetic 16 km loop with one climb) and Herne Hill (`velodrome.rs`) | `load_route` in `session.rs` | | **A group ride** | The host's GPX, fetched from the relay | `group_fetch_route` | +### Planning on the map + +The Explore screen ([`Explore.tsx`](../../web/src/ui/Explore.tsx)) keeps a plan: the waypoints, and a style for each section between them (`styles[i]` is the section from waypoint `i`). Every change (adding, inserting, moving or removing a waypoint, reversing, changing a style) is one step on an undo list, and the plan is sent to `geo_plan` 300 ms after the last change. + +**Styles** are BRouter profiles, listed in `planner::STYLES`: + +| Shown as | Profile | +|---|---| +| Road bike | `fastbike` | +| Quiet roads | `fastbike-verylowtraffic` | +| Gravel | `gravel` | +| Touring | `trekking` | +| Safest | `safety` | +| Mountain bike | `mtb` | + +An unknown name falls back to `fastbike`. + +**Sections are planned one at a time** (`geo::plan`). Each section is one BRouter request, asked for as GeoJSON, four at once. The reply is read by `planner::parse_brouter` into a `Leg`: the points with their heights, and *stretches*, each running to a point index with the OSM tags of its way. Those come from BRouter's `messages` table, whose rows end at a point of the line. Each section is kept in memory by style and end points (`SECTIONS`, up to 400), so moving one waypoint only plans the two sections that touch it. + +`planner::join` puts the sections end to end, keeping their shared point once. That gives the GPX and the route, built like any other. From the joined leg: + +- **The breakdown** (`planner::breakdown`): each stretch is classified by `classify` into a surface (paved, cobbles, gravel, dirt, not mapped) and a kind of way (main road, minor road, cycle path, track, path). The surface comes from `surface=` through `Surface::from_osm`, from `tracktype=` on a track, and is taken as paved on an untagged road. Neighbouring stretches of the same kind become one *run*, with its own thinned line, so the map can colour the route by either. The shares are in metres, largest first. +- **The outline** (`planner::outline`): the thinned line for the map, keeping the points where sections meet. `ends` says where they are, so the page can tell which section a point on the line belongs to, and dragging the line inserts a waypoint into that section. +- **The time** (`planner::ride_time`): the route ridden in the app's own physics at three quarters of the rider's FTP, with their weight, bike, CdA and rolling resistance. With road surfaces on in Settings, each surface's rolling factor counts too (`rolling_lookup`), so gravel is slower. Waymarked and Strava routes get a time too, on tarmac. + +**Loops** (`geo::round_trip`) use BRouter's round-trip mode (`engineMode=4`) with a radius and a heading. A loop comes out about 6.4 times the radius (`planner::round_trip_radius`); if one is more than 20% off the distance asked for, it's asked again once with the radius corrected. The loop is then cut into 4 to 12 waypoints about an eighth of its length apart (`planner::loop_waypoints`), and each piece is put in the section memory under its style and ends. So the page gets back ordinary waypoints, planning them gives exactly the loop, and the rider can edit it like any route. **Try another** turns the heading a little each time, or picks a new one at random. + ### Waymarked routes `area_query` asks Overpass for route relations of one kind in the bounds (route relations only: a superroute such as a EuroVelo route holds other relations, not ways). The area may be about 60 km across at most (0.6° by 0.9°). Anything bigger holds too many routes for a public server, and the app asks the rider to zoom in. At most 60 routes are listed. diff --git a/docs/wiki/Routes-and-the-map.md b/docs/wiki/Routes-and-the-map.md index a437427..ef718af 100644 --- a/docs/wiki/Routes-and-the-map.md +++ b/docs/wiki/Routes-and-the-map.md @@ -17,11 +17,44 @@ Press **Import GPX…**, or drag files onto the window. Any GPX works: exports f Open **Find a route**. 1. Search for a place, or move the map there. -2. Click to add waypoints from start to finish. Drag one to move it; click it to remove it. -3. The route follows bike-friendly roads between them, with real heights. **Prefer** picks the kind of roads: **Road bike (fast roads)**, **Quiet roads and lanes**, **Safest (avoid traffic)**, or **Mountain bike (trails)** for tracks and singletrack. -4. Give it a name and press **Save to library**. +2. Pick a **Style for new sections**: + - **Road bike:** fast, direct roads. + - **Quiet roads:** lanes and minor roads, away from traffic. + - **Gravel:** gravel roads and good tracks where there are some. + - **Touring:** a mix of quiet roads, cycle paths and good tracks. + - **Safest:** cycle paths and the quietest roads, even if it's longer. + - **Mountain bike:** trails and paths. +3. Click to add waypoints from start to finish. The route follows the roads between them, with real heights. +4. Change it: + - **Drag the route** to pull in a new waypoint between two others. + - **Drag a waypoint** to move it. **Click one** to remove it. + - Under **Sections**, each stretch between two waypoints has its own style. So you can ride the lanes out, take a gravel track across, and come home on the main road. +5. Give it a name and press **Save to library**. -**Undo**, **Reverse** and **Clear** do what they say. +The buttons: + +- **Undo** and **Redo** (also ⌘Z and ⇧⌘Z, or Ctrl+Z and Ctrl+Shift+Z). +- **Reverse** rides it the other way. +- **Close the loop** adds a way back from the finish to the start. +- **Out and back** rides back the way you came. +- **Clear** starts again. + +### Make a loop + +Under **Make a loop**, choose how far and which way to head off (or **Any way**), and press **Make a loop**. You get a round trip from your first waypoint, or from the middle of the map if you haven't added one, in the style for new sections. Don't like it? **Try another** gives a different one from the same place. + +The loop comes as ordinary waypoints, so you can drag it, move them or change a section's style like any route. + +### What the route is made of + +Under the route's distance and climbing you'll find: + +- **About how long it takes** at three quarters of your FTP, worked out with the same physics as your rides: your weight, your bike and the hills. With **Road surfaces** on in Settings, gravel and cobbles slow it down too. +- **The elevation profile**, with the climbs shaded, and a list of the climbs. +- **Surface:** how much is paved, cobbles, gravel or dirt, and how much isn't mapped. +- **Road type:** how much is on main roads, minor roads, cycle paths, tracks and paths. + +Point at a surface or road type to show where it is on the map, or press **Surface** or **Road type** beside **On the map** to colour the whole route by it. ![Find a route](https://raw.githubusercontent.com/pepperstm/velopopuli/main/docs/images/screen-explore.jpg) diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 86d534f..4101008 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -578,7 +578,7 @@ pub async fn connector_route(state: State<'_, AppState>, id: String, route_id: S let gpx = connectors::get(&id)?.route_gpx(&state.connector_ctx(), &route_id).await?; let (name, raw) = parse_gpx(&gpx)?; let route = build_route(&name, &raw)?; - Ok(Planned::new(gpx, &route, Some(name).filter(|n| !n.trim().is_empty()), 0, false)) + Ok(Planned::new(gpx, &route, Some(name).filter(|n| !n.trim().is_empty()), 0, false, &state.store.get::("settings").unwrap_or_default())) } #[tauri::command] @@ -881,6 +881,7 @@ pub struct Planned { distance: f64, ascent: f64, climbs: usize, + climb_list: Vec, /// `[lat, lon]` outline and `[distance, elevation]` profile, thinned for drawing. line: Vec<[f64; 2]>, profile: Vec<[f64; 2]>, @@ -890,30 +891,90 @@ pub struct Planned { gaps: usize, /// Only the part of a waymarked route in the area searched. clipped: bool, + /// For a route planned on the map: where each waypoint falls in `line`, and how long each + /// section between them is. + ends: Vec, + sections: Vec, + /// What the route is made of, when the planner said. + breakdown: Option, + estimate: Estimate, +} + +/// How long the route would take at an easy endurance effort. +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Estimate { + seconds: f64, + watts: f64, +} + +/// Three quarters of the rider's FTP, to the nearest 5 W: a steady endurance pace. +fn estimate(route: &Route, settings: &Settings, rolling: impl Fn(f64) -> f64) -> Estimate { + let watts = ((settings.rider.ftp * 0.75) / 5.0).round() * 5.0; + let params = velopopuli_core::physics::PhysicsParams { + mass: settings.rider.weight_kg + settings.rider.bike_kg, + crr: settings.physics.crr, + cda: settings.physics.cda, + max_speed: settings.physics.max_speed_kph / 3.6, + }; + let surfaces = settings.physics.road_surfaces; + Estimate { seconds: velopopuli_core::planner::ride_time(route, watts.max(50.0), ¶ms, |d| if surfaces { rolling(d) } else { 1.0 }), watts } } impl Planned { - fn new(gpx: String, route: &Route, name: Option, gaps: usize, clipped: bool) -> Self { + fn new(gpx: String, route: &Route, name: Option, gaps: usize, clipped: bool, settings: &Settings) -> Self { let stride = (route.n / 600).max(1); Planned { distance: route.total, ascent: route.ascent, climbs: route.climbs.len(), + climb_list: route.climbs.clone(), line: route.preview_outline(1500), profile: (0..route.n).step_by(stride).map(|i| [i as f64 * route.step, route.ele[i] as f64]).collect(), gpx, name, gaps, clipped, + ends: Vec::new(), + sections: Vec::new(), + breakdown: None, + estimate: estimate(route, settings, |_| 1.0), + } + } + + /// A route planned on the map, section by section. + fn from_sections(legs: &[velopopuli_core::planner::Leg], settings: &Settings) -> Res { + use velopopuli_core::planner; + let joined = planner::join(legs); + let route = build_route("Planned route", &joined.raw_points())?; + let gpx = velopopuli_core::waymarked::to_gpx("Planned route", &joined.points); + let mut ends = vec![0]; + for leg in legs { + ends.push(ends.last().unwrap() + leg.points.len().saturating_sub(1)); } + let breakdown = planner::breakdown(&joined, 3000); + let (line, ends) = planner::outline(&joined, &ends, 1500); + let estimate = estimate(&route, settings, planner::rolling_lookup(&breakdown, route.total)); + Ok(Planned { line, ends, sections: legs.iter().map(planner::Leg::length).collect(), breakdown: Some(breakdown), estimate, ..Planned::new(gpx, &route, None, 0, false, settings) }) } } +/// Plans a route through `[lat, lon]` waypoints, each section in its own style (`styles[i]` +/// from waypoint i; missing ones take the last). +#[tauri::command] +pub async fn geo_plan(state: State<'_, AppState>, points: Vec<[f64; 2]>, styles: Vec) -> Res { + let legs = geo::plan(&state.http, &points, &styles).await?; + Planned::from_sections(&legs, &state.store.get::("settings").unwrap_or_default()) +} + +/// Waypoints for a loop of about `distance` metres from `start`, heading off towards +/// `direction` (degrees from north). Planning them gives the loop. #[tauri::command] -pub async fn geo_plan(state: State<'_, AppState>, points: Vec<[f64; 2]>, profile: String) -> Res { - let gpx = geo::plan(&state.http, &points, &profile).await?; - let route = build_route("Planned", &parse_gpx(&gpx)?.1)?; - Ok(Planned::new(gpx, &route, None, 0, false)) +pub async fn geo_round_trip(state: State<'_, AppState>, start: [f64; 2], distance: f64, direction: f64, style: String) -> Res> { + if !(2_000.0..=300_000.0).contains(&distance) { + return Err("Choose a loop between 2 and 300 km.".into()); + } + geo::round_trip(&state.http, start, distance, direction, &style).await } /// The waymarked routes of a kind (mountain-bike or road) within `[south, west, north, east]`. @@ -938,7 +999,7 @@ pub async fn geo_waymarked_route(state: State<'_, AppState>, kind: velopopuli_co let stride = ((20.0 / route.step).round() as usize).max(1); let points: Vec<([f64; 2], Option)> = (0..route.n).step_by(stride).chain([route.n - 1]).map(|i| ([route.lat[i], route.lon[i]], dem.as_ref().map(|_| route.ele[i] as f64))).collect(); let gpx = velopopuli_core::waymarked::to_gpx(&way.name, &points); - Ok(Planned::new(gpx, &route, Some(way.name), way.gaps, way.clipped)) + Ok(Planned::new(gpx, &route, Some(way.name), way.gaps, way.clipped, &state.store.get::("settings").unwrap_or_default())) } /// Street-level photos along the route being ridden. @@ -1014,6 +1075,8 @@ pub struct SmokeConfig { laps: Option, /// Ride this route instead of the newest in the library (VP_SMOKE_ROUTE, e.g. `herne-hill`). route: Option, + /// On the Explore screen, plan `lat,lon;lat,lon;…` or make `loop:lat,lon,km` (VP_SMOKE_PLAN). + plan: Option, } /// Automated check only: saves window frame `index` as `.frames/NNNN.png`, for demo clips. @@ -1045,6 +1108,7 @@ pub fn smoke_config() -> Option { scroll: std::env::var("VP_SMOKE_SCROLL").ok(), laps: std::env::var("VP_SMOKE_LAPS").ok().and_then(|v| v.parse().ok()), route: std::env::var("VP_SMOKE_ROUTE").ok(), + plan: std::env::var("VP_SMOKE_PLAN").ok(), }) } diff --git a/src-tauri/src/geo.rs b/src-tauri/src/geo.rs index 7e1de27..4815cf4 100644 --- a/src-tauri/src/geo.rs +++ b/src-tauri/src/geo.rs @@ -1,8 +1,14 @@ //! Finding places and planning routes inside the app: place search through -//! OpenStreetMap's Nominatim, bike routing (with elevation) through BRouter, and -//! waymarked mountain-bike routes through the Overpass API. +//! OpenStreetMap's Nominatim, bike routing through BRouter (with elevation, section by +//! section, and loops), and waymarked routes through the Overpass API. +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; +use std::time::Duration; + +use futures::StreamExt; use serde::Serialize; +use velopopuli_core::planner::{self, Leg}; use velopopuli_core::waymarked::Kind; #[derive(Serialize)] @@ -38,28 +44,99 @@ pub async fn search(http: &reqwest::Client, query: &str) -> Result, S .collect()) } -/// Routes through the given `[lat, lon]` waypoints and returns the GPX (with elevation). -pub async fn plan(http: &reqwest::Client, points: &[[f64; 2]], profile: &str) -> Result { - if points.len() < 2 { - return Err("Add at least a start and a finish.".into()); - } - if points.len() > 30 { - return Err("Use at most 30 waypoints.".into()); +/// Sections already planned, by style and end points, so moving one waypoint only plans the +/// two sections that touch it again. Loops made by `round_trip` are put here in pieces too. +static SECTIONS: OnceLock>> = OnceLock::new(); +/// Enough for a few long routes and their edits; past it the oldest are dropped. +const SECTIONS_KEPT: usize = 400; + +fn section_key(style: &str, from: [f64; 2], to: [f64; 2]) -> String { + format!("{style}|{:.6},{:.6}|{:.6},{:.6}", from[0], from[1], to[0], to[1]) +} + +fn remember(key: String, leg: Leg) { + let mut cache = SECTIONS.get_or_init(Mutex::default).lock().unwrap(); + if cache.len() >= SECTIONS_KEPT { + cache.clear(); } - let profile = match profile { - "trekking" | "safety" | "fastbike" | "mtb" => profile, - _ => "fastbike", - }; - let lonlats = points.iter().map(|p| format!("{:.6},{:.6}", p[1], p[0])).collect::>().join("|"); - let url = format!("https://brouter.de/brouter?lonlats={lonlats}&profile={profile}&alternativeidx=0&format=gpx"); - let res = http.get(url).timeout(std::time::Duration::from_secs(60)).send().await.map_err(|e| format!("Could not reach the route planner: {e}"))?; + cache.insert(key, leg); +} + +fn recall(key: &str) -> Option { + SECTIONS.get_or_init(Mutex::default).lock().unwrap().get(key).cloned() +} + +async fn brouter(http: &reqwest::Client, query: &str) -> Result { + let url = format!("https://brouter.de/brouter?{query}&alternativeidx=0&format=geojson"); + let res = http.get(url).timeout(Duration::from_secs(60)).send().await.map_err(|e| format!("Could not reach the route planner: {e}"))?; let status = res.status(); let text = res.text().await.map_err(|e| e.to_string())?; - if !status.is_success() || !text.contains("(); - return Err(format!("No route found between those points{}", if reason.is_empty() { ".".into() } else { format!(": {reason}") })); + return Err(if reason.is_empty() { "no route".into() } else { reason }); + } + planner::parse_brouter(&text) +} + +/// Waypoint names as the map shows them: S, 1, 2, …, F. +fn label(i: usize, count: usize) -> String { + match i { + 0 => "S".into(), + i if i + 1 == count => "F".into(), + i => i.to_string(), } - Ok(text) +} + +/// Plans each section between `[lat, lon]` waypoints in its own style (`styles[i]` for the +/// section from waypoint i; a missing one takes the last given), reusing sections already planned. +pub async fn plan(http: &reqwest::Client, points: &[[f64; 2]], styles: &[String]) -> Result, String> { + if points.len() < 2 { + return Err("Add at least a start and a finish.".into()); + } + if points.len() > 40 { + return Err("Use at most 40 waypoints.".into()); + } + let style_of = |i: usize| planner::style(styles.get(i).or(styles.last()).map_or("", String::as_str)); + let sections = (0..points.len() - 1).map(|i| async move { + let key = section_key(style_of(i), points[i], points[i + 1]); + if let Some(leg) = recall(&key) { + return Ok(leg); + } + let lonlats = format!("{:.6},{:.6}|{:.6},{:.6}", points[i][1], points[i][0], points[i + 1][1], points[i + 1][0]); + match brouter(http, &format!("lonlats={lonlats}&profile={}", style_of(i))).await { + Ok(leg) => { + remember(key, leg.clone()); + Ok(leg) + } + Err(e) => Err(format!("No route found from {} to {}: {e}", label(i, points.len()), label(i + 1, points.len()))), + } + }); + // A few at a time: the planner is a free public service. + futures::stream::iter(sections).buffered(4).collect::>().await.into_iter().collect() +} + +/// A loop of about `distance` metres from `start`, heading off towards `direction` (degrees +/// from north), as waypoints to plan and edit like any route. Its sections are remembered, so +/// planning those waypoints gives back the loop as it was made. +pub async fn round_trip(http: &reqwest::Client, start: [f64; 2], distance: f64, direction: f64, style: &str) -> Result, String> { + let style = planner::style(style); + let ask = |radius: f64| format!("lonlats={:.6},{:.6}&profile={style}&engineMode=4&roundTripDistance={:.0}&direction={:.0}", start[1], start[0], radius, direction.rem_euclid(360.0)); + let failed = |e: String| format!("No loop found from here: {e}"); + let mut radius = planner::round_trip_radius(distance); + let mut leg = brouter(http, &ask(radius)).await.map_err(failed)?; + // The roads decide how long a loop really comes out; one more try gets closer. + let length = leg.length(); + if length > 0.0 && (length / distance - 1.0).abs() > 0.2 { + radius = (radius * distance / length).clamp(500.0, 60_000.0); + if let Ok(again) = brouter(http, &ask(radius)).await { + leg = again; + } + } + let waypoints = planner::loop_waypoints(&leg, distance / 8.0); + for w in waypoints.windows(2) { + remember(section_key(style, w[0].1, w[1].1), leg.slice(w[0].0, w[1].0)); + } + Ok(waypoints.into_iter().map(|(_, p)| p).collect()) } /// The waymarked routes of a kind within `[south, west, north, east]`. @@ -103,7 +180,7 @@ pub const CLASSICS: &[Classic] = &[ #[cfg(test)] mod tests { - use velopopuli_core::gpx::{build_route, parse_gpx}; + use velopopuli_core::gpx::build_route; use velopopuli_core::waymarked::Kind; /// Needs the network: `cargo test -p velopopuli -- --ignored`. @@ -114,13 +191,30 @@ mod tests { let found = super::search(&http, "Bourg d'Oisans").await.unwrap(); assert!(found.iter().any(|p| (p.lat - 45.05).abs() < 0.05), "{}", found.len()); for c in super::CLASSICS { - let gpx = super::plan(&http, c.points, "fastbike").await.unwrap(); - let route = build_route(c.name, &parse_gpx(&gpx).unwrap().1).unwrap(); + let legs = super::plan(&http, c.points, &["fastbike".to_string()]).await.unwrap(); + assert_eq!(legs.len(), c.points.len() - 1); + let route = build_route(c.name, &velopopuli_core::planner::join(&legs).raw_points()).unwrap(); println!("{}: {:.1} km, {:.0} m up, {} climbs", c.name, route.total / 1000.0, route.ascent, route.climbs.len()); assert!(route.ascent > 100.0 && route.climbs.len() >= 1, "{}", c.name); } } + /// Needs the network: `cargo test -p velopopuli -- --ignored`. + #[tokio::test] + #[ignore] + async fn makes_loops_that_plan_back_as_they_were() { + let http = reqwest::Client::builder().user_agent("VeloPopuli/0.2 (open-source indoor cycling app)").build().unwrap(); + // Bovey Tracey, Devon: about 40 km, heading east. + let start = [50.577, -3.676]; + let points = super::round_trip(&http, start, 40_000.0, 90.0, "fastbike").await.unwrap(); + assert!((5..=14).contains(&points.len()), "{}", points.len()); + assert_eq!(points.first(), points.last()); + let legs = super::plan(&http, &points, &["fastbike".to_string()]).await.unwrap(); + let length = velopopuli_core::planner::join(&legs).length(); + println!("loop: {} waypoints, {:.1} km", points.len(), length / 1000.0); + assert!((28_000.0..52_000.0).contains(&length), "{length}"); + } + /// Needs the network: `cargo test -p velopopuli -- --ignored`. #[tokio::test] #[ignore] diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 3eb24f2..cecef1b 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -160,6 +160,7 @@ fn main() { commands::smart_test, commands::geo_search, commands::geo_plan, + commands::geo_round_trip, commands::geo_classics, commands::geo_waymarked_routes, commands::geo_waymarked_route, diff --git a/web/src/bridge.ts b/web/src/bridge.ts index 9a9a146..e5ac1ec 100644 --- a/web/src/bridge.ts +++ b/web/src/bridge.ts @@ -13,6 +13,7 @@ import type { GearPreview, GearSettings, GhostMeta, + Planned, RideInit, RideRequest, RideSearch, @@ -100,18 +101,7 @@ export const api = { /** The rider's saved routes on the service. */ routes: (id: string) => invoke('connector_routes', { id }), /** One saved route, ready to preview and save like a planned one. */ - route: (id: string, routeId: string) => - invoke<{ - gpx: string - distance: number - ascent: number - climbs: number - line: [number, number][] - profile: [number, number][] - name: string | null - gaps: number - clipped: boolean - }>('connector_route', { id, routeId }), + route: (id: string, routeId: string) => invoke('connector_route', { id, routeId }), /** Every ride the rider has on the service, newest first, with a preview of each. */ rideList: (id: string) => invoke('connector_ride_list', { id }) }, @@ -148,11 +138,11 @@ export const api = { fitness: () => invoke('fitness_overview'), geo: { search: (query: string) => invoke<{ name: string; detail: string; lat: number; lon: number }[]>('geo_search', { query }), - plan: (points: [number, number][], profile: string) => - invoke<{ gpx: string; distance: number; ascent: number; climbs: number; line: [number, number][]; profile: [number, number][] }>('geo_plan', { - points, - profile - }), + /** Plans through the waypoints, the section from waypoint i in `styles[i]` (missing ones take the last). */ + plan: (points: [number, number][], styles: string[]) => invoke('geo_plan', { points, styles }), + /** Waypoints for a loop of about `distance` metres from `start`, heading off towards `direction` (degrees from north). */ + roundTrip: (start: [number, number], distance: number, direction: number, style: string) => + invoke<[number, number][]>('geo_round_trip', { start, distance, direction, style }), classics: () => invoke<{ name: string; region: string; points: [number, number][] }[]>('geo_classics'), /** Waymarked routes of a kind (mountain-bike or signposted road) within `[south, west, north, east]`. */ waymarkedRoutes: (kind: 'mtb' | 'road', bounds: [number, number, number, number]) => @@ -161,18 +151,7 @@ export const api = { { kind, bounds } ), /** One waymarked route, joined into a line with elevation, ready to save. A road route is cut down to its part within `bounds`. */ - waymarkedRoute: (kind: 'mtb' | 'road', id: number, bounds: [number, number, number, number]) => - invoke<{ - gpx: string - distance: number - ascent: number - climbs: number - line: [number, number][] - profile: [number, number][] - name: string | null - gaps: number - clipped: boolean - }>('geo_waymarked_route', { kind, id, bounds }) + waymarkedRoute: (kind: 'mtb' | 'road', id: number, bounds: [number, number, number, number]) => invoke('geo_waymarked_route', { kind, id, bounds }) }, group: { fetchRoute: (room: string) => invoke('group_fetch_route', { room }) @@ -195,6 +174,7 @@ export const api = { scroll: string | null laps: number | null route: string | null + plan: string | null } | null>('smoke_config'), frame: (index: number) => invoke('smoke_frame', { index }), done: (png: string | null, info: string) => invoke('smoke_done', { png, info }) diff --git a/web/src/styles.css b/web/src/styles.css index 952d5e8..71b40c4 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -1273,6 +1273,99 @@ button.small { flex-direction: column; gap: 8px; } +.chart.elevation .climb { + fill: rgba(255, 159, 67, 0.18); +} +.wp.ghost { + opacity: 0.8; +} +.leaflet-interactive.route-grab { + cursor: copy; +} +.row.wrap { + flex-wrap: wrap; +} +.card.make-loop, +.card.sections { + display: flex; + flex-direction: column; + gap: 8px; +} +.card.make-loop h2 { + margin: 0; +} +.make-loop input[type='number'] { + width: 70px; + flex: none; +} +.make-loop select { + flex: 1; + min-width: 0; +} +.section-row { + display: grid; + grid-template-columns: 70px 64px 1fr; + align-items: center; + gap: 8px; +} +.section-ends { + font-weight: 700; + font-size: 13px; +} +.climb-list { + margin: 0; + padding-left: 18px; + display: flex; + flex-direction: column; + gap: 2px; +} +.colour-by { + align-items: center; + gap: 6px; +} +.colour-by button.on { + background: var(--accent); + color: var(--accent-ink); +} +.shares { + display: flex; + flex-direction: column; + gap: 4px; +} +.share-bar { + display: flex; + height: 8px; + border-radius: 4px; + overflow: hidden; + gap: 1px; +} +.share-legend { + list-style: none; + margin: 0; + padding: 0; + font-size: 13px; +} +.share-legend li { + display: grid; + grid-template-columns: 12px 1fr auto 40px; + align-items: center; + gap: 8px; + padding: 2px 4px; + border-radius: 4px; + cursor: default; +} +.share-legend li.on, +.share-legend li:hover { + background: var(--panel-2); +} +.share-legend i { + width: 10px; + height: 10px; + border-radius: 2px; +} +.share-legend span { + text-align: right; +} .ok { color: var(--ok); } diff --git a/web/src/types.ts b/web/src/types.ts index 5566ba9..a8769d8 100644 --- a/web/src/types.ts +++ b/web/src/types.ts @@ -94,6 +94,39 @@ export const DEFAULT_SETTINGS: Settings = { } } +export type SurfaceClass = 'paved' | 'cobbles' | 'gravel' | 'dirt' | 'unknown' +export type WayClass = 'mainRoad' | 'minorRoad' | 'cyclePath' | 'track' | 'path' + +/** What a planned route is made of: how much of each surface and kind of way, and where. */ +export interface Breakdown { + surfaces: { class: SurfaceClass; metres: number }[] + ways: { class: WayClass; metres: number }[] + runs: { surface: SurfaceClass; way: WayClass; from: number; to: number; line: [number, number][] }[] +} + +/** A route ready to preview and save: planned on the map, a waymarked route, or one from a service. */ +export interface Planned { + gpx: string + distance: number + ascent: number + climbs: number + climbList: Climb[] + /** `[lat, lon]` outline and `[distance, elevation]` profile, thinned for drawing. */ + line: [number, number][] + profile: [number, number][] + name: string | null + /** Where a waymarked route's mapped ways don't meet. */ + gaps: number + /** Only the part of a waymarked route in the area searched. */ + clipped: boolean + /** Planned on the map: where each waypoint falls in `line`, and each section's length. */ + ends: number[] + sections: number[] + breakdown: Breakdown | null + /** How long it takes at an easy endurance effort (three quarters of FTP). */ + estimate: { seconds: number; watts: number } +} + export interface RouteMeta { id: string name: string diff --git a/web/src/ui/Explore.tsx b/web/src/ui/Explore.tsx index 3d25da9..1409fc9 100644 --- a/web/src/ui/Explore.tsx +++ b/web/src/ui/Explore.tsx @@ -2,9 +2,10 @@ import { useEffect, useRef, useState } from 'react' import L from 'leaflet' import 'leaflet/dist/leaflet.css' import { errorText } from '../bridge' -import { fmtDist, fmtEle } from '../core/fmt' +import { distUnit, fmtDist, fmtEle, type Units } from '../core/fmt' import { api, useSettings } from '../state' -import type { ConnectorEntry, RemoteRoute, RouteList, RouteMeta } from '../types' +import type { Climb } from '../core/gpx' +import type { ConnectorEntry, Planned, RemoteRoute, RouteList, RouteMeta, SurfaceClass, WayClass } from '../types' interface Place { name: string @@ -19,19 +20,7 @@ interface Classic { points: [number, number][] } -interface Planned { - gpx: string - distance: number - ascent: number - climbs: number - line: [number, number][] - profile: [number, number][] - /** Where a waymarked route's mapped ways don't meet. */ - gaps?: number - /** Only the part of a waymarked route in the area searched. */ - clipped?: boolean -} - +type LatLon = [number, number] type Kind = 'mtb' | 'road' type Bounds = [number, number, number, number] @@ -53,7 +42,7 @@ const KINDS: { kind: Kind; title: string; about: string; find: string; looking: about: 'Waymarked trails mapped in OpenStreetMap, in the area on the map.', find: 'Find MTB routes here', looking: 'Looking for mountain-bike routes…', - none: 'No waymarked mountain-bike routes here. Try another area, or plan one with “Mountain bike (trails)”.', + none: 'No waymarked mountain-bike routes here. Try another area, or plan one with the “Mountain bike” style.', numbered: 'MTB route' } ] @@ -69,14 +58,71 @@ interface WaymarkedRoute { const NETWORKS: Record = { lcn: 'local', rcn: 'regional', ncn: 'national', icn: 'international' } -const PROFILES = [ - { id: 'fastbike', label: 'Road bike (fast roads)' }, - { id: 'trekking', label: 'Quiet roads and lanes' }, - { id: 'safety', label: 'Safest (avoid traffic)' }, - { id: 'mtb', label: 'Mountain bike (trails)' } +/** Routing styles, as BRouter profiles: the same list as `planner::STYLES` in Rust. */ +const STYLES = [ + { id: 'fastbike', label: 'Road bike', hint: 'Fast, direct roads' }, + { id: 'fastbike-verylowtraffic', label: 'Quiet roads', hint: 'Lanes and minor roads, away from traffic' }, + { id: 'gravel', label: 'Gravel', hint: 'Gravel roads and good tracks where there are some' }, + { id: 'trekking', label: 'Touring', hint: 'A mix of quiet roads, cycle paths and good tracks' }, + { id: 'safety', label: 'Safest', hint: 'Cycle paths and the quietest roads, even if longer' }, + { id: 'mtb', label: 'Mountain bike', hint: 'Trails and paths' } +] + +const SURFACES: Record = { + paved: { label: 'Paved', colour: '#d4ee2a' }, + cobbles: { label: 'Cobbles', colour: '#ff9f43' }, + gravel: { label: 'Gravel', colour: '#c9a36b' }, + dirt: { label: 'Dirt and grass', colour: '#a0673a' }, + unknown: { label: 'Not mapped', colour: '#7d8590' } +} + +const WAYS: Record = { + mainRoad: { label: 'Main roads', colour: '#ff6b6b' }, + minorRoad: { label: 'Minor roads', colour: '#d4ee2a' }, + cyclePath: { label: 'Cycle paths', colour: '#4ddb8a' }, + track: { label: 'Tracks', colour: '#c9a36b' }, + path: { label: 'Paths', colour: '#b38bff' } +} + +const DIRECTIONS: { label: string; degrees: number | null }[] = [ + { label: 'Any way', degrees: null }, + { label: 'North', degrees: 0 }, + { label: 'North-east', degrees: 45 }, + { label: 'East', degrees: 90 }, + { label: 'South-east', degrees: 135 }, + { label: 'South', degrees: 180 }, + { label: 'South-west', degrees: 225 }, + { label: 'West', degrees: 270 }, + { label: 'North-west', degrees: 315 } ] -function Elevation({ profile }: { profile: [number, number][] }): React.JSX.Element | null { +/** "Try another" in a chosen direction turns a little each time, so each loop is different. */ +const NUDGES = [0, 25, -25, 50, -50, 75, -75] + +/** The waypoints, and the style of each section between them (`styles[i]` from waypoint i). */ +interface Plan { + points: LatLon[] + styles: string[] +} + +const EMPTY: Plan = { points: [], styles: [] } + +/** How a waypoint is shown on the map: S, 1, 2, …, F. */ +function waypointLabel(i: number, count: number): string { + return i === 0 ? 'S' : i === count - 1 ? 'F' : String(i) +} + +function fmtDuration(s: number): string { + const minutes = Math.max(1, Math.round(s / 60)) + const h = Math.floor(minutes / 60) + return h ? `${h} h ${String(minutes % 60).padStart(2, '0')} min` : `${minutes} min` +} + +function climbName(c: Climb): string { + return c.category === 'HC' ? 'HC climb' : c.category ? `Cat ${c.category} climb` : 'Climb' +} + +function Elevation({ profile, climbs }: { profile: [number, number][]; climbs: Climb[] }): React.JSX.Element | null { if (profile.length < 2) return null const W = 600 const H = 90 @@ -86,21 +132,74 @@ function Elevation({ profile }: { profile: [number, number][] }): React.JSX.Elem const pts = profile.map(([d, e]) => `${((d / total) * W).toFixed(1)},${(H - ((e - lo) / (hi - lo)) * (H - 6)).toFixed(1)}`) return ( + {climbs.map((c, i) => ( + + ))} ) } -/** Plan a new route on a map, or pick a famous climb. */ +/** How much of the route is each surface (or kind of way): a bar, and a legend that shows it on the map. */ +function Shares({ + title, + shares, + info, + total, + units, + focus, + onFocus +}: { + title: string + shares: { class: T; metres: number }[] + info: Record + total: number + units: Units + focus: string | null + onFocus: (c: T | null) => void +}): React.JSX.Element { + return ( +
+
{title}
+
+ {shares.map((s) => ( + + ))} +
+
    + {shares.map((s) => ( +
  • onFocus(s.class)} onMouseLeave={() => onFocus(null)}> + + {info[s.class].label} + {fmtDist(s.metres, units)} + {Math.round((s.metres / Math.max(1, total)) * 100)}% +
  • + ))} +
+
+ ) +} + +/** Plan a new route on a map, make a loop, or pick one: a famous climb, a waymarked route, one of your own. */ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element { const { settings } = useSettings() const u = settings.units const el = useRef(null) const map = useRef(null) const layer = useRef(null) - const [points, setPoints] = useState<[number, number][]>([]) - const [profile, setProfile] = useState('fastbike') + const [plan, setPlan] = useState(EMPTY) + const [past, setPast] = useState([]) + const [future, setFuture] = useState([]) + /** The style new sections get. */ + const [style, setStyle] = useState('fastbike') const [planned, setPlanned] = useState(null) + /** What the route on the map is coloured by, and the surface or kind of way picked out. */ + const [colourBy, setColourBy] = useState<'route' | 'surface' | 'way'>('route') + const [focus, setFocus] = useState(null) + const [loopDistance, setLoopDistance] = useState(40) + const [loopDirection, setLoopDirection] = useState(null) + /** The last loop made, so "Try another" starts from the same place. */ + const [loop, setLoop] = useState<{ start: LatLon; tries: number } | null>(null) const [query, setQuery] = useState('') const [places, setPlaces] = useState([]) const [classics, setClassics] = useState([]) @@ -114,48 +213,199 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element const [connectors, setConnectors] = useState([]) const [remote, setRemote] = useState>({}) + // The map's handlers are set up once; they read the latest plan and style through these. + const planRef = useRef(plan) + planRef.current = plan + const styleRef = useRef(style) + styleRef.current = style + /** Set when a drag along the route ends, so the click that follows doesn't add a waypoint too. */ + const inserting = useRef(false) + + /** Changes the plan, so that it can be undone. */ + const edit = (change: (p: Plan) => Plan): void => { + const current = planRef.current + const next = change(current) + if (next === current) return + setPast((p) => [...p.slice(-49), current]) + setFuture([]) + planRef.current = next + setPlan(next) + } + const undo = (): void => { + if (!past.length) return + setFuture((f) => [planRef.current, ...f]) + const previous = past[past.length - 1] + setPast((p) => p.slice(0, -1)) + setPlan(previous) + } + const redo = (): void => { + if (!future.length) return + setPast((p) => [...p, planRef.current]) + setPlan(future[0]) + setFuture((f) => f.slice(1)) + } + + const add = (ll: LatLon): void => + edit((p) => (p.points.length ? { points: [...p.points, ll], styles: [...p.styles, styleRef.current] } : { points: [ll], styles: [] })) + /** A waypoint in the middle of section `i`, which is split in two of the same style. */ + const insert = (i: number, ll: LatLon): void => + edit((p) => ({ + points: [...p.points.slice(0, i + 1), ll, ...p.points.slice(i + 1)], + styles: [...p.styles.slice(0, i + 1), p.styles[i] ?? styleRef.current, ...p.styles.slice(i + 1)] + })) + const move = (i: number, ll: LatLon): void => edit((p) => ({ ...p, points: p.points.map((q, k) => (k === i ? ll : q)) })) + /** Removing a waypoint joins the sections either side into one, in the first one's style. */ + const remove = (i: number): void => + edit((p) => { + const n = p.points.length + const drop = i === 0 ? 0 : i === n - 1 ? n - 2 : i + return { points: p.points.filter((_, k) => k !== i), styles: n <= 2 ? [] : p.styles.filter((_, k) => k !== drop) } + }) + const same = (a: LatLon, b: LatLon): boolean => a[0] === b[0] && a[1] === b[1] + const isLoop = plan.points.length > 2 && same(plan.points[0], plan.points[plan.points.length - 1]) + useEffect(() => { const m = L.map(el.current!, { zoomControl: true }).setView([46.2, 7.2], 6) m.attributionControl.setPrefix(false) L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 18, attribution: '© OpenStreetMap contributors' }).addTo(m) layer.current = L.layerGroup().addTo(m) - m.on('click', (e: L.LeafletMouseEvent) => setPoints((p) => [...p, [e.latlng.lat, e.latlng.lng]])) + m.on('click', (e: L.LeafletMouseEvent) => { + if (inserting.current) { + inserting.current = false + return + } + add([e.latlng.lat, e.latlng.lng]) + }) map.current = m void api.geo.classics().then(setClassics) + // Automated check: plan waypoints, or make a loop, as soon as the map is up. + void api.smoke.config().then((smoke) => { + const spec = smoke?.plan + if (!spec) return + const nums = (s: string): number[] => s.split(',').map(Number) + if (spec.startsWith('loop:')) { + const [lat, lon, km] = nums(spec.slice(5)) + m.setView([lat, lon], 11) + void api.geo.roundTrip([lat, lon], km * 1000, 90, styleRef.current).then((points) => { + edit(() => ({ points, styles: points.slice(1).map(() => styleRef.current) })) + m.fitBounds(L.latLngBounds(points).pad(0.15)) + }) + } else { + const points = spec.split(';').map((p) => nums(p) as LatLon) + edit(() => ({ points, styles: points.slice(1).map(() => styleRef.current) })) + m.fitBounds(L.latLngBounds(points).pad(0.3)) + } + }) void api.connectors.list().then((all) => setConnectors(all.filter((c) => c.listsRoutes && c.status.connected))) return () => { m.remove() map.current = null } + // The handlers read the plan through refs, so the map is made once. + // eslint-disable-next-line react-hooks/exhaustive-deps }, []) - // Draw waypoints and the planned line. + // Undo and redo from the keyboard, when not typing. + useEffect(() => { + const onKey = (e: KeyboardEvent): void => { + if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== 'z') return + const t = e.target as HTMLElement + if (t.tagName === 'INPUT' || t.tagName === 'SELECT' || t.tagName === 'TEXTAREA') return + e.preventDefault() + if (e.shiftKey) redo() + else undo() + } + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }) + + /** Which section of the planned route a point on its line is in. */ + const sectionAt = (p: Planned, ll: L.LatLng): number => { + const k = Math.cos((ll.lat * Math.PI) / 180) + let best = 0 + let bestD = Infinity + p.line.forEach(([lat, lon], i) => { + const d = (lat - ll.lat) ** 2 + ((lon - ll.lng) * k) ** 2 + if (d < bestD) { + bestD = d + best = i + } + }) + const section = p.ends.filter((e) => e <= best).length - 1 + return Math.max(0, Math.min(planRef.current.points.length - 2, section)) + } + + // Draw the route and the waypoints. useEffect(() => { const g = layer.current - if (!g) return + const m = map.current + if (!g || !m) return g.clearLayers() if (planned) { - L.polyline(planned.line, { color: '#24271f', weight: 8, opacity: 0.85 }).addTo(g) - L.polyline(planned.line, { color: '#d4ee2a', weight: 5, opacity: 1 }).addTo(g) + L.polyline(planned.line, { color: '#24271f', weight: 8, opacity: 0.85, interactive: false }).addTo(g) + if (colourBy === 'route' || !planned.breakdown) { + L.polyline(planned.line, { color: '#d4ee2a', weight: 5, opacity: 1, interactive: false }).addTo(g) + } else { + for (const run of planned.breakdown.runs) { + const key = colourBy === 'surface' ? run.surface : run.way + const colour = colourBy === 'surface' ? SURFACES[run.surface].colour : WAYS[run.way].colour + const dim = focus !== null && focus !== key + L.polyline(run.line, { color: colour, weight: focus === key ? 7 : 5, opacity: dim ? 0.25 : 1, interactive: false }).addTo(g) + } + } + // A wide, invisible line along the route to grab: drag from it to add a waypoint there. + if (planned.ends.length === plan.points.length && plan.points.length >= 2) { + const grab = L.polyline(planned.line, { weight: 22, opacity: 0.001, bubblingMouseEvents: false, className: 'route-grab' }) + grab.on('mousedown', (e: L.LeafletMouseEvent) => { + L.DomEvent.stop(e) + const section = sectionAt(planned, e.latlng) + m.dragging.disable() + const ghost = L.marker(e.latlng, { + icon: L.divIcon({ className: 'wp ghost', html: '+', iconSize: [22, 22] }), + interactive: false + }).addTo(g) + const follow = (ev: L.LeafletMouseEvent): void => { + ghost.setLatLng(ev.latlng) + } + const drop = (ev: L.LeafletMouseEvent): void => { + m.off('mousemove', follow) + m.off('mouseup', drop) + m.dragging.enable() + ghost.remove() + inserting.current = true + setTimeout(() => (inserting.current = false), 300) + insert(section, [ev.latlng.lat, ev.latlng.lng]) + } + m.on('mousemove', follow) + m.on('mouseup', drop) + }) + grab.addTo(g) + } } - points.forEach((p, i) => { + plan.points.forEach((p, i) => { + // On a loop the finish is the start: one marker for both. + if (isLoop && i === plan.points.length - 1) return const marker = L.marker(p, { draggable: true, - icon: L.divIcon({ className: 'wp', html: `${i === 0 ? 'S' : i === points.length - 1 ? 'F' : i}`, iconSize: [22, 22] }) + icon: L.divIcon({ className: 'wp', html: `${isLoop && i === 0 ? 'S/F' : waypointLabel(i, plan.points.length)}`, iconSize: [22, 22] }) }) marker.on('dragend', () => { const ll = marker.getLatLng() - setPoints((all) => all.map((q, k) => (k === i ? [ll.lat, ll.lng] : q))) + const at: LatLon = [ll.lat, ll.lng] + // Moving a loop's start moves its finish with it. + if (isLoop && i === 0) edit((q) => ({ ...q, points: q.points.map((x, k) => (k === 0 || k === q.points.length - 1 ? at : x)) })) + else move(i, at) }) - marker.on('click', () => setPoints((all) => all.filter((_, k) => k !== i))) + marker.on('click', () => remove(i)) marker.addTo(g) }) - }, [points, planned]) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [plan, planned, colourBy, focus]) - // Route whenever the waypoints or the profile change. + // Plan whenever the waypoints or the styles change. useEffect(() => { setSaved('') - if (points.length < 2) { + if (plan.points.length < 2) { setPlanned(null) return } @@ -163,16 +413,16 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element const timer = setTimeout(() => { setBusy('Planning the route…') setError('') - api.geo.plan(points, profile).then( + api.geo.plan(plan.points, plan.styles).then( (p) => live && (setPlanned(p), setBusy('')), (err) => live && (setError(errorText(err)), setBusy('')) ) - }, 400) + }, 300) return () => { live = false clearTimeout(timer) } - }, [points, profile]) + }, [plan]) const search = async (): Promise => { if (!query.trim()) return @@ -186,6 +436,39 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element } } + const makeLoop = async (again: boolean): Promise => { + const m = map.current + if (!m) return + const centre = m.getCenter() + const start: LatLon = again && loop ? loop.start : (plan.points[0] ?? [centre.lat, centre.lng]) + const tries = again && loop ? loop.tries + 1 : 0 + const direction = loopDirection === null ? Math.random() * 360 : loopDirection + NUDGES[tries % NUDGES.length] + const metres = loopDistance * (u === 'imperial' ? 1609.344 : 1000) + setBusy('Making a loop…') + setError('') + try { + const points = await api.geo.roundTrip(start, metres, direction, style) + setLoop({ start, tries }) + edit(() => ({ points, styles: points.slice(1).map(() => style) })) + if (!name.trim() || name.startsWith('Loop from')) setName(`Loop from ${(await placeName(start)) ?? 'here'}`) + m.fitBounds(L.latLngBounds(points).pad(0.15)) + } catch (err) { + setError(errorText(err)) + } finally { + setBusy('') + } + } + + /** A short name for the place at a point, from the place search, if it answers. */ + const placeName = async (p: LatLon): Promise => { + try { + const found = await api.geo.search(`${p[0].toFixed(4)}, ${p[1].toFixed(4)}`) + return found[0]?.name || null + } catch { + return null + } + } + const findWaymarked = async (kind: Kind, looking: string): Promise => { const b = map.current?.getBounds() if (!b) return @@ -207,7 +490,7 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element } const pickWaymarked = async (kind: Kind, r: WaymarkedRoute, bounds: Bounds): Promise => { - setPoints([]) + edit(() => EMPTY) setBusy(`Fetching ${r.name} and its elevation…`) setError('') try { @@ -236,7 +519,7 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element } const pickRemote = async (c: ConnectorEntry, r: RemoteRoute): Promise => { - setPoints([]) + edit(() => EMPTY) setBusy(`Fetching ${r.name} from ${c.info.name}…`) setError('') try { @@ -253,7 +536,7 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element const pickClassic = (c: Classic): void => { setName(c.name) - setPoints(c.points) + edit(() => ({ points: c.points, styles: c.points.slice(1).map(() => style) })) map.current?.fitBounds(L.latLngBounds(c.points).pad(0.4)) } @@ -273,12 +556,20 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element } } + const n = plan.points.length + const sectionLengths = planned && planned.sections.length === plan.styles.length ? planned.sections : null + const showOnMap = (by: 'surface' | 'way') => (c: string | null) => { + if (c) setColourBy(by) + setFocus(c) + } + return (

Find a route

- Click the map to add waypoints from start to finish; drag one to move it, click it to remove it. Routing by BRouter, with real elevation. + Click the map to add waypoints from start to finish. Drag the route to add a waypoint in between, drag a waypoint to move it, and click one to remove + it. Routing by BRouter, with real elevation.

void }): React.JSX.Element
)} -
- - + - + +
+ +
+

Make a loop

+

+ A round trip from {n ? 'your start (S)' : 'the middle of the map'}, in the style for new sections. Each one can be changed like any route. +

+
+ setLoopDistance(Math.max(1, Number(e.target.value) || 0))} + aria-label="Loop distance" + /> + {distUnit(u)} + +
+
+ + +
+
+ {busy &&
{busy}
} {error &&
{error}
} + + {n >= 2 && ( +
+
Sections
+ {plan.styles.map((s, i) => ( +
+ + {isLoop && i === 0 ? 'S/F' : waypointLabel(i, n)} → {isLoop && i === n - 2 ? 'S/F' : waypointLabel(i + 1, n)} + + {sectionLengths ? fmtDist(sectionLengths[i], u) : ''} + +
+ ))} + {plan.styles.some((s) => s !== style) && ( + + )} +
+ )} + {planned && (
@@ -337,7 +710,51 @@ export function Explore({ onSaved }: { onSaved: () => void }): React.JSX.Element {planned.climbs} climb{planned.climbs === 1 ? '' : 's'}
- + {planned.estimate.seconds > 0 && ( +
+ About {fmtDuration(planned.estimate.seconds)} at {planned.estimate.watts} W, three quarters of your FTP. +
+ )} + + {planned.climbList.length > 0 && ( +
    + {planned.climbList.slice(0, 8).map((c, i) => ( +
  • + {climbName(c)} from {fmtDist(c.start, u)}: {fmtDist(c.length, u)} at {(c.avgGrade * 100).toFixed(1)}%, ↗ {fmtEle(c.gain, u)} +
  • + ))} +
+ )} + {planned.breakdown && planned.breakdown.runs.length > 0 && ( + <> +
+ On the map: + {(['route', 'surface', 'way'] as const).map((by) => ( + + ))} +
+ + + + )} {!!planned.gaps && (
The map's pieces of this route don't meet in {planned.gaps} place{planned.gaps === 1 ? '' : 's'}; you'll ride straight across