ferravex_play/navigation/route.rs
1use super::NavigationError;
2use ferravex_math::Vec3;
3pub const MAX_ROUTE_POINTS: usize = 4096;
4/// Reusable piecewise-linear world-space route. Arc lengths are f64, repeated
5/// points are legal, and updates validate the complete input before mutation.
6pub struct Route3 {
7 points: Vec<Vec3>,
8 lengths: Vec<f64>,
9 capacity: usize,
10 closed: bool,
11 total_length: f64,
12}
13/// Arc-distance sample from [`Route3::sample`] or [`Route3::sample_progress`].
14#[derive(Clone, Copy, Debug)]
15pub struct RouteSample {
16 pub position: Vec3,
17 pub direction: Vec3,
18 pub segment: usize,
19 pub distance: f64,
20 /// True only at the endpoint of an open route, including a zero-length one.
21 pub complete: bool,
22}
23/// Nearest geometric observation from [`Route3::project`]. This is not evidence
24/// of visiting checkpoints or completing laps. See that method for an example.
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct RouteProjection {
27 pub position: Vec3,
28 /// Unit tangent of the selected segment, including at its endpoints. Zero
29 /// for a route consisting only of coincident points.
30 pub direction: Vec3,
31 /// Start vertex of the selected segment. The closing segment starts at the
32 /// last vertex; a route consisting only of coincident points uses zero.
33 pub segment: usize,
34 /// Clamped fraction along the selected segment, in `0..=1`.
35 pub segment_fraction: f64,
36 /// Arc distance from the first vertex, in world units. The closed seam is
37 /// canonicalized to zero; no lap count is retained.
38 pub distance: f64,
39 /// Arc distance divided by route length, or zero for a zero-length route.
40 pub progress: f64,
41 /// Unsigned world-space distance from the query to its projection, computed
42 /// in f64 before rounding the returned position to Vec3.
43 pub distance_to_route: f64,
44}
45impl Route3 {
46 pub fn new(capacity: usize) -> Result<Self, NavigationError> {
47 if capacity == 0 || capacity > MAX_ROUTE_POINTS {
48 return Err(NavigationError::Capacity);
49 }
50 Ok(Self {
51 points: Vec::with_capacity(capacity),
52 lengths: Vec::with_capacity(capacity),
53 capacity,
54 closed: false,
55 total_length: 0.,
56 })
57 }
58 /// Replaces the route with an open polyline, including after `set_closed`.
59 /// Invalid input leaves the previous geometry and topology unchanged.
60 pub fn set(&mut self, points: &[Vec3]) -> Result<(), NavigationError> {
61 self.set_points(points, false)
62 }
63 /// Replaces the route with a closed polyline, adding a last-to-first segment
64 /// without storing another point or consuming capacity. Repeating the first
65 /// point at the end is also legal. Empty and zero-length loops are legal.
66 /// Invalid input leaves the previous route unchanged.
67 ///
68 /// Closed distance samples and cursors wrap at the seam and never complete.
69 /// `WaypointFollower` retains its finite traversal of the authored vertices.
70 /// No query, cursor operation or successful replacement allocates.
71 ///
72 /// ```
73 /// use ferravex_math::Vec3;
74 /// use ferravex_play::navigation::{PathCursor, Route3};
75 /// let mut route = Route3::new(4)?;
76 /// route.set_closed(&[Vec3::ZERO, Vec3::X * 2., Vec3::new(2., 2., 0.), Vec3::Y * 2.])?;
77 /// assert!(route.is_closed());
78 /// assert_eq!(route.length(), 8.);
79 /// assert_eq!(route.sample(9.)?.unwrap().position, Vec3::X);
80 /// let mut cursor = PathCursor::default();
81 /// cursor.seek(&route, 7.)?;
82 /// assert_eq!(cursor.advance(&route, 2., 1.)?.unwrap().distance, 1.);
83 /// route.clear();
84 /// assert!(!route.is_closed());
85 /// # Ok::<(), ferravex_play::navigation::NavigationError>(())
86 /// ```
87 pub fn set_closed(&mut self, points: &[Vec3]) -> Result<(), NavigationError> {
88 self.set_points(points, true)
89 }
90 /// Whether samples wrap over a last-to-first segment. See [`Self::set_closed`].
91 pub fn is_closed(&self) -> bool {
92 self.closed
93 }
94 fn set_points(&mut self, points: &[Vec3], closed: bool) -> Result<(), NavigationError> {
95 if points.len() > self.capacity {
96 return Err(NavigationError::Capacity);
97 }
98 if points.iter().any(|p| !p.is_finite()) {
99 return Err(NavigationError::InvalidInput);
100 }
101 self.points.clear();
102 self.lengths.clear();
103 let mut length = 0.;
104 for (i, point) in points.iter().enumerate() {
105 if i > 0 {
106 length += distance(points[i - 1], *point);
107 }
108 self.points.push(*point);
109 self.lengths.push(length);
110 }
111 if closed && points.len() > 1 {
112 length += distance(points[points.len() - 1], points[0]);
113 }
114 self.total_length = length;
115 self.closed = closed;
116 Ok(())
117 }
118 pub fn clear(&mut self) {
119 self.points.clear();
120 self.lengths.clear();
121 self.total_length = 0.;
122 self.closed = false;
123 }
124 pub fn points(&self) -> &[Vec3] {
125 &self.points
126 }
127 pub fn length(&self) -> f64 {
128 self.total_length
129 }
130 /// Samples a finite nonnegative distance. Open routes clamp at the endpoint;
131 /// closed routes wrap, with zero-length loops staying at their sole position.
132 /// Empty routes return `None`. See [`Self::set_closed`] for a loop example.
133 pub fn sample(&self, travel: f64) -> Result<Option<RouteSample>, NavigationError> {
134 if !travel.is_finite() || travel < 0. {
135 return Err(NavigationError::InvalidInput);
136 }
137 let Some(last) = self.points.last().copied() else {
138 return Ok(None);
139 };
140 let travel = self.canonical_distance(travel);
141 if self.length() == 0. || (!self.closed && travel >= self.length()) {
142 return Ok(Some(RouteSample {
143 position: last,
144 direction: Vec3::ZERO,
145 segment: self.points.len() - 1,
146 distance: self.length(),
147 complete: !self.closed,
148 }));
149 }
150 // upper_bound skips zero-length segments without a linear traversal.
151 let next = self.lengths.partition_point(|v| *v <= travel).max(1);
152 let start = self.lengths[next - 1];
153 let segment = self.lengths.get(next).copied().unwrap_or(self.length()) - start;
154 let alpha = ((travel - start) / segment).clamp(0., 1.);
155 let a = self.points[next - 1].to_array();
156 let b = self.points[next % self.points.len()].to_array();
157 let position = Vec3::from_array(std::array::from_fn(|i| {
158 (f64::from(a[i]) * (1. - alpha) + f64::from(b[i]) * alpha) as f32
159 }));
160 let direction = Vec3::from_array(std::array::from_fn(|i| {
161 ((f64::from(b[i]) - f64::from(a[i])) / segment) as f32
162 }));
163 Ok(Some(RouteSample {
164 position,
165 direction,
166 segment: next - 1,
167 distance: travel,
168 complete: false,
169 }))
170 }
171
172 /// Samples a normalized arc fraction in `0..=1`; out-of-range and non-finite
173 /// inputs return `InvalidInput`, even on an empty route. One is the endpoint
174 /// for an open route and the start of a closed route.
175 ///
176 /// ```
177 /// use ferravex_math::Vec3;
178 /// use ferravex_play::navigation::Route3;
179 /// let mut route = Route3::new(2)?;
180 /// route.set(&[Vec3::ZERO, Vec3::X * 10.])?;
181 /// assert_eq!(route.sample_progress(0.25)?.unwrap().position, Vec3::X * 2.5);
182 /// assert!(route.sample_progress(1.)?.unwrap().complete);
183 /// assert!(route.sample_progress(1.1).is_err());
184 /// # Ok::<(), ferravex_play::navigation::NavigationError>(())
185 /// ```
186 pub fn sample_progress(&self, progress: f64) -> Result<Option<RouteSample>, NavigationError> {
187 if !progress.is_finite() || !(0. ..=1.).contains(&progress) {
188 return Err(NavigationError::InvalidInput);
189 }
190 self.sample(self.length() * progress)
191 }
192
193 /// Projects a finite world position onto the entire route in O(point count)
194 /// time and constant scratch space. Empty routes return `None`. Calculations
195 /// use f64, including differences between extreme finite f32 coordinates.
196 ///
197 /// Zero-length segments are skipped. Equal squared distances select the
198 /// lowest index of a nonzero-length segment, including at corners or
199 /// intersections. A point-only route returns its first point, zero progress
200 /// and zero tangent.
201 /// Projection is global: teleports and nearby branches can change progress
202 /// discontinuously. It does not infer motion, laps or checkpoint visits.
203 ///
204 /// ```
205 /// use ferravex_math::Vec3;
206 /// use ferravex_play::navigation::{Route3, RouteProjection};
207 /// let mut route = Route3::new(3)?;
208 /// route.set(&[Vec3::ZERO, Vec3::ZERO, Vec3::X * 10.])?;
209 /// let hit: RouteProjection = route.project(Vec3::new(4., 3., 0.))?.unwrap();
210 /// assert_eq!(hit.position, Vec3::X * 4.);
211 /// assert_eq!(hit.segment, 1);
212 /// assert_eq!(hit.distance, 4.);
213 /// assert_eq!(hit.progress, 0.4);
214 /// assert_eq!(hit.distance_to_route, 3.);
215 /// # Ok::<(), ferravex_play::navigation::NavigationError>(())
216 /// ```
217 pub fn project(&self, position: Vec3) -> Result<Option<RouteProjection>, NavigationError> {
218 if !position.is_finite() {
219 return Err(NavigationError::InvalidInput);
220 }
221 let Some(first) = self.points.first().copied() else {
222 return Ok(None);
223 };
224 let query = position.to_array().map(f64::from);
225 // (segment, fraction, squared length, projection, delta). The projection
226 // record is built once for the winner instead of per improvement.
227 type Candidate = (usize, f64, f64, [f64; 3], [f64; 3]);
228 let mut best: Option<Candidate> = None;
229 let mut best_squared = f64::INFINITY;
230 let segment_count = self.points.len() - 1 + usize::from(self.closed);
231 let mut a = first.to_array().map(f64::from);
232 for segment in 0..segment_count {
233 let next = if segment + 1 == self.points.len() {
234 0
235 } else {
236 segment + 1
237 };
238 let b = self.points[next].to_array().map(f64::from);
239 let start = std::mem::replace(&mut a, b);
240 let delta: [f64; 3] = std::array::from_fn(|i| b[i] - start[i]);
241 let squared_length = delta.iter().map(|v| v * v).sum::<f64>();
242 if squared_length == 0. {
243 continue;
244 }
245 let fraction = ((0..3)
246 .map(|i| (query[i] - start[i]) * delta[i])
247 .sum::<f64>()
248 / squared_length)
249 .clamp(0., 1.);
250 let projected: [f64; 3] =
251 std::array::from_fn(|i| start[i] * (1. - fraction) + b[i] * fraction);
252 let squared = (0..3)
253 .map(|i| (query[i] - projected[i]).powi(2))
254 .sum::<f64>();
255 if squared < best_squared {
256 best = Some((segment, fraction, squared_length, projected, delta));
257 best_squared = squared;
258 }
259 }
260 Ok(Some(best.map_or_else(
261 || RouteProjection {
262 position: first,
263 direction: Vec3::ZERO,
264 segment: 0,
265 segment_fraction: 0.,
266 distance: 0.,
267 progress: 0.,
268 distance_to_route: distance(position, first),
269 },
270 |(segment, fraction, squared_length, projected, delta)| {
271 let length = squared_length.sqrt();
272 let along = self.canonical_distance(self.lengths[segment] + length * fraction);
273 RouteProjection {
274 position: Vec3::from_array(projected.map(|v| v as f32)),
275 direction: Vec3::from_array(delta.map(|v| (v / length) as f32)),
276 segment,
277 segment_fraction: fraction,
278 distance: along,
279 progress: along / self.length(),
280 distance_to_route: best_squared.sqrt(),
281 }
282 },
283 )))
284 }
285
286 fn canonical_distance(&self, travel: f64) -> f64 {
287 if self.closed && self.length() > 0. {
288 travel % self.length()
289 } else {
290 travel.min(self.length())
291 }
292 }
293}
294fn distance(a: Vec3, b: Vec3) -> f64 {
295 let a = a.to_array();
296 let b = b.to_array();
297 (0..3)
298 .map(|i| (f64::from(b[i]) - f64::from(a[i])).powi(2))
299 .sum::<f64>()
300 .sqrt()
301}
302/// Exact distance cursor for authored rail/path movement. Collision-driven actors
303/// should use WaypointFollower, so a blocked body cannot advance along a route.
304#[derive(Clone, Copy, Debug, Default)]
305pub struct PathCursor {
306 distance: f64,
307}
308impl PathCursor {
309 pub fn reset(&mut self) {
310 self.distance = 0.;
311 }
312 pub fn distance(&self) -> f64 {
313 self.distance
314 }
315 /// Seeks to a finite nonnegative distance, clamping open routes and wrapping
316 /// closed routes. See [`Route3::set_closed`] for a cursor example.
317 pub fn seek(&mut self, route: &Route3, distance: f64) -> Result<(), NavigationError> {
318 if !distance.is_finite() || distance < 0. {
319 return Err(NavigationError::InvalidInput);
320 }
321 self.distance = route.canonical_distance(distance);
322 Ok(())
323 }
324 /// Repositions the cursor to the global nearest projection after a teleport
325 /// or route replacement. This can move backward or jump across the seam;
326 /// it neither advances time nor awards laps/checkpoints. Invalid positions
327 /// and empty routes leave the cursor unchanged. See [`Route3::project`] for
328 /// tie rules. No route identity or previous projection is cached.
329 ///
330 /// ```
331 /// use ferravex_math::Vec3;
332 /// use ferravex_play::navigation::{PathCursor, Route3};
333 /// let mut route = Route3::new(2)?;
334 /// route.set(&[Vec3::ZERO, Vec3::X * 10.])?;
335 /// let mut cursor = PathCursor::default();
336 /// cursor.seek(&route, 9.)?;
337 /// cursor.recover(&route, Vec3::new(2., 3., 0.))?;
338 /// assert_eq!(cursor.distance(), 2.);
339 /// assert_eq!(cursor.advance(&route, 1., 1.)?.unwrap().position, Vec3::X * 3.);
340 /// # Ok::<(), ferravex_play::navigation::NavigationError>(())
341 /// ```
342 pub fn recover(
343 &mut self,
344 route: &Route3,
345 position: Vec3,
346 ) -> Result<Option<RouteProjection>, NavigationError> {
347 let projection = route.project(position)?;
348 if let Some(hit) = projection {
349 self.distance = hit.distance;
350 }
351 Ok(projection)
352 }
353 /// Advances by a caller-supplied speed and simulation delta. Open routes
354 /// stop at the endpoint; closed routes wrap without tracking completed laps.
355 pub fn advance(
356 &mut self,
357 route: &Route3,
358 speed: f32,
359 dt: f32,
360 ) -> Result<Option<RouteSample>, NavigationError> {
361 if !speed.is_finite() || speed < 0. || !dt.is_finite() || !(0. ..=60.).contains(&dt) {
362 return Err(NavigationError::InvalidInput);
363 }
364 // Reduce each operand first so a large whole-loop step cannot erase a
365 // small existing offset when they are added. This also bounds a stale
366 // cursor after a route replacement without storing route identities.
367 let step = f64::from(speed) * f64::from(dt);
368 self.distance = route.canonical_distance(
369 route.canonical_distance(self.distance) + route.canonical_distance(step),
370 );
371 route.sample(self.distance)
372 }
373}
374#[derive(Clone, Copy, Debug, Default)]
375pub struct WaypointFollower {
376 next: usize,
377}
378impl WaypointFollower {
379 pub fn reset(&mut self) {
380 self.next = 0;
381 }
382 pub fn next_index(&self) -> usize {
383 self.next
384 }
385 /// Returns the next unvisited waypoint. Stops at the endpoint; never advances
386 /// merely because time passes while an actor is blocked. At most max_skips
387 /// waypoints are consumed per call, even for a route of repeated points.
388 pub fn target(
389 &mut self,
390 route: &Route3,
391 position: Vec3,
392 radius: f32,
393 max_skips: usize,
394 ) -> Result<Option<Vec3>, NavigationError> {
395 if !position.is_finite() || !radius.is_finite() || radius < 0. {
396 return Err(NavigationError::InvalidInput);
397 }
398 self.next = self.next.min(route.points.len());
399 let mut skipped = 0;
400 while self.next < route.points.len()
401 && distance(position, route.points[self.next]) <= f64::from(radius)
402 {
403 if skipped == max_skips {
404 return Ok(Some(route.points[self.next]));
405 }
406 self.next += 1;
407 skipped += 1;
408 }
409 Ok(route.points.get(self.next).copied())
410 }
411}