ferravex_play/navigation/
mesh.rs

1//! Authored triangular navigation surfaces. Walk portals join exact shared edges;
2//! directional traversal links remain explicit host actions. Bake clearance for
3//! the agent radius before construction. This is not an automatic mesh baker.
4//! Use the checked constructors for indexed authoring diagnostics; the original
5//! constructors retain their permissive adjacency rules.
6use super::NavigationError;
7use crate::ai::WorkBudget;
8use ferravex_math::Vec3;
9
10const MAX_TRIANGLES: usize = 2048;
11const MAX_LINKS: usize = 16384;
12const MAX_COORDINATE: f32 = 1_000_000.;
13
14#[derive(Clone, Copy, Debug)]
15pub struct NavTriangle(pub [Vec3; 3]);
16impl NavTriangle {
17    fn center(self) -> Vec3 {
18        (self.0[0] + self.0[1] + self.0[2]) / 3.
19    }
20    /// Test either winding using a 0.001 world-unit plane tolerance and 1e-5
21    /// barycentric edge tolerance. Non-finite or degenerate input returns false.
22    /// Geometry arithmetic uses f64 intermediates, including thin faces.
23    pub fn contains(self, p: Vec3) -> bool {
24        if !p.is_finite() || self.0.iter().any(|v| !v.is_finite()) {
25            return false;
26        }
27        let [a, b, c] = self.0;
28        let u = difference(b, a);
29        let v = difference(c, a);
30        let d = difference(p, a);
31        let n = cross(u, v);
32        let den = dot(n, n);
33        if den < 1e-10 || dot(d, n).abs() > 0.001 * den.sqrt() {
34            return false;
35        }
36        // Cross products avoid subtracting nearly equal squared edge lengths.
37        // Widen before subtraction so skinny, large-coordinate faces work too.
38        let x = dot(cross(d, v), n) / den;
39        let y = dot(cross(u, d), n) / den;
40        x >= -1e-5 && y >= -1e-5 && x + y <= 1.00001
41    }
42}
43
44fn difference(a: Vec3, b: Vec3) -> [f64; 3] {
45    [
46        f64::from(a.x) - f64::from(b.x),
47        f64::from(a.y) - f64::from(b.y),
48        f64::from(a.z) - f64::from(b.z),
49    ]
50}
51
52fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
53    [
54        a[1] * b[2] - a[2] * b[1],
55        a[2] * b[0] - a[0] * b[2],
56        a[0] * b[1] - a[1] * b[0],
57    ]
58}
59
60fn dot(a: [f64; 3], b: [f64; 3]) -> f64 {
61    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
62}
63
64/// First authoring failure from a checked mesh operation, with zero-based input
65/// indices. Edge `e` runs from vertex `e` to vertex `(e + 1) % 3`.
66///
67/// Geometry is checked before adjacency, then links in input order. Correct the
68/// reported issue and validate again to find subsequent issues. Both global
69/// winding directions are accepted; neighbors must traverse a shared edge in
70/// opposite directions. Disconnected components need not share an orientation.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum NavMeshDiagnostic {
73    EmptyMesh,
74    TriangleCapacity {
75        count: usize,
76        maximum: usize,
77    },
78    LinkCapacity {
79        count: usize,
80        maximum: usize,
81    },
82    NonFiniteVertex {
83        triangle: usize,
84        vertex: usize,
85    },
86    /// A vertex component exceeds the supported absolute limit of 1,000,000.
87    VertexOutOfRange {
88        triangle: usize,
89        vertex: usize,
90    },
91    /// Repeated/collinear vertices or squared cross-product magnitude < 1e-6.
92    DegenerateTriangle {
93        triangle: usize,
94    },
95    /// The same three exact vertices appear in two faces, in any order.
96    DuplicateTriangle {
97        triangle: usize,
98        other: usize,
99    },
100    /// More than two faces use the same exact edge.
101    NonManifoldEdge {
102        triangle: usize,
103        edge: usize,
104        first_neighbor: usize,
105        second_neighbor: usize,
106    },
107    InconsistentWinding {
108        triangle: usize,
109        edge: usize,
110        neighbor: usize,
111        neighbor_edge: usize,
112    },
113    SourceOutOfBounds {
114        link: usize,
115        triangle: usize,
116    },
117    DestinationOutOfBounds {
118        link: usize,
119        triangle: usize,
120    },
121    SelfLink {
122        link: usize,
123        triangle: usize,
124    },
125    InvalidLinkCost {
126        link: usize,
127    },
128    /// Entry is non-finite or outside the indicated face's containment tolerance.
129    InvalidEntry {
130        link: usize,
131        triangle: usize,
132    },
133    /// Exit is non-finite or outside the destination face's containment tolerance.
134    InvalidExit {
135        link: usize,
136        triangle: usize,
137    },
138    MissingSharedEdge {
139        link: usize,
140        from: usize,
141        to: usize,
142    },
143    /// Walk entry/exit differ by more than 0.001 world units.
144    PortalMismatch {
145        link: usize,
146    },
147    /// Walk entry or exit is more than 0.001 units from the shared edge segment.
148    PortalOffEdge {
149        link: usize,
150        triangle: usize,
151        edge: usize,
152    },
153    /// The shared mesh/grid identity counter is exhausted; no mesh was installed.
154    RevisionExhausted,
155}
156
157impl NavMeshDiagnostic {
158    fn navigation_error(self) -> NavigationError {
159        match self {
160            Self::EmptyMesh | Self::TriangleCapacity { .. } | Self::LinkCapacity { .. } => {
161                NavigationError::Capacity
162            }
163            Self::RevisionExhausted => NavigationError::RevisionExhausted,
164            _ => NavigationError::InvalidInput,
165        }
166    }
167}
168
169impl std::fmt::Display for NavMeshDiagnostic {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        match *self {
172            Self::EmptyMesh => write!(f, "add at least one navigation triangle"),
173            Self::TriangleCapacity { count, maximum } => {
174                write!(f, "{count} triangles exceed the limit of {maximum}")
175            }
176            Self::LinkCapacity { count, maximum } => {
177                write!(f, "{count} links exceed the limit of {maximum}")
178            }
179            Self::NonFiniteVertex { triangle, vertex } => {
180                write!(f, "triangle {triangle} vertex {vertex} must be finite")
181            }
182            Self::VertexOutOfRange { triangle, vertex } => write!(
183                f,
184                "triangle {triangle} vertex {vertex} must have components within +/-1,000,000"
185            ),
186            Self::DegenerateTriangle { triangle } => write!(
187                f,
188                "triangle {triangle} needs three distinct non-collinear vertices with squared cross magnitude >= 1e-6"
189            ),
190            Self::DuplicateTriangle { triangle, other } => {
191                write!(
192                    f,
193                    "triangle {triangle} duplicates triangle {other}; remove one face"
194                )
195            }
196            Self::NonManifoldEdge {
197                triangle,
198                edge,
199                first_neighbor,
200                second_neighbor,
201            } => write!(
202                f,
203                "triangle {triangle} edge {edge} is shared with triangles {first_neighbor} and {second_neighbor}; at most two faces may share an edge"
204            ),
205            Self::InconsistentWinding {
206                triangle,
207                edge,
208                neighbor,
209                neighbor_edge,
210            } => write!(
211                f,
212                "triangle {triangle} edge {edge} and triangle {neighbor} edge {neighbor_edge} run in the same direction; reverse one face's winding"
213            ),
214            Self::SourceOutOfBounds { link, triangle } => {
215                write!(f, "link {link} source triangle {triangle} does not exist")
216            }
217            Self::DestinationOutOfBounds { link, triangle } => {
218                write!(
219                    f,
220                    "link {link} destination triangle {triangle} does not exist"
221                )
222            }
223            Self::SelfLink { link, triangle } => {
224                write!(
225                    f,
226                    "link {link} must connect distinct triangles, not triangle {triangle} to itself"
227                )
228            }
229            Self::InvalidLinkCost { link } => {
230                write!(f, "link {link} cost must be finite and nonnegative")
231            }
232            Self::InvalidEntry { link, triangle } => {
233                write!(
234                    f,
235                    "link {link} entry must be finite and lie on triangle {triangle}"
236                )
237            }
238            Self::InvalidExit { link, triangle } => {
239                write!(
240                    f,
241                    "link {link} exit must be finite and lie on triangle {triangle}"
242                )
243            }
244            Self::MissingSharedEdge { link, from, to } => write!(
245                f,
246                "walk link {link} triangles {from} and {to} must share an exact vertex edge; use an explicit traversal for a gap"
247            ),
248            Self::PortalMismatch { link } => {
249                write!(
250                    f,
251                    "walk link {link} entry and exit must be within 0.001 units"
252                )
253            }
254            Self::PortalOffEdge {
255                link,
256                triangle,
257                edge,
258            } => write!(
259                f,
260                "walk link {link} entry and exit must lie on triangle {triangle} edge {edge} within 0.001 units"
261            ),
262            Self::RevisionExhausted => write!(f, "navigation identity counter exhausted"),
263        }
264    }
265}
266
267impl std::error::Error for NavMeshDiagnostic {}
268#[derive(Clone, Copy, Debug, PartialEq, Eq)]
269pub enum Traversal {
270    Walk,
271    Jump,
272    Drop,
273    Climb,
274}
275#[derive(Clone, Copy, Debug)]
276pub struct TraversalLink {
277    pub from: usize,
278    pub to: usize,
279    pub entry: Vec3,
280    pub exit: Vec3,
281    pub kind: Traversal,
282    pub cost: f32,
283    pub enabled: bool,
284}
285#[derive(Clone, Copy, Debug)]
286pub struct NavWaypoint {
287    pub position: Vec3,
288    pub traversal: Traversal,
289}
290
291fn validate_capacity(triangles: usize, links: usize) -> Result<(), NavMeshDiagnostic> {
292    if triangles == 0 {
293        return Err(NavMeshDiagnostic::EmptyMesh);
294    }
295    if triangles > MAX_TRIANGLES {
296        return Err(NavMeshDiagnostic::TriangleCapacity {
297            count: triangles,
298            maximum: MAX_TRIANGLES,
299        });
300    }
301    if links > MAX_LINKS {
302        return Err(NavMeshDiagnostic::LinkCapacity {
303            count: links,
304            maximum: MAX_LINKS,
305        });
306    }
307    Ok(())
308}
309
310fn validate_triangles(triangles: &[NavTriangle]) -> Result<(), NavMeshDiagnostic> {
311    for (triangle, t) in triangles.iter().enumerate() {
312        for (vertex, p) in t.0.iter().enumerate() {
313            if !p.is_finite() {
314                return Err(NavMeshDiagnostic::NonFiniteVertex { triangle, vertex });
315            }
316            if p.abs().max_element() > MAX_COORDINATE {
317                return Err(NavMeshDiagnostic::VertexOutOfRange { triangle, vertex });
318            }
319        }
320        let n = cross(difference(t.0[1], t.0[0]), difference(t.0[2], t.0[0]));
321        if dot(n, n) < f64::from(1e-6_f32) {
322            return Err(NavMeshDiagnostic::DegenerateTriangle { triangle });
323        }
324    }
325    Ok(())
326}
327
328fn shared_edge(a: NavTriangle, b: NavTriangle) -> Option<(usize, usize)> {
329    for edge in 0..3 {
330        for other in 0..3 {
331            let [a0, a1] = [a.0[edge], a.0[(edge + 1) % 3]];
332            let [b0, b1] = [b.0[other], b.0[(other + 1) % 3]];
333            if (a0 == b0 && a1 == b1) || (a0 == b1 && a1 == b0) {
334                return Some((edge, other));
335            }
336        }
337    }
338    None
339}
340
341fn validate_topology(triangles: &[NavTriangle]) -> Result<(), NavMeshDiagnostic> {
342    let mut neighbors = vec![[None; 3]; triangles.len()];
343    let mut winding = None;
344    for (i, a) in triangles.iter().enumerate() {
345        for (j, b) in triangles.iter().enumerate().skip(i + 1) {
346            if a.0.iter().all(|p| b.0.contains(p)) {
347                return Err(NavMeshDiagnostic::DuplicateTriangle {
348                    triangle: j,
349                    other: i,
350                });
351            }
352            if let Some((edge, other_edge)) = shared_edge(*a, *b) {
353                for (triangle, edge, neighbor) in [(i, edge, j), (j, other_edge, i)] {
354                    if let Some(first_neighbor) = neighbors[triangle][edge] {
355                        return Err(NavMeshDiagnostic::NonManifoldEdge {
356                            triangle,
357                            edge,
358                            first_neighbor,
359                            second_neighbor: neighbor,
360                        });
361                    }
362                    neighbors[triangle][edge] = Some(neighbor);
363                }
364                if a.0[edge] == b.0[other_edge] && winding.is_none() {
365                    winding = Some(NavMeshDiagnostic::InconsistentWinding {
366                        triangle: i,
367                        edge,
368                        neighbor: j,
369                        neighbor_edge: other_edge,
370                    });
371                }
372            }
373        }
374    }
375    // A third face on an edge is more useful to report than the winding conflict
376    // that inevitably accompanies it.
377    winding.map_or(Ok(()), Err)
378}
379
380fn on_edge(p: Vec3, a: Vec3, b: Vec3) -> bool {
381    let edge = difference(b, a);
382    let offset = difference(p, a);
383    let t = (dot(offset, edge) / dot(edge, edge)).clamp(0., 1.);
384    let distance = [
385        offset[0] - t * edge[0],
386        offset[1] - t * edge[1],
387        offset[2] - t * edge[2],
388    ];
389    dot(distance, distance) <= 0.001_f64.powi(2)
390}
391
392fn validate_links(
393    triangles: &[NavTriangle],
394    links: &[TraversalLink],
395    checked: bool,
396) -> Result<(), NavMeshDiagnostic> {
397    for (link, l) in links.iter().enumerate() {
398        let from = triangles
399            .get(l.from)
400            .ok_or(NavMeshDiagnostic::SourceOutOfBounds {
401                link,
402                triangle: l.from,
403            })?;
404        let to = triangles
405            .get(l.to)
406            .ok_or(NavMeshDiagnostic::DestinationOutOfBounds {
407                link,
408                triangle: l.to,
409            })?;
410        if checked && l.from == l.to {
411            return Err(NavMeshDiagnostic::SelfLink {
412                link,
413                triangle: l.from,
414            });
415        }
416        if !l.cost.is_finite() || l.cost < 0. {
417            return Err(NavMeshDiagnostic::InvalidLinkCost { link });
418        }
419        if !from.contains(l.entry) {
420            return Err(NavMeshDiagnostic::InvalidEntry {
421                link,
422                triangle: l.from,
423            });
424        }
425        if !to.contains(l.exit) {
426            return Err(NavMeshDiagnostic::InvalidExit {
427                link,
428                triangle: l.to,
429            });
430        }
431        if l.kind == Traversal::Walk {
432            if l.entry.distance(l.exit) > 0.001 {
433                return Err(NavMeshDiagnostic::PortalMismatch { link });
434            }
435            if checked {
436                let (edge, _) =
437                    shared_edge(*from, *to).ok_or(NavMeshDiagnostic::MissingSharedEdge {
438                        link,
439                        from: l.from,
440                        to: l.to,
441                    })?;
442                let a = from.0[edge];
443                let b = from.0[(edge + 1) % 3];
444                if !on_edge(l.entry, a, b) || !on_edge(l.exit, a, b) {
445                    return Err(NavMeshDiagnostic::PortalOffEdge {
446                        link,
447                        triangle: l.from,
448                        edge,
449                    });
450                }
451            }
452            if !to.contains(l.entry) {
453                return Err(NavMeshDiagnostic::InvalidEntry {
454                    link,
455                    triangle: l.to,
456                });
457            }
458        }
459    }
460    Ok(())
461}
462
463fn welded_links(triangles: &[NavTriangle]) -> Result<Vec<TraversalLink>, NavMeshDiagnostic> {
464    let mut links = Vec::new();
465    for (i, a) in triangles.iter().enumerate() {
466        for (j, b) in triangles.iter().enumerate().skip(i + 1) {
467            let mut shared = [Vec3::ZERO; 3];
468            let mut n = 0;
469            for v in a.0 {
470                if b.0.contains(&v) {
471                    shared[n] = v;
472                    n += 1;
473                }
474            }
475            if n == 2 {
476                let p = (shared[0] + shared[1]) * 0.5;
477                let cost = a.center().distance(b.center());
478                for (from, to) in [(i, j), (j, i)] {
479                    if links.len() == MAX_LINKS {
480                        return Err(NavMeshDiagnostic::LinkCapacity {
481                            count: MAX_LINKS + 1,
482                            maximum: MAX_LINKS,
483                        });
484                    }
485                    links.push(TraversalLink {
486                        from,
487                        to,
488                        entry: p,
489                        exit: p,
490                        kind: Traversal::Walk,
491                        cost,
492                        enabled: true,
493                    });
494                }
495            }
496        }
497    }
498    Ok(links)
499}
500
501pub struct NavMesh {
502    triangles: Vec<NavTriangle>,
503    links: Vec<TraversalLink>,
504    edges: Vec<Vec<usize>>,
505    blocked: Vec<bool>,
506    revision: u64,
507    identity: u64,
508}
509impl NavMesh {
510    /// Construction allocates; searches reuse their own scratch space. Retains
511    /// permissive legacy adjacency; use [`Self::new_checked`] for authoring.
512    pub fn new(
513        triangles: Vec<NavTriangle>,
514        links: Vec<TraversalLink>,
515    ) -> Result<Self, NavigationError> {
516        validate_capacity(triangles.len(), links.len())
517            .map_err(NavMeshDiagnostic::navigation_error)?;
518        validate_triangles(&triangles).map_err(NavMeshDiagnostic::navigation_error)?;
519        validate_links(&triangles, &links, false).map_err(NavMeshDiagnostic::navigation_error)?;
520        Self::build(triangles, links).map_err(NavMeshDiagnostic::navigation_error)
521    }
522
523    /// Inspect borrowed authoring data without allocating a mesh identity or
524    /// changing a live mesh. Scratch storage is at most three neighbor slots per
525    /// face; topology checking is O(triangles²), bounded to 2048 faces/16384 links.
526    ///
527    /// Checks finite, bounded, nondegenerate faces, duplicates, manifold shared
528    /// edges and consistent relative winding. Walk links require an exact shared
529    /// edge and endpoints within 0.001 units of its segment. Disabled links are
530    /// checked too; non-walk links may bridge gaps. Self links are rejected.
531    /// Missing reverse links are allowed: authored links remain directional.
532    /// This does not detect geometric overlaps, T-junctions, clearance or slope.
533    ///
534    /// ```
535    /// use ferravex_math::Vec3;
536    /// use ferravex_play::navigation::{NavMesh, NavMeshDiagnostic, NavTriangle};
537    /// let faces = [NavTriangle([Vec3::ZERO, Vec3::X, Vec3::X])];
538    /// assert_eq!(NavMesh::validate(&faces, &[]),
539    ///     Err(NavMeshDiagnostic::DegenerateTriangle { triangle: 0 }));
540    /// ```
541    pub fn validate(
542        triangles: &[NavTriangle],
543        links: &[TraversalLink],
544    ) -> Result<(), NavMeshDiagnostic> {
545        validate_capacity(triangles.len(), links.len())?;
546        validate_triangles(triangles)?;
547        validate_topology(triangles)?;
548        validate_links(triangles, links, true)
549    }
550
551    /// Construct only after all [`Self::validate`] checks pass. Errors carry
552    /// input indices and implement [`std::fmt::Display`] for editor messages.
553    ///
554    /// ```
555    /// use ferravex_math::Vec3;
556    /// use ferravex_play::navigation::{NavMesh, NavTriangle};
557    /// let mesh = NavMesh::new_checked(
558    ///     vec![NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z])], vec![])?;
559    /// assert_eq!(mesh.locate(Vec3::ZERO), Some(0));
560    /// # Ok::<(), ferravex_play::navigation::NavMeshDiagnostic>(())
561    /// ```
562    pub fn new_checked(
563        triangles: Vec<NavTriangle>,
564        links: Vec<TraversalLink>,
565    ) -> Result<Self, NavMeshDiagnostic> {
566        Self::validate(&triangles, &links)?;
567        Self::build(triangles, links)
568    }
569
570    /// Replace an authored mesh transactionally. On error, geometry, block/link
571    /// state, identity and existing searches are untouched. On success, faces
572    /// start unblocked, link enabled flags come from the input, and every old
573    /// search/result is invalidated by a fresh identity (even for identical data).
574    ///
575    /// ```
576    /// use ferravex_math::Vec3;
577    /// use ferravex_play::navigation::{NavMesh, NavTriangle};
578    /// let mut mesh = NavMesh::new_checked(
579    ///     vec![NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z])], vec![])?;
580    /// assert!(mesh.replace_checked(vec![], vec![]).is_err());
581    /// assert_eq!(mesh.locate(Vec3::ZERO), Some(0));
582    /// # Ok::<(), ferravex_play::navigation::NavMeshDiagnostic>(())
583    /// ```
584    pub fn replace_checked(
585        &mut self,
586        triangles: Vec<NavTriangle>,
587        links: Vec<TraversalLink>,
588    ) -> Result<(), NavMeshDiagnostic> {
589        let replacement = Self::new_checked(triangles, links)?;
590        *self = replacement;
591        Ok(())
592    }
593
594    fn build(
595        triangles: Vec<NavTriangle>,
596        links: Vec<TraversalLink>,
597    ) -> Result<Self, NavMeshDiagnostic> {
598        #[allow(deprecated)] // Preserve the workspace Rust 1.88 minimum.
599        let identity = super::NEXT_GRID_ID
600            .fetch_update(
601                std::sync::atomic::Ordering::Relaxed,
602                std::sync::atomic::Ordering::Relaxed,
603                |v| v.checked_add(1),
604            )
605            .map_err(|_| NavMeshDiagnostic::RevisionExhausted)?;
606        let mut edges = vec![Vec::new(); triangles.len()];
607        for (i, l) in links.iter().enumerate() {
608            edges[l.from].push(i);
609        }
610        Ok(Self {
611            identity,
612            blocked: vec![false; triangles.len()],
613            triangles,
614            links,
615            edges,
616            revision: 0,
617        })
618    }
619    /// Weld exact shared vertex edges; O(triangles²) setup, bounded to 2048 faces.
620    /// Use [`Self::welded_checked`] to diagnose malformed adjacency before welding.
621    pub fn welded(triangles: Vec<NavTriangle>) -> Result<Self, NavigationError> {
622        validate_capacity(triangles.len(), 0).map_err(NavMeshDiagnostic::navigation_error)?;
623        let links = welded_links(&triangles).map_err(NavMeshDiagnostic::navigation_error)?;
624        Self::new(triangles, links)
625    }
626
627    /// Validate geometry and topology before generating bidirectional walk
628    /// portals, then check generated endpoints before publishing the mesh.
629    /// Uses the same midpoint/cost/order as [`Self::welded`] on valid input.
630    ///
631    /// ```
632    /// use ferravex_math::Vec3;
633    /// use ferravex_play::navigation::{NavMesh, NavTriangle};
634    /// let mesh = NavMesh::welded_checked(vec![
635    ///     NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z]),
636    ///     NavTriangle([Vec3::X, Vec3::X + Vec3::Z, Vec3::Z]),
637    /// ])?;
638    /// assert!(mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).is_ok());
639    /// # Ok::<(), ferravex_play::navigation::NavMeshDiagnostic>(())
640    /// ```
641    pub fn welded_checked(triangles: Vec<NavTriangle>) -> Result<Self, NavMeshDiagnostic> {
642        validate_capacity(triangles.len(), 0)?;
643        validate_triangles(&triangles)?;
644        validate_topology(&triangles)?;
645        let links = welded_links(&triangles)?;
646        validate_links(&triangles, &links, true)?;
647        Self::build(triangles, links)
648    }
649    pub fn locate(&self, p: Vec3) -> Option<usize> {
650        self.triangles
651            .iter()
652            .enumerate()
653            .find(|(i, t)| !self.blocked[*i] && t.contains(p))
654            .map(|(i, _)| i)
655    }
656    pub fn set_blocked(&mut self, index: usize, blocked: bool) -> Result<(), NavigationError> {
657        let value = self
658            .blocked
659            .get_mut(index)
660            .ok_or(NavigationError::OutOfBounds)?;
661        if *value != blocked {
662            let revision = self
663                .revision
664                .checked_add(1)
665                .ok_or(NavigationError::RevisionExhausted)?;
666            *value = blocked;
667            self.revision = revision;
668        }
669        Ok(())
670    }
671    pub fn set_link_enabled(&mut self, index: usize, enabled: bool) -> Result<(), NavigationError> {
672        let l = self
673            .links
674            .get_mut(index)
675            .ok_or(NavigationError::OutOfBounds)?;
676        if l.enabled != enabled {
677            let revision = self
678                .revision
679                .checked_add(1)
680                .ok_or(NavigationError::RevisionExhausted)?;
681            l.enabled = enabled;
682            self.revision = revision;
683        }
684        Ok(())
685    }
686    pub fn search(&self, start: Vec3, end: Vec3) -> Result<NavSearch, NavigationError> {
687        let a = self.locate(start).ok_or(NavigationError::BlockedEndpoint)?;
688        let b = self.locate(end).ok_or(NavigationError::BlockedEndpoint)?;
689        let n = self.triangles.len();
690        let mut cost = vec![f64::INFINITY; n];
691        cost[a] = 0.;
692        Ok(NavSearch {
693            identity: self.identity,
694            revision: self.revision,
695            cost,
696            previous: vec![None; n],
697            closed: vec![false; n],
698            start: a,
699            end: b,
700            end_point: end,
701            route: Vec::with_capacity(n * 3 + 2),
702            done: false,
703            current: None,
704            edge: 0,
705        })
706    }
707}
708/// Incremental Dijkstra search. Each node scan and outgoing edge consumes a path
709/// work unit. A mesh edit invalidates the search, including an existing result.
710pub struct NavSearch {
711    revision: u64,
712    identity: u64,
713    cost: Vec<f64>,
714    previous: Vec<Option<usize>>,
715    closed: Vec<bool>,
716    start: usize,
717    end: usize,
718    end_point: Vec3,
719    route: Vec<NavWaypoint>,
720    done: bool,
721    current: Option<usize>,
722    edge: usize,
723}
724impl NavSearch {
725    /// Returns true only when the route is complete; NoPath or mesh edits fail.
726    /// Up to 2048 distance comparisons select a node; one unit accounts that scan.
727    pub fn step(
728        &mut self,
729        mesh: &NavMesh,
730        budget: &mut WorkBudget,
731    ) -> Result<bool, NavigationError> {
732        if self.identity != mesh.identity
733            || self.revision != mesh.revision
734            || self.cost.len() != mesh.triangles.len()
735        {
736            return Err(NavigationError::InvalidInput);
737        }
738        if self.done {
739            return Ok(true);
740        }
741        while budget.spend_path_steps(1) {
742            if let Some(i) = self.current {
743                if let Some(&link) = mesh.edges[i].get(self.edge) {
744                    self.edge += 1;
745                    let l = mesh.links[link];
746                    if l.enabled && !mesh.blocked[l.to] && !self.closed[l.to] {
747                        let cost = self.cost[i] + f64::from(l.cost);
748                        if cost < self.cost[l.to] {
749                            self.cost[l.to] = cost;
750                            self.previous[l.to] = Some(link);
751                        }
752                    }
753                } else {
754                    self.current = None;
755                }
756            } else {
757                let next = self
758                    .cost
759                    .iter()
760                    .enumerate()
761                    .filter(|(i, c)| !self.closed[*i] && c.is_finite())
762                    .min_by(|(i, a), (j, b)| a.total_cmp(b).then(i.cmp(j)))
763                    .map(|(i, _)| i)
764                    .ok_or(NavigationError::NoPath)?;
765                if next == self.end {
766                    self.route.push(NavWaypoint {
767                        position: self.end_point,
768                        traversal: Traversal::Walk,
769                    });
770                    self.route.push(NavWaypoint {
771                        position: mesh.triangles[self.end].center(),
772                        traversal: Traversal::Walk,
773                    });
774                    let mut node = self.end;
775                    while node != self.start {
776                        let l = mesh.links[self.previous[node].ok_or(NavigationError::NoPath)?];
777                        self.route.push(NavWaypoint {
778                            position: l.exit,
779                            traversal: l.kind,
780                        });
781                        if l.kind != Traversal::Walk {
782                            self.route.push(NavWaypoint {
783                                position: l.entry,
784                                traversal: Traversal::Walk,
785                            });
786                        }
787                        self.route.push(NavWaypoint {
788                            position: mesh.triangles[l.from].center(),
789                            traversal: Traversal::Walk,
790                        });
791                        node = l.from;
792                    }
793                    self.route.reverse();
794                    self.done = true;
795                    return Ok(true);
796                }
797                self.closed[next] = true;
798                self.current = Some(next);
799                self.edge = 0;
800            }
801        }
802        Ok(false)
803    }
804    pub fn route<'a>(&'a self, mesh: &NavMesh) -> Result<&'a [NavWaypoint], NavigationError> {
805        if self.identity != mesh.identity || self.revision != mesh.revision || !self.done {
806            Err(NavigationError::InvalidInput)
807        } else {
808            Ok(&self.route)
809        }
810    }
811}
812#[cfg(test)]
813mod tests {
814    use super::*;
815    fn faces() -> Vec<NavTriangle> {
816        vec![
817            NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z]),
818            NavTriangle([Vec3::X, Vec3::X + Vec3::Z, Vec3::Z]),
819        ]
820    }
821    #[test]
822    fn portals_budget_and_revision() {
823        let mut m = NavMesh::welded(faces()).unwrap();
824        let mut s = m.search(Vec3::ZERO, (Vec3::X + Vec3::Z) * 0.9).unwrap();
825        assert!(!s.step(&m, &mut WorkBudget::new(0, 0, 0)).unwrap());
826        for _ in 0..20 {
827            if s.step(&m, &mut WorkBudget::new(0, 0, 1)).unwrap() {
828                break;
829            }
830        }
831        assert!(s.route(&m).unwrap().len() >= 2);
832        m.set_blocked(1, true).unwrap();
833        assert!(s.route(&m).is_err());
834        assert!(s.step(&m, &mut WorkBudget::new(0, 0, 99)).is_err());
835    }
836    #[test]
837    fn directional_links_need_host_traversal_and_disable() {
838        let mut f = faces();
839        for v in &mut f[1].0 {
840            *v += Vec3::Y * 2.;
841        }
842        let l = TraversalLink {
843            from: 0,
844            to: 1,
845            entry: Vec3::X,
846            exit: Vec3::X + Vec3::Y * 2.,
847            kind: Traversal::Climb,
848            cost: 3.,
849            enabled: true,
850        };
851        let mut m = NavMesh::new(f, vec![l]).unwrap();
852        let mut s = m.search(Vec3::ZERO, Vec3::X + Vec3::Y * 2.).unwrap();
853        assert!(s.step(&m, &mut WorkBudget::new(0, 0, 30)).unwrap());
854        assert!(
855            s.route(&m)
856                .unwrap()
857                .iter()
858                .any(|w| w.traversal == Traversal::Climb)
859        );
860        let mut reverse = m.search(Vec3::X + Vec3::Y * 2., Vec3::ZERO).unwrap();
861        assert_eq!(
862            reverse.step(&m, &mut WorkBudget::new(0, 0, 30)),
863            Err(NavigationError::NoPath)
864        );
865        m.set_link_enabled(0, false).unwrap();
866        let mut s = m.search(Vec3::ZERO, Vec3::X + Vec3::Y * 2.).unwrap();
867        assert_eq!(
868            s.step(&m, &mut WorkBudget::new(0, 0, 30)),
869            Err(NavigationError::NoPath)
870        );
871    }
872
873    fn walk_link() -> TraversalLink {
874        TraversalLink {
875            from: 0,
876            to: 1,
877            entry: (Vec3::X + Vec3::Z) * 0.5,
878            exit: (Vec3::X + Vec3::Z) * 0.5,
879            kind: Traversal::Walk,
880            cost: 1.,
881            enabled: true,
882        }
883    }
884
885    fn completed_route(mesh: &NavMesh) -> Vec<(Vec3, Traversal)> {
886        let mut search = mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).unwrap();
887        assert!(search.step(mesh, &mut WorkBudget::new(0, 0, 30)).unwrap());
888        search
889            .route(mesh)
890            .unwrap()
891            .iter()
892            .map(|w| (w.position, w.traversal))
893            .collect()
894    }
895
896    #[test]
897    fn diagnostic_capacity_is_checked_before_geometry() {
898        assert_eq!(
899            NavMesh::validate(&[], &[]),
900            Err(NavMeshDiagnostic::EmptyMesh)
901        );
902        let too_many = vec![NavTriangle([Vec3::ZERO; 3]); MAX_TRIANGLES + 1];
903        assert_eq!(
904            NavMesh::validate(&too_many, &[]),
905            Err(NavMeshDiagnostic::TriangleCapacity {
906                count: MAX_TRIANGLES + 1,
907                maximum: MAX_TRIANGLES,
908            })
909        );
910        assert_eq!(
911            NavMesh::validate(&faces(), &vec![walk_link(); MAX_LINKS + 1]),
912            Err(NavMeshDiagnostic::LinkCapacity {
913                count: MAX_LINKS + 1,
914                maximum: MAX_LINKS
915            })
916        );
917        // Exact limits remain inclusive. Repeated directional links are legal.
918        assert!(NavMesh::validate(&faces(), &vec![walk_link(); MAX_LINKS]).is_ok());
919        assert_eq!(
920            NavMesh::new(vec![], vec![]).err(),
921            Some(NavigationError::Capacity)
922        );
923    }
924
925    #[test]
926    fn diagnostic_identifies_nonfinite_and_out_of_range_vertices() {
927        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
928            let mut f = faces();
929            f[1].0[2].y = value;
930            assert_eq!(
931                NavMesh::validate(&f, &[]),
932                Err(NavMeshDiagnostic::NonFiniteVertex {
933                    triangle: 1,
934                    vertex: 2
935                })
936            );
937        }
938        let mut f = faces();
939        f[1].0[1].x = MAX_COORDINATE + 1.;
940        assert_eq!(
941            NavMesh::validate(&f, &[]),
942            Err(NavMeshDiagnostic::VertexOutOfRange {
943                triangle: 1,
944                vertex: 1
945            })
946        );
947    }
948
949    #[test]
950    fn diagnostic_rejects_repeated_collinear_and_tiny_faces() {
951        for triangle in [
952            NavTriangle([Vec3::ZERO, Vec3::X, Vec3::X]),
953            NavTriangle([Vec3::ZERO, Vec3::X, Vec3::X * 2.]),
954            NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z * 0.0001]),
955        ] {
956            assert_eq!(
957                NavMesh::welded_checked(vec![triangle]).err(),
958                Some(NavMeshDiagnostic::DegenerateTriangle { triangle: 0 })
959            );
960            assert_eq!(
961                NavMesh::new(vec![triangle], vec![]).err(),
962                Some(NavigationError::InvalidInput)
963            );
964        }
965    }
966
967    #[test]
968    fn relative_winding_accepts_both_orientations_and_preserves_routes() {
969        for reverse in [false, true] {
970            let mut f = faces();
971            if reverse {
972                for t in &mut f {
973                    t.0.swap(1, 2);
974                }
975            }
976            let legacy = NavMesh::welded(f.clone()).unwrap();
977            let checked = NavMesh::welded_checked(f).unwrap();
978            assert_eq!(completed_route(&legacy), completed_route(&checked));
979            assert_eq!(checked.links.len(), 2);
980            for (a, b) in legacy.links.iter().zip(&checked.links) {
981                assert_eq!((a.from, a.to, a.cost), (b.from, b.to, b.cost));
982            }
983        }
984        let mut f = faces();
985        f[1].0.swap(1, 2);
986        assert_eq!(
987            NavMesh::validate(&f, &[]),
988            Err(NavMeshDiagnostic::InconsistentWinding {
989                triangle: 0,
990                edge: 1,
991                neighbor: 1,
992                neighbor_edge: 0,
993            })
994        );
995        assert!(
996            NavMesh::welded(f).is_ok(),
997            "legacy winding remains permissive"
998        );
999    }
1000
1001    #[test]
1002    fn disconnected_and_folded_faces_do_not_require_an_up_axis() {
1003        let a = NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z]);
1004        let folded = NavTriangle([Vec3::X, Vec3::ZERO, Vec3::Y]);
1005        assert!(NavMesh::welded_checked(vec![a, folded]).is_ok());
1006        let mut disconnected = a;
1007        disconnected.0.swap(1, 2);
1008        for v in &mut disconnected.0 {
1009            *v += Vec3::Y * 2.;
1010        }
1011        assert!(NavMesh::welded_checked(vec![a, disconnected]).is_ok());
1012    }
1013
1014    #[test]
1015    fn duplicate_faces_report_both_indices_in_any_order() {
1016        let a = faces()[0];
1017        for vertices in [a.0, [a.0[2], a.0[0], a.0[1]], [a.0[0], a.0[2], a.0[1]]] {
1018            assert_eq!(
1019                NavMesh::validate(&[a, NavTriangle(vertices)], &[]),
1020                Err(NavMeshDiagnostic::DuplicateTriangle {
1021                    triangle: 1,
1022                    other: 0
1023                })
1024            );
1025        }
1026    }
1027
1028    #[test]
1029    fn nonmanifold_edge_reports_third_face_before_winding() {
1030        let f = vec![
1031            NavTriangle([Vec3::ZERO, Vec3::X, Vec3::Z]),
1032            NavTriangle([Vec3::X, Vec3::ZERO, Vec3::Y]),
1033            NavTriangle([Vec3::ZERO, Vec3::X, -Vec3::Z]),
1034        ];
1035        assert_eq!(
1036            NavMesh::validate(&f, &[]),
1037            Err(NavMeshDiagnostic::NonManifoldEdge {
1038                triangle: 0,
1039                edge: 0,
1040                first_neighbor: 1,
1041                second_neighbor: 2,
1042            })
1043        );
1044    }
1045
1046    #[test]
1047    fn links_report_indices_costs_and_disabled_errors() {
1048        let f = faces();
1049        let base = walk_link();
1050        assert_eq!(
1051            NavMesh::validate(
1052                &f,
1053                &[
1054                    base,
1055                    TraversalLink {
1056                        from: 5,
1057                        enabled: false,
1058                        ..base
1059                    }
1060                ]
1061            ),
1062            Err(NavMeshDiagnostic::SourceOutOfBounds {
1063                link: 1,
1064                triangle: 5
1065            })
1066        );
1067        assert_eq!(
1068            NavMesh::validate(&f, &[TraversalLink { to: 6, ..base }]),
1069            Err(NavMeshDiagnostic::DestinationOutOfBounds {
1070                link: 0,
1071                triangle: 6
1072            })
1073        );
1074        assert_eq!(
1075            NavMesh::validate(&f, &[TraversalLink { to: 0, ..base }]),
1076            Err(NavMeshDiagnostic::SelfLink {
1077                link: 0,
1078                triangle: 0
1079            })
1080        );
1081        for cost in [-1., f32::NAN, f32::INFINITY] {
1082            assert_eq!(
1083                NavMesh::validate(&f, &[TraversalLink { cost, ..base }]),
1084                Err(NavMeshDiagnostic::InvalidLinkCost { link: 0 })
1085            );
1086        }
1087        assert!(NavMesh::new_checked(f, vec![TraversalLink { cost: 0., ..base }]).is_ok());
1088    }
1089
1090    #[test]
1091    fn links_report_nonfinite_and_outside_endpoints() {
1092        let f = faces();
1093        let base = walk_link();
1094        for position in [
1095            Vec3::splat(f32::NAN),
1096            Vec3::splat(f32::INFINITY),
1097            Vec3::Y,
1098            Vec3::X * 2.,
1099        ] {
1100            assert_eq!(
1101                NavMesh::validate(
1102                    &f,
1103                    &[TraversalLink {
1104                        entry: position,
1105                        ..base
1106                    }]
1107                ),
1108                Err(NavMeshDiagnostic::InvalidEntry {
1109                    link: 0,
1110                    triangle: 0
1111                })
1112            );
1113            assert_eq!(
1114                NavMesh::validate(
1115                    &f,
1116                    &[TraversalLink {
1117                        exit: position,
1118                        ..base
1119                    }]
1120                ),
1121                Err(NavMeshDiagnostic::InvalidExit {
1122                    link: 0,
1123                    triangle: 1
1124                })
1125            );
1126        }
1127    }
1128
1129    #[test]
1130    fn walk_portals_require_an_edge_not_a_vertex_or_overlap() {
1131        let a = faces()[0];
1132        for b in [
1133            NavTriangle([Vec3::ZERO, -Vec3::X, -Vec3::Z]),
1134            NavTriangle([Vec3::ZERO, Vec3::X * 2., Vec3::Z * 2.]),
1135        ] {
1136            let link = TraversalLink {
1137                entry: Vec3::ZERO,
1138                exit: Vec3::ZERO,
1139                ..walk_link()
1140            };
1141            assert!(NavMesh::new(vec![a, b], vec![link]).is_ok());
1142            assert_eq!(
1143                NavMesh::new_checked(vec![a, b], vec![link]).err(),
1144                Some(NavMeshDiagnostic::MissingSharedEdge {
1145                    link: 0,
1146                    from: 0,
1147                    to: 1
1148                })
1149            );
1150        }
1151    }
1152
1153    #[test]
1154    fn walk_portals_must_match_and_lie_on_the_shared_segment() {
1155        let mut link = walk_link();
1156        link.exit += (Vec3::X - Vec3::Z) * 0.01;
1157        assert_eq!(
1158            NavMesh::validate(&faces(), &[link]),
1159            Err(NavMeshDiagnostic::PortalMismatch { link: 0 })
1160        );
1161
1162        let mut f = faces();
1163        for t in &mut f {
1164            for v in &mut t.0 {
1165                *v *= 1000.;
1166            }
1167        }
1168        // Both faces' barycentric tolerance accepts these points, but the
1169        // portal's world-space tolerance excludes an interior point and an
1170        // extension past the endpoint of the shared segment.
1171        for p in [
1172            (Vec3::X + Vec3::Z) * 500. - Vec3::X * 0.005,
1173            Vec3::X * 1000. + (Vec3::X - Vec3::Z) * 0.005,
1174        ] {
1175            assert!(f[0].contains(p) && f[1].contains(p));
1176            link.entry = p;
1177            link.exit = p;
1178            assert_eq!(
1179                NavMesh::validate(&f, &[link]),
1180                Err(NavMeshDiagnostic::PortalOffEdge {
1181                    link: 0,
1182                    triangle: 0,
1183                    edge: 1
1184                })
1185            );
1186        }
1187        // Segment endpoints are valid portals, too.
1188        for p in [Vec3::X, Vec3::Z] {
1189            assert!(
1190                NavMesh::validate(
1191                    &faces(),
1192                    &[TraversalLink {
1193                        entry: p,
1194                        exit: p,
1195                        ..walk_link()
1196                    }]
1197                )
1198                .is_ok()
1199            );
1200        }
1201    }
1202
1203    #[test]
1204    fn checked_traversal_links_still_cross_gaps_directionally() {
1205        let mut f = faces();
1206        for p in &mut f[1].0 {
1207            *p += Vec3::Y * 2.;
1208        }
1209        for kind in [Traversal::Jump, Traversal::Drop, Traversal::Climb] {
1210            let link = TraversalLink {
1211                entry: Vec3::X,
1212                exit: Vec3::X + Vec3::Y * 2.,
1213                kind,
1214                ..walk_link()
1215            };
1216            let mesh = NavMesh::new_checked(f.clone(), vec![link]).unwrap();
1217            let mut forward = mesh.search(Vec3::ZERO, link.exit).unwrap();
1218            assert!(forward.step(&mesh, &mut WorkBudget::new(0, 0, 30)).unwrap());
1219            assert!(
1220                forward
1221                    .route(&mesh)
1222                    .unwrap()
1223                    .iter()
1224                    .any(|p| p.traversal == kind)
1225            );
1226            let mut reverse = mesh.search(link.exit, Vec3::ZERO).unwrap();
1227            assert_eq!(
1228                reverse.step(&mesh, &mut WorkBudget::new(0, 0, 30)),
1229                Err(NavigationError::NoPath)
1230            );
1231        }
1232    }
1233
1234    #[test]
1235    fn thin_large_coordinate_faces_remain_locatable() {
1236        let triangle = NavTriangle([
1237            Vec3::ZERO,
1238            Vec3::X * MAX_COORDINATE,
1239            Vec3::X * MAX_COORDINATE + Vec3::Z,
1240        ]);
1241        let interior = Vec3::X * 750_000. + Vec3::Z * 0.25;
1242        assert!(triangle.contains(interior));
1243        for p in triangle.0 {
1244            assert!(triangle.contains(p));
1245        }
1246        assert!(!triangle.contains(interior + Vec3::Y * 0.01));
1247        let mesh = NavMesh::welded_checked(vec![triangle]).unwrap();
1248        assert_eq!(mesh.locate(interior), Some(0));
1249        let mut search = mesh.search(interior, triangle.0[2]).unwrap();
1250        assert!(search.step(&mesh, &mut WorkBudget::new(0, 0, 1)).unwrap());
1251        assert_eq!(
1252            search.route(&mesh).unwrap().last().unwrap().position,
1253            triangle.0[2]
1254        );
1255    }
1256
1257    #[test]
1258    fn contains_rejects_malformed_faces_and_points() {
1259        assert!(!NavTriangle([Vec3::ZERO; 3]).contains(Vec3::ZERO));
1260        assert!(!NavTriangle([Vec3::ZERO, Vec3::X, Vec3::splat(f32::NAN)]).contains(Vec3::ZERO));
1261        assert!(!faces()[0].contains(Vec3::splat(f32::NAN)));
1262    }
1263
1264    #[test]
1265    fn failed_replace_preserves_state_and_completed_and_pending_searches() {
1266        let mut f = faces();
1267        let mut extra = f[0];
1268        for v in &mut extra.0 {
1269            *v += Vec3::Y * 3.;
1270        }
1271        f.push(extra);
1272        let mut mesh = NavMesh::welded_checked(f).unwrap();
1273        mesh.set_blocked(2, true).unwrap();
1274        mesh.set_link_enabled(1, false).unwrap();
1275        let identity = mesh.identity;
1276        let revision = mesh.revision;
1277        let mut done = mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).unwrap();
1278        assert!(done.step(&mesh, &mut WorkBudget::new(0, 0, 30)).unwrap());
1279        let mut pending = mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).unwrap();
1280        assert!(!pending.step(&mesh, &mut WorkBudget::new(0, 0, 1)).unwrap());
1281        assert_eq!(
1282            mesh.replace_checked(
1283                faces(),
1284                vec![
1285                    walk_link(),
1286                    TraversalLink {
1287                        to: 99,
1288                        ..walk_link()
1289                    }
1290                ]
1291            ),
1292            Err(NavMeshDiagnostic::DestinationOutOfBounds {
1293                link: 1,
1294                triangle: 99
1295            })
1296        );
1297        assert_eq!((mesh.identity, mesh.revision), (identity, revision));
1298        assert_eq!(mesh.triangles.len(), 3);
1299        assert_eq!(mesh.blocked, [false, false, true]);
1300        assert!(!mesh.links[1].enabled);
1301        assert!(done.route(&mesh).is_ok());
1302        assert!(pending.step(&mesh, &mut WorkBudget::new(0, 0, 30)).unwrap());
1303        let mut reverse = mesh.search(Vec3::X + Vec3::Z, Vec3::ZERO).unwrap();
1304        assert_eq!(
1305            reverse.step(&mesh, &mut WorkBudget::new(0, 0, 30)),
1306            Err(NavigationError::NoPath)
1307        );
1308    }
1309
1310    #[test]
1311    fn successful_replace_resets_state_and_invalidates_all_old_searches() {
1312        let mut mesh = NavMesh::welded_checked(faces()).unwrap();
1313        let mut done = mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).unwrap();
1314        assert!(done.step(&mesh, &mut WorkBudget::new(0, 0, 30)).unwrap());
1315        let mut pending = mesh.search(Vec3::ZERO, Vec3::X + Vec3::Z).unwrap();
1316        let identity = mesh.identity;
1317        mesh.replace_checked(faces(), vec![walk_link()]).unwrap();
1318        assert_ne!(mesh.identity, identity);
1319        assert!(done.route(&mesh).is_err());
1320        assert!(pending.step(&mesh, &mut WorkBudget::new(0, 0, 30)).is_err());
1321        mesh.set_blocked(1, true).unwrap();
1322        mesh.set_link_enabled(0, false).unwrap();
1323        mesh.replace_checked(faces(), vec![walk_link()]).unwrap();
1324        assert_eq!(mesh.revision, 0);
1325        assert_eq!(mesh.blocked, [false, false]);
1326        assert!(mesh.links[0].enabled);
1327        assert!(!completed_route(&mesh).is_empty());
1328    }
1329
1330    #[test]
1331    fn diagnostics_display_actionable_indices() {
1332        let diagnostic = NavMeshDiagnostic::InconsistentWinding {
1333            triangle: 2,
1334            edge: 1,
1335            neighbor: 5,
1336            neighbor_edge: 0,
1337        };
1338        let text = diagnostic.to_string();
1339        assert!(text.contains("triangle 2 edge 1"));
1340        assert!(text.contains("triangle 5 edge 0"));
1341        assert!(text.contains("reverse"));
1342        let error: &dyn std::error::Error = &diagnostic;
1343        assert!(error.source().is_none());
1344    }
1345}