From da10c9481ab9639b39695acd60bbcabd9349ed21 Mon Sep 17 00:00:00 2001 From: pepperstm Date: Thu, 12 Nov 2026 13:41:54 +0000 Subject: [PATCH 1/2] Turn smoothly through corners The rider's heading was taken over a fixed window round the sample behind them, so it held still between samples and jumped at each one: through a corner the rider turned in steps. It's now blended between neighbouring samples, centred where the rider is, in both the page's renderer and the native one. --- src-tauri/src/native/mod.rs | 56 +++++++++++++++++++++++++++++++++++-- web/src/core/gpx.ts | 24 +++++++++++++--- 2 files changed, 74 insertions(+), 6 deletions(-) diff --git a/src-tauri/src/native/mod.rs b/src-tauri/src/native/mod.rs index 3e86236..b51df31 100644 --- a/src-tauri/src/native/mod.rs +++ b/src-tauri/src/native/mod.rs @@ -1486,16 +1486,33 @@ fn sample(route: &velopopuli_core::gpx::Route, dist: f64) -> Pos { let i = (f.floor() as usize).min(route.n - 2); let t = f - i as f64; let lerp = |a: f64, b: f64| a + (b - a) * t; - let (a, b) = (i.saturating_sub(2), (i + 3).min(route.n - 1)); Pos { x: lerp(route.x[i], route.x[i + 1]), z: lerp(route.z[i], route.z[i + 1]), ele: lerp(route.ele[i] as f64, route.ele[i + 1] as f64), grade: lerp(route.grade[i] as f64, route.grade[i + 1] as f64), - heading: (route.x[b] - route.x[a]).atan2(route.z[b] - route.z[a]), + heading: heading_at(route, f), } } +/// The direction of travel at `f` samples along, as the page's `headingAt` gives it: over a +/// ~25 m baseline against GPS jitter, blended between neighbouring samples so a corner turns +/// smoothly rather than in a step at each one. +fn heading_at(route: &velopopuli_core::gpx::Route, f: f64) -> f64 { + // Over samples k-2..k+3, centred on k + 0.5. + let over = |k: usize| { + let (a, b) = (k.saturating_sub(2), (k + 3).min(route.n - 1)); + (route.x[b] - route.x[a]).atan2(route.z[b] - route.z[a]) + }; + let u = (f - 0.5).max(0.0); + let k = (u.floor() as usize).min(route.n - 2); + let s = (u - k as f64).min(1.0); + let h0 = over(k); + // The short way round, across ±π. + let d = (over(k + 1) - h0).sin().atan2((over(k + 1) - h0).cos()); + h0 + d * s +} + /// Ground height from a loaded chunk, if the chunk under the point is in. fn height_at(chunks: &HashMap<(i32, i32), Chunk>, x: f64, z: f64) -> Option { let (chunk, cells) = (LAYOUT.chunk, LAYOUT.cells); @@ -1516,3 +1533,38 @@ fn write_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> Result<(), enc.set_depth(png::BitDepth::Eight); enc.write_header().and_then(|mut wr| wr.write_image_data(rgba)).map_err(|e| e.to_string()) } + +#[cfg(test)] +mod tests { + use velopopuli_core::gpx::{build_route, RawPoint}; + + /// A rider going round a tight circle turns a little for every bit ridden, never in steps, + /// and faces along the road. + #[test] + fn corners_turn_smoothly() { + // Two laps of a 30 m-radius circle, a point every 2°. + let (lat0, lon0, r) = (51.0_f64, 0.0_f64, 30.0); + let m_lat = 111_320.0; + let raw: Vec = (0..=360) + .map(|k| { + let a = (k as f64 * 2.0).to_radians(); + RawPoint { lat: lat0 + r * a.sin() / m_lat, lon: lon0 + r * a.cos() / (m_lat * lat0.to_radians().cos()), ele: None } + }) + .collect(); + let route = build_route("Circle", &raw).unwrap(); + let wrap = |d: f64| d.sin().atan2(d.cos()); + let (from, to, dd) = (20.0, route.total - 20.0, 0.1); + let mut biggest: f64 = 0.0; + let mut d = from; + while d < to { + let (p, q) = (super::sample(&route, d), super::sample(&route, d + dd)); + biggest = biggest.max(wrap(q.heading - p.heading).abs()); + // Facing the way the rider moves. + let moving = (q.x - p.x).atan2(q.z - p.z); + assert!(wrap(p.heading - moving).abs() < 0.15, "at {d:.1} m facing {:.3}, moving {:.3}", p.heading, moving); + d += dd; + } + // Round a 30 m circle, 10 cm turns the rider by 1/300 rad; a step at each sample would be ~50 times that. + assert!(biggest < 3.0 * dd / r, "the heading jumped {biggest:.4} rad in {dd} m"); + } +} diff --git a/web/src/core/gpx.ts b/web/src/core/gpx.ts index 409a0d4..498f9ce 100644 --- a/web/src/core/gpx.ts +++ b/web/src/core/gpx.ts @@ -80,14 +80,30 @@ export function sampleAt(route: Route, dist: number, out?: RoutePos): RoutePos { const i = Math.min(route.n - 2, Math.floor(f)) const t = f - i const lerp = (a: Float64Array): number => a[i] + (a[i + 1] - a[i]) * t - // Heading is taken over a ~25 m baseline so GPS jitter doesn't shake the camera. - const a = Math.max(0, i - 2) - const b = Math.min(route.n - 1, i + 3) const o = out ?? ({} as RoutePos) o.x = lerp(route.x) o.z = lerp(route.z) o.ele = lerp(route.ele) o.grade = lerp(route.grade) - o.heading = Math.atan2(route.x[b] - route.x[a], route.z[b] - route.z[a]) + o.heading = headingAt(route, f) return o } + +/** The direction of travel at `f` samples along, over a ~25 m baseline so GPS jitter doesn't + * shake the camera. Blended between neighbouring samples, so a corner turns smoothly rather + * than in a step at each one. */ +function headingAt(route: Route, f: number): number { + // Over samples k-2..k+3, centred on k + 0.5. + const over = (k: number): number => { + const a = Math.max(0, k - 2) + const b = Math.min(route.n - 1, k + 3) + return Math.atan2(route.x[b] - route.x[a], route.z[b] - route.z[a]) + } + const u = Math.max(0, f - 0.5) + const k = Math.min(route.n - 2, Math.floor(u)) + const s = Math.min(1, u - k) + const h0 = over(k) + // The short way round, across ±π. + const d = Math.atan2(Math.sin(over(k + 1) - h0), Math.cos(over(k + 1) - h0)) + return h0 + d * s +} From 7358b7c0ddf286958f45a587f3c31f54ed65ecbe Mon Sep 17 00:00:00 2001 From: pepperstm Date: Thu, 12 Nov 2026 13:59:32 +0000 Subject: [PATCH 2/2] Ride bends on a smooth curve, and lean into them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The line between route samples was straight, so a tight bend was a kink every 5 m, and the heading was averaged over 25 m, longer than a hairpin. Riders now follow a Catmull-Rom curve through the samples and face along it. Riders also lean into bends by what balances the turn at their speed, atan(v² / g r), up to 40°, on top of any banking. Both renderers. --- src-tauri/src/native/mod.rs | 93 ++++++++++++++++++++++--------------- web/src/core/gpx.ts | 55 ++++++++++++++-------- web/src/world/scene.ts | 11 +++-- 3 files changed, 96 insertions(+), 63 deletions(-) diff --git a/src-tauri/src/native/mod.rs b/src-tauri/src/native/mod.rs index b51df31..2ce4869 100644 --- a/src-tauri/src/native/mod.rs +++ b/src-tauri/src/native/mod.rs @@ -1031,16 +1031,17 @@ impl Renderer { let pose_count = assets.poses.len().max(1); let pose = ((crank.fract() * pose_count as f64) as usize) % pose_count; // On a berm, a rider stands on the slope where they are across the trail and leans with it. - let place = |q: &Pos, d: f64, lane: f64| -> Mat { + // Riders also lean into bends, by what balances the turn at their speed. + let place = |q: &Pos, d: f64, lane: f64, speed: f64| -> Mat { let (bank, lift) = world.bank_at(d, lane); let at = rel([q.x + q.heading.cos() * lane, q.ele + LAYOUT.road_lift + lift, q.z - q.heading.sin() * lane]); - model_rolled(at, q.heading as f32, -(q.grade.atan()) as f32, bank.atan() as f32) + model_rolled(at, q.heading as f32, -(q.grade.atan()) as f32, (bank.atan() + lean_at(&route, d, speed)) as f32) }; // The rider's own colour, #e9ff60, in linear light. - slots.push(Draw { model: place(&p, shown, 0.0), tint: [0.815, 1.0, 0.117, 1.0], flags: [1.0, 1.0, 0.0, 0.0] }); + slots.push(Draw { model: place(&p, shown, 0.0, speed), tint: [0.815, 1.0, 0.117, 1.0], flags: [1.0, 1.0, 0.0, 0.0] }); riders.push((slots.len() - 1, pose, false)); let mut rider_tags: Vec<(String, [f64; 3])> = Vec::new(); - for (i, (id, kind, color, d, _)) in rivals.iter().enumerate() { + for (i, (id, kind, color, d, rival_speed)) in rivals.iter().enumerate() { let gap = if lap_ride { wrapped(shown, *d).abs() } else { (d - shown).abs() }; if gap > 700.0 || (!lap_ride && (*d <= 0.0 || *d >= route.total)) || slots.len() as u64 >= MAX_DRAWS { continue; @@ -1052,7 +1053,11 @@ impl Renderer { let q = sample(&route, *d); let ghost = *kind == RivalKind::Ghost; let rgb = [((color >> 16) & 255) as f32 / 255.0, ((color >> 8) & 255) as f32 / 255.0, (color & 255) as f32 / 255.0].map(|c| c.powf(2.2)); - slots.push(Draw { model: place(&q, *d, lane), tint: if ghost { [1.0, 1.0, 1.0, 0.38] } else { [rgb[0], rgb[1], rgb[2], 1.0] }, flags: [1.0, 1.0, 0.0, if ghost { 1.0 } else { 0.0 }] }); + slots.push(Draw { + model: place(&q, *d, lane, *rival_speed), + tint: if ghost { [1.0, 1.0, 1.0, 0.38] } else { [rgb[0], rgb[1], rgb[2], 1.0] }, + flags: [1.0, 1.0, 0.0, if ghost { 1.0 } else { 0.0 }], + }); riders.push((slots.len() - 1, (pose + i * 2) % pose_count, ghost)); if gap < 250.0 && gap > 12.0 { rider_tags.push((id.clone(), [q.x + q.heading.cos() * lane, q.ele + 2.3, q.z - q.heading.sin() * lane])); @@ -1486,31 +1491,34 @@ fn sample(route: &velopopuli_core::gpx::Route, dist: f64) -> Pos { let i = (f.floor() as usize).min(route.n - 2); let t = f - i as f64; let lerp = |a: f64, b: f64| a + (b - a) * t; - Pos { - x: lerp(route.x[i], route.x[i + 1]), - z: lerp(route.z[i], route.z[i + 1]), - ele: lerp(route.ele[i] as f64, route.ele[i + 1] as f64), - grade: lerp(route.grade[i] as f64, route.grade[i + 1] as f64), - heading: heading_at(route, f), - } + // On a smooth curve through the samples, as the page's `sampleAt` does it, so a tight bend + // is ridden round rather than in a kink at every sample. + let (x, dx) = curve(&route.x, i, t); + let (z, dz) = curve(&route.z, i, t); + Pos { x, z, ele: lerp(route.ele[i] as f64, route.ele[i + 1] as f64), grade: lerp(route.grade[i] as f64, route.grade[i + 1] as f64), heading: dx.atan2(dz) } } -/// The direction of travel at `f` samples along, as the page's `headingAt` gives it: over a -/// ~25 m baseline against GPS jitter, blended between neighbouring samples so a corner turns -/// smoothly rather than in a step at each one. -fn heading_at(route: &velopopuli_core::gpx::Route, f: f64) -> f64 { - // Over samples k-2..k+3, centred on k + 0.5. - let over = |k: usize| { - let (a, b) = (k.saturating_sub(2), (k + 3).min(route.n - 1)); - (route.x[b] - route.x[a]).atan2(route.z[b] - route.z[a]) - }; - let u = (f - 0.5).max(0.0); - let k = (u.floor() as usize).min(route.n - 2); - let s = (u - k as f64).min(1.0); - let h0 = over(k); - // The short way round, across ±π. - let d = (over(k + 1) - h0).sin().atan2((over(k + 1) - h0).cos()); - h0 + d * s +/// The Catmull-Rom curve through `a` between samples `i` and `i + 1`, at `t` of the way: its +/// value and its rate of change. +fn curve(a: &[f64], i: usize, t: f64) -> (f64, f64) { + let (p0, p1, p2, p3) = (a[i.saturating_sub(1)], a[i], a[i + 1], a[(i + 2).min(a.len() - 1)]); + let (b, c, d) = (p2 - p0, 2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3, -p0 + 3.0 * p1 - 3.0 * p2 + p3); + (p1 + 0.5 * t * (b + t * (c + t * d)), 0.5 * (b + t * (2.0 * c + 3.0 * t * d))) +} + +/// Over how far a bend's tightness is judged, either side of the rider. +const LEAN_SPAN: f64 = 4.0; +/// The most a rider leans into a bend. +const MAX_LEAN: f64 = 40.0 * std::f64::consts::PI / 180.0; + +/// How far a rider at `speed` (m/s) leans into the bend at `dist`, as the page's `leanAt` +/// gives it: the lean that balances the turn, atan(v² / g r). Negative leans left. +fn lean_at(route: &velopopuli_core::gpx::Route, dist: f64, speed: f64) -> f64 { + let h = |d: f64| sample(route, d).heading; + let dh = h(dist + LEAN_SPAN) - h(dist - LEAN_SPAN); + // Turning towards +x (heading rising) is turning left. + let lean = (speed * speed * (dh.sin().atan2(dh.cos()) / (2.0 * LEAN_SPAN)) / 9.81).atan(); + -lean.clamp(-MAX_LEAN, MAX_LEAN) } /// Ground height from a loaded chunk, if the chunk under the point is in. @@ -1539,10 +1547,10 @@ mod tests { use velopopuli_core::gpx::{build_route, RawPoint}; /// A rider going round a tight circle turns a little for every bit ridden, never in steps, - /// and faces along the road. + /// moves on a path without kinks, faces along it, and leans into the turn. #[test] fn corners_turn_smoothly() { - // Two laps of a 30 m-radius circle, a point every 2°. + // Two laps of a 30 m-radius circle anticlockwise on the map (turning left), a point every 2°. let (lat0, lon0, r) = (51.0_f64, 0.0_f64, 30.0); let m_lat = 111_320.0; let raw: Vec = (0..=360) @@ -1554,17 +1562,26 @@ mod tests { let route = build_route("Circle", &raw).unwrap(); let wrap = |d: f64| d.sin().atan2(d.cos()); let (from, to, dd) = (20.0, route.total - 20.0, 0.1); - let mut biggest: f64 = 0.0; + let (mut turned, mut kinked): (f64, f64) = (0.0, 0.0); let mut d = from; while d < to { - let (p, q) = (super::sample(&route, d), super::sample(&route, d + dd)); - biggest = biggest.max(wrap(q.heading - p.heading).abs()); - // Facing the way the rider moves. - let moving = (q.x - p.x).atan2(q.z - p.z); - assert!(wrap(p.heading - moving).abs() < 0.15, "at {d:.1} m facing {:.3}, moving {:.3}", p.heading, moving); + let (p, q, s) = (super::sample(&route, d), super::sample(&route, d + dd), super::sample(&route, d + 2.0 * dd)); + turned = turned.max(wrap(q.heading - p.heading).abs()); + // The way it moves from one 10 cm to the next: a kink is a sudden change. + let (m1, m2) = ((q.x - p.x).atan2(q.z - p.z), (s.x - q.x).atan2(s.z - q.z)); + kinked = kinked.max(wrap(m2 - m1).abs()); + assert!(wrap(p.heading - m1).abs() < 0.02, "at {d:.1} m facing {:.3}, moving {m1:.3}", p.heading); d += dd; } - // Round a 30 m circle, 10 cm turns the rider by 1/300 rad; a step at each sample would be ~50 times that. - assert!(biggest < 3.0 * dd / r, "the heading jumped {biggest:.4} rad in {dd} m"); + // Round a 30 m circle, 10 cm turns the rider by 1/300 rad; a step or kink at each 5 m + // sample would be ~50 times that. + assert!(turned < 3.0 * dd / r, "the heading jumped {turned:.4} rad in {dd} m"); + assert!(kinked < 3.0 * dd / r, "the path kinked {kinked:.4} rad in {dd} m"); + // At 10 m/s round 30 m, the balancing lean is atan(100 / (9.81 · 30)), about 19°, to the left. + let lean = super::lean_at(&route, route.total / 2.0, 10.0); + assert!((lean + (100.0_f64 / (9.81 * 30.0)).atan()).abs() < 0.03, "leans {:.1}°", lean.to_degrees()); + // Standing still, no lean; and never past the limit, however fast. + assert!(super::lean_at(&route, route.total / 2.0, 0.0).abs() < 1e-9); + assert!((super::lean_at(&route, route.total / 2.0, 40.0) + super::MAX_LEAN).abs() < 1e-9); } } diff --git a/web/src/core/gpx.ts b/web/src/core/gpx.ts index 498f9ce..67cf007 100644 --- a/web/src/core/gpx.ts +++ b/web/src/core/gpx.ts @@ -75,35 +75,50 @@ export interface RoutePos { heading: number } +/** A point along the route. The line runs on a smooth curve through the samples (Catmull-Rom) + * rather than straight from one to the next, so a tight bend is ridden round, not in a kink at + * every sample; the heading is the curve's own direction there. */ export function sampleAt(route: Route, dist: number, out?: RoutePos): RoutePos { const f = Math.max(0, Math.min(route.n - 1, dist / route.step)) const i = Math.min(route.n - 2, Math.floor(f)) const t = f - i const lerp = (a: Float64Array): number => a[i] + (a[i + 1] - a[i]) * t + const [x, dx] = curve(route.x, route.n, i, t) + const [z, dz] = curve(route.z, route.n, i, t) const o = out ?? ({} as RoutePos) - o.x = lerp(route.x) - o.z = lerp(route.z) + o.x = x + o.z = z o.ele = lerp(route.ele) o.grade = lerp(route.grade) - o.heading = headingAt(route, f) + o.heading = Math.atan2(dx, dz) return o } -/** The direction of travel at `f` samples along, over a ~25 m baseline so GPS jitter doesn't - * shake the camera. Blended between neighbouring samples, so a corner turns smoothly rather - * than in a step at each one. */ -function headingAt(route: Route, f: number): number { - // Over samples k-2..k+3, centred on k + 0.5. - const over = (k: number): number => { - const a = Math.max(0, k - 2) - const b = Math.min(route.n - 1, k + 3) - return Math.atan2(route.x[b] - route.x[a], route.z[b] - route.z[a]) - } - const u = Math.max(0, f - 0.5) - const k = Math.min(route.n - 2, Math.floor(u)) - const s = Math.min(1, u - k) - const h0 = over(k) - // The short way round, across ±π. - const d = Math.atan2(Math.sin(over(k + 1) - h0), Math.cos(over(k + 1) - h0)) - return h0 + d * s +/** The Catmull-Rom curve through `a` between samples `i` and `i + 1`, at `t` of the way: its + * value and its rate of change. */ +function curve(a: Float64Array, n: number, i: number, t: number): [number, number] { + const p0 = a[Math.max(0, i - 1)] + const p1 = a[i] + const p2 = a[i + 1] + const p3 = a[Math.min(n - 1, i + 2)] + const b = p2 - p0 + const c = 2 * p0 - 5 * p1 + 4 * p2 - p3 + const d = -p0 + 3 * p1 - 3 * p2 + p3 + return [p1 + 0.5 * t * (b + t * (c + t * d)), 0.5 * (b + t * (2 * c + 3 * t * d))] +} + +/** Over how far a bend's tightness is judged, either side of the rider. */ +const LEAN_SPAN = 4 +/** The most a rider leans into a bend. */ +const MAX_LEAN = (40 * Math.PI) / 180 + +/** How far a rider at `speed` (m/s) leans into the bend at `dist`, in radians: the lean that + * balances the turn, atan(v² / g r). Negative leans left, the way `rotation.z` rolls. */ +export function leanAt(route: Route, dist: number, speed: number): number { + const h = (d: number): number => sampleAt(route, d, scratch).heading + const turn = Math.atan2(Math.sin(h(dist + LEAN_SPAN) - h(dist - LEAN_SPAN)), Math.cos(h(dist + LEAN_SPAN) - h(dist - LEAN_SPAN))) + // Turning towards +x (heading rising) is turning left. + const lean = Math.atan((speed * speed * (turn / (2 * LEAN_SPAN))) / 9.81) + return -Math.max(-MAX_LEAN, Math.min(MAX_LEAN, lean)) } +const scratch = {} as RoutePos diff --git a/web/src/world/scene.ts b/web/src/world/scene.ts index 1c525bc..1f76478 100644 --- a/web/src/world/scene.ts +++ b/web/src/world/scene.ts @@ -2,7 +2,7 @@ import * as THREE from 'three' import { Barriers } from './barriers' import { SURFACES, surfaceRuns, surfaceTexture } from './surfaces' import { api } from '../bridge' -import { bankAt, halfWidthAt, sampleAt, wrapDist, wrapGap, type Route, type RoutePos } from '../core/gpx' +import { bankAt, halfWidthAt, leanAt, sampleAt, wrapDist, wrapGap, type Route, type RoutePos } from '../core/gpx' import type { Landmark, WorldLayout } from '../types' import { RiderModel } from './rider' import { Terrain } from './terrain' @@ -422,15 +422,16 @@ export class World { } /** On a berm, a rider stands on the slope where they are across the trail and leans with it. */ - private place(group: THREE.Object3D, p: RoutePos, dist: number, lane: number): void { + /** Riders also lean into bends, by what balances the turn at their speed. */ + private place(group: THREE.Object3D, p: RoutePos, dist: number, lane: number, speed: number): void { const [bank, lift] = bankAt(this.route, dist, lane) group.position.set(p.x + Math.cos(p.heading) * lane, p.ele + this.layout.roadLift + lift, p.z - Math.sin(p.heading) * lane) - group.rotation.set(-Math.atan(p.grade), p.heading, Math.atan(bank), 'YXZ') + group.rotation.set(-Math.atan(p.grade), p.heading, Math.atan(bank) + leanAt(this.route, dist, speed), 'YXZ') } frame(dt: number, f: WorldFrame): void { const p = sampleAt(this.route, f.distance, this.pos) - this.place(this.rider.group, p, f.distance, 0) + this.place(this.rider.group, p, f.distance, 0, f.speed) this.rider.update(dt, f.speed, f.cadence) const seen = new Set() @@ -451,7 +452,7 @@ export class World { const op = sampleAt(this.route, r.distance, this.otherPos) // Kept on the road where it is narrow. const room = Math.max(0.4, halfWidthAt(this.route, r.distance) - 0.6) - this.place(other.model.group, op, r.distance, Math.sign(other.lane) * Math.min(Math.abs(other.lane), room)) + this.place(other.model.group, op, r.distance, Math.sign(other.lane) * Math.min(Math.abs(other.lane), room), r.speed) other.model.update(dt, r.speed, r.speed > 0.5 ? 85 : 0) other.label.position.copy(other.model.group.position) other.label.position.y += 2.3