raasta 1.0.0

Raasta — navigation and pathfinding engine for AGNOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! D\* Lite — incremental replanning for dynamic environments.

use std::cmp::Ordering;
use std::collections::BinaryHeap;

use crate::grid::{GridPos, NavGrid};

#[cfg(feature = "logging")]
use tracing::instrument;

/// D\* Lite incremental pathfinder.
///
/// Searches backwards from goal to start. When the environment changes
/// (cells blocked/unblocked, costs changed), call [`update_cell()`](Self::update_cell)
/// to notify, then [`compute_path()`](Self::compute_path) to incrementally
/// update only the affected nodes.
///
/// More efficient than re-running A\* from scratch when few cells change.
pub struct DStarLite {
    start_idx: usize,
    goal_idx: usize,
    grid_width: usize,
    grid_height: usize,
    allow_diagonal: bool,
    /// g values: cost from node to goal.
    g: Vec<f32>,
    /// rhs values: one-step lookahead.
    rhs: Vec<f32>,
    /// Priority queue.
    open: BinaryHeap<DStarNode>,
    /// Key modifier (increases when start position moves).
    km: f32,
    /// Current start position (can change as agent moves).
    start: GridPos,
    /// Goal position.
    goal: GridPos,
}

#[derive(Clone, Copy)]
struct DStarNode {
    idx: usize,
    key: (f32, f32), // (k1, k2) priority
}

impl PartialEq for DStarNode {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
    }
}

impl Eq for DStarNode {}

impl PartialOrd for DStarNode {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for DStarNode {
    fn cmp(&self, other: &Self) -> Ordering {
        // Min-heap: reverse ordering. Compare k1 first, then k2.
        match other.key.0.partial_cmp(&self.key.0) {
            Some(Ordering::Equal) | None => other
                .key
                .1
                .partial_cmp(&self.key.1)
                .unwrap_or(Ordering::Equal),
            Some(ord) => ord,
        }
    }
}

impl DStarLite {
    /// Initialize D\* Lite for a grid from `start` to `goal`.
    ///
    /// Returns `None` if start or goal is outside the grid.
    #[cfg_attr(feature = "logging", instrument(skip(grid)))]
    #[must_use]
    pub fn new(grid: &NavGrid, start: GridPos, goal: GridPos) -> Option<Self> {
        let w = grid.width();
        let h = grid.height();
        let len = w * h;

        let start_idx = index(start.x, start.y, w, h)?;
        let goal_idx = index(goal.x, goal.y, w, h)?;

        let g = vec![f32::INFINITY; len];
        let rhs = vec![f32::INFINITY; len];

        let mut inst = Self {
            start_idx,
            goal_idx,
            grid_width: w,
            grid_height: h,
            allow_diagonal: grid.allow_diagonal,
            g,
            rhs,
            open: BinaryHeap::new(),
            km: 0.0,
            start,
            goal,
        };
        inst.rhs[goal_idx] = 0.0;

        let key = calculate_key(goal_idx, &inst.g, &inst.rhs, start_idx, 0.0, w);
        inst.open.push(DStarNode { idx: goal_idx, key });

        Some(inst)
    }

    /// Compute (or recompute) the shortest path.
    ///
    /// Processes all inconsistent cells so the g-field is fully consistent,
    /// enabling reliable full-path extraction via [`path()`](Self::path).
    ///
    /// Call after [`new()`](Self::new) for initial computation, or after
    /// [`update_cell()`](Self::update_cell) for incremental replanning.
    #[cfg_attr(feature = "logging", instrument(skip(self, grid)))]
    pub fn compute_path(&mut self, grid: &NavGrid) {
        self.process_queue(grid, false);
    }

    /// Compute the shortest path with early termination.
    ///
    /// Stops as soon as the start node is locally consistent, which is
    /// sufficient for single-step navigation via [`next_step()`](Self::next_step).
    /// For full path extraction, use [`compute_path()`](Self::compute_path)
    /// instead.
    #[cfg_attr(feature = "logging", instrument(skip(self, grid)))]
    pub fn compute_path_lazy(&mut self, grid: &NavGrid) {
        self.process_queue(grid, true);
    }

    /// Return the next cell to move to from the current start.
    ///
    /// This is the most efficient way to use D\* Lite: call
    /// [`compute_path_lazy()`](Self::compute_path_lazy), take one step with
    /// this method, then call [`set_start()`](Self::set_start) and repeat.
    ///
    /// Returns `None` if no path exists.
    #[must_use]
    pub fn next_step(&self, grid: &NavGrid) -> Option<GridPos> {
        if self.g[self.start_idx] == f32::INFINITY {
            return None;
        }
        if self.start_idx == self.goal_idx {
            return Some(self.goal);
        }

        let sx = (self.start_idx % self.grid_width) as i32;
        let sy = (self.start_idx / self.grid_width) as i32;
        let mut neighbors_buf = [(0i32, 0i32, 0.0f32); 8];
        let count = grid_neighbors(grid, sx, sy, self.allow_diagonal, &mut neighbors_buf);

        let mut best_idx = None;
        let mut best_cost = f32::INFINITY;
        for &(nx, ny, move_cost) in &neighbors_buf[..count] {
            if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                let cost = move_cost * grid.cost(nx, ny) + self.g[n_idx];
                if cost < best_cost {
                    best_cost = cost;
                    best_idx = Some(n_idx);
                }
            }
        }

        best_idx.map(|idx| {
            GridPos::new(
                (idx % self.grid_width) as i32,
                (idx / self.grid_width) as i32,
            )
        })
    }

    fn process_queue(&mut self, grid: &NavGrid, early_terminate: bool) {
        let mut neighbors_buf = [(0i32, 0i32, 0.0f32); 8];
        let mut iterations = 0u32;
        let max_iterations = (self.grid_width * self.grid_height * 4) as u32;

        loop {
            let Some(top) = self.open.peek() else {
                break;
            };
            if early_terminate {
                let top_key = top.key;
                let start_key = calculate_key(
                    self.start_idx,
                    &self.g,
                    &self.rhs,
                    self.start_idx,
                    self.km,
                    self.grid_width,
                );
                let g_neq_rhs = self.rhs[self.start_idx] != self.g[self.start_idx];
                if !(key_less(top_key, start_key) || g_neq_rhs) {
                    break;
                }
            }

            iterations += 1;
            if iterations > max_iterations {
                break;
            }

            let Some(u) = self.open.pop() else {
                break;
            };
            let u_idx = u.idx;
            let ux = (u_idx % self.grid_width) as i32;
            let uy = (u_idx / self.grid_width) as i32;

            let new_key = calculate_key(
                u_idx,
                &self.g,
                &self.rhs,
                self.start_idx,
                self.km,
                self.grid_width,
            );

            if key_less(u.key, new_key) {
                // Key is outdated: reinsert with updated key.
                self.open.push(DStarNode {
                    idx: u_idx,
                    key: new_key,
                });
            } else if (self.g[u_idx] - self.rhs[u_idx]).abs() <= f32::EPSILON {
                // Locally consistent — stale queue entry, skip.
                continue;
            } else if self.g[u_idx] > self.rhs[u_idx] {
                // Overconsistent.
                self.g[u_idx] = self.rhs[u_idx];
                let count = grid_neighbors(grid, ux, uy, self.allow_diagonal, &mut neighbors_buf);
                for &(nx, ny, _) in &neighbors_buf[..count] {
                    if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                        self.update_vertex(grid, n_idx);
                    }
                }
            } else {
                // Underconsistent.
                self.g[u_idx] = f32::INFINITY;
                // Update u itself.
                self.update_vertex(grid, u_idx);
                let count = grid_neighbors(grid, ux, uy, self.allow_diagonal, &mut neighbors_buf);
                for &(nx, ny, _) in &neighbors_buf[..count] {
                    if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                        self.update_vertex(grid, n_idx);
                    }
                }
            }
        }
    }

    /// Notify that a cell's cost or walkability has changed.
    ///
    /// Call this for each changed cell, then call [`compute_path()`](Self::compute_path)
    /// to replan.
    #[cfg_attr(feature = "logging", instrument(skip(self, grid)))]
    pub fn update_cell(&mut self, grid: &NavGrid, pos: GridPos) {
        if let Some(idx) = index(pos.x, pos.y, self.grid_width, self.grid_height) {
            self.update_vertex(grid, idx);
            // Also update all neighbors since their paths through this cell changed.
            let mut neighbors_buf = [(0i32, 0i32, 0.0f32); 8];
            let count = grid_neighbors(grid, pos.x, pos.y, self.allow_diagonal, &mut neighbors_buf);
            for &(nx, ny, _) in &neighbors_buf[..count] {
                if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                    self.update_vertex(grid, n_idx);
                }
            }
        }
    }

    /// Update the start position (when the agent moves).
    ///
    /// Call [`compute_path()`](Self::compute_path) after to update the path.
    pub fn set_start(&mut self, new_start: GridPos) {
        if let Some(new_idx) = index(new_start.x, new_start.y, self.grid_width, self.grid_height) {
            // Increase km by the heuristic distance between old and new start.
            self.km += heuristic(self.start_idx, new_idx, self.grid_width);
            self.start = new_start;
            self.start_idx = new_idx;
        }
    }

    /// Extract the current path from start to goal.
    ///
    /// Returns `None` if no path exists.
    #[must_use]
    pub fn path(&self, grid: &NavGrid) -> Option<Vec<GridPos>> {
        if self.g[self.start_idx] == f32::INFINITY {
            return None;
        }

        let mut path = Vec::new();
        let mut current = self.start_idx;
        let mut visited = vec![false; self.g.len()];
        let max_steps = self.grid_width * self.grid_height;

        for _ in 0..max_steps {
            let cx = (current % self.grid_width) as i32;
            let cy = (current / self.grid_width) as i32;
            path.push(GridPos::new(cx, cy));

            if current == self.goal_idx {
                return Some(path);
            }

            visited[current] = true;

            // Follow the lowest g-cost neighbor.
            let mut best_idx = current;
            let mut best_cost = f32::INFINITY;
            let mut neighbors_buf = [(0i32, 0i32, 0.0f32); 8];
            let count = grid_neighbors(grid, cx, cy, self.allow_diagonal, &mut neighbors_buf);

            for &(nx, ny, move_cost) in &neighbors_buf[..count] {
                if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                    if visited[n_idx] {
                        continue;
                    }
                    let cost = move_cost * grid.cost(nx, ny) + self.g[n_idx];
                    if cost < best_cost {
                        best_cost = cost;
                        best_idx = n_idx;
                    }
                }
            }

            if best_idx == current {
                return None; // Stuck.
            }
            current = best_idx;
        }

        None
    }

    /// Start position.
    #[must_use]
    pub fn start(&self) -> GridPos {
        self.start
    }

    /// Goal position.
    #[must_use]
    pub fn goal(&self) -> GridPos {
        self.goal
    }

    fn update_vertex(&mut self, grid: &NavGrid, idx: usize) {
        let x = (idx % self.grid_width) as i32;
        let y = (idx / self.grid_width) as i32;

        if idx != self.goal_idx {
            // rhs = min over successors s': c(u,s') + g(s').
            let mut neighbors_buf = [(0i32, 0i32, 0.0f32); 8];
            let count = grid_neighbors(grid, x, y, self.allow_diagonal, &mut neighbors_buf);

            if !grid.is_walkable(x, y) {
                self.rhs[idx] = f32::INFINITY;
            } else {
                let mut min_rhs = f32::INFINITY;
                for &(nx, ny, move_cost) in &neighbors_buf[..count] {
                    if let Some(n_idx) = index(nx, ny, self.grid_width, self.grid_height) {
                        let cost = move_cost * grid.cost(nx, ny) + self.g[n_idx];
                        if cost < min_rhs {
                            min_rhs = cost;
                        }
                    }
                }
                self.rhs[idx] = min_rhs;
            }
        }

        // Lazy deletion: stale entries in the heap are skipped via key comparison
        // in compute_path, so we simply push a new entry if g != rhs.
        if (self.g[idx] - self.rhs[idx]).abs() > f32::EPSILON {
            let key = calculate_key(
                idx,
                &self.g,
                &self.rhs,
                self.start_idx,
                self.km,
                self.grid_width,
            );
            self.open.push(DStarNode { idx, key });
        }
    }
}

/// Convert (x, y) to a flat index, returning `None` if out of bounds.
#[inline]
fn index(x: i32, y: i32, w: usize, h: usize) -> Option<usize> {
    if x >= 0 && y >= 0 && (x as usize) < w && (y as usize) < h {
        Some(y as usize * w + x as usize)
    } else {
        None
    }
}

/// Octile heuristic between two flat indices.
#[inline]
fn heuristic(a: usize, b: usize, width: usize) -> f32 {
    let ax = (a % width) as f32;
    let ay = (a / width) as f32;
    let bx = (b % width) as f32;
    let by = (b / width) as f32;
    let dx = (ax - bx).abs();
    let dy = (ay - by).abs();
    let (min, max) = if dx < dy { (dx, dy) } else { (dy, dx) };
    max + (std::f32::consts::SQRT_2 - 1.0) * min
}

/// Compare two keys lexicographically: (k1, k2) < (k1', k2').
#[inline]
fn key_less(a: (f32, f32), b: (f32, f32)) -> bool {
    a.0 < b.0 || (a.0 == b.0 && a.1 < b.1)
}

/// Compute the priority key for a node.
#[inline]
fn calculate_key(
    idx: usize,
    g: &[f32],
    rhs: &[f32],
    start_idx: usize,
    km: f32,
    width: usize,
) -> (f32, f32) {
    let min_g_rhs = g[idx].min(rhs[idx]);
    let h = heuristic(start_idx, idx, width);
    (min_g_rhs + h + km, min_g_rhs)
}

/// Compute walkable neighbors into a stack buffer, returning the count.
#[inline]
fn grid_neighbors(
    grid: &NavGrid,
    x: i32,
    y: i32,
    allow_diagonal: bool,
    buf: &mut [(i32, i32, f32); 8],
) -> usize {
    const CARDINAL: [(i32, i32); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)];
    const DIAGONAL: [(i32, i32); 4] = [(1, 1), (1, -1), (-1, 1), (-1, -1)];

    let mut count = 0;
    for (dx, dy) in CARDINAL {
        let nx = x + dx;
        let ny = y + dy;
        if grid.is_walkable(nx, ny) {
            buf[count] = (nx, ny, 1.0);
            count += 1;
        }
    }
    if allow_diagonal {
        for (dx, dy) in DIAGONAL {
            let nx = x + dx;
            let ny = y + dy;
            if grid.is_walkable(nx, ny)
                && grid.is_walkable(x + dx, y)
                && grid.is_walkable(x, y + dy)
            {
                buf[count] = (nx, ny, std::f32::consts::SQRT_2);
                count += 1;
            }
        }
    }
    count
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dstar_basic_path() {
        let grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        let path = ds.path(&grid);
        assert!(path.is_some());
        let path = path.unwrap();
        assert_eq!(*path.first().unwrap(), GridPos::new(0, 0));
        assert_eq!(*path.last().unwrap(), GridPos::new(9, 9));
    }

    #[test]
    fn dstar_blocked_no_path() {
        let mut grid = NavGrid::new(10, 1, 1.0);
        grid.set_walkable(5, 0, false);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 0)).unwrap();
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_none());
    }

    #[test]
    fn dstar_replan_after_block() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_some());

        // Block a cell and replan.
        grid.set_walkable(5, 5, false);
        ds.update_cell(&grid, GridPos::new(5, 5));
        ds.compute_path(&grid);

        let path = ds.path(&grid);
        assert!(path.is_some());
        // Path should avoid (5,5).
        let path = path.unwrap();
        assert!(!path.contains(&GridPos::new(5, 5)));
    }

    #[test]
    fn dstar_replan_after_unblock() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        // Wall.
        for y in 0..9 {
            grid.set_walkable(5, y, false);
        }
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 0)).unwrap();
        ds.compute_path(&grid);
        let path1 = ds.path(&grid).unwrap();

        // Open a gap.
        grid.set_walkable(5, 0, true);
        ds.update_cell(&grid, GridPos::new(5, 0));
        ds.compute_path(&grid);
        let path2 = ds.path(&grid).unwrap();

        // New path should be shorter (goes through the gap).
        assert!(path2.len() <= path1.len());
    }

    #[test]
    fn dstar_same_start_goal() {
        let grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(5, 5), GridPos::new(5, 5)).unwrap();
        ds.compute_path(&grid);
        let path = ds.path(&grid).unwrap();
        assert_eq!(path.len(), 1);
        assert_eq!(path[0], GridPos::new(5, 5));
    }

    #[test]
    fn dstar_set_start() {
        let grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);

        // Move start.
        ds.set_start(GridPos::new(2, 2));
        ds.compute_path(&grid);
        let path = ds.path(&grid).unwrap();
        assert_eq!(*path.first().unwrap(), GridPos::new(2, 2));
        assert_eq!(*path.last().unwrap(), GridPos::new(9, 9));
    }

    #[test]
    fn dstar_around_obstacle() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        for y in 0..8 {
            grid.set_walkable(5, y, false);
        }
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 0)).unwrap();
        ds.compute_path(&grid);
        let path = ds.path(&grid);
        assert!(path.is_some());
    }

    #[test]
    fn dstar_sequential_updates() {
        let mut grid = NavGrid::new(20, 20, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(19, 19)).unwrap();
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_some());

        // Block cells one at a time, replan each time
        for i in 0..5 {
            grid.set_walkable(10, i * 3, false);
            ds.update_cell(&grid, GridPos::new(10, i * 3));
            ds.compute_path(&grid);
        }
        let path = ds.path(&grid);
        assert!(path.is_some());
        // Path should avoid all blocked cells
        let path = path.unwrap();
        for i in 0..5 {
            assert!(!path.contains(&GridPos::new(10, i * 3)));
        }
    }

    #[test]
    fn dstar_moving_start_along_path() {
        let grid = NavGrid::new(20, 20, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(19, 19)).unwrap();
        ds.compute_path(&grid);

        // Simulate agent moving along the path
        ds.set_start(GridPos::new(5, 5));
        ds.compute_path(&grid);
        let path = ds.path(&grid).unwrap();
        assert_eq!(*path.first().unwrap(), GridPos::new(5, 5));
        assert_eq!(*path.last().unwrap(), GridPos::new(19, 19));
    }

    #[test]
    fn dstar_highly_dynamic() {
        let mut grid = NavGrid::new(20, 20, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(19, 19)).unwrap();
        ds.compute_path(&grid);

        // Block and unblock many cells
        for i in 0..10 {
            grid.set_walkable(i * 2, 10, false);
            ds.update_cell(&grid, GridPos::new(i * 2, 10));
        }
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_some());

        // Unblock them
        for i in 0..10 {
            grid.set_walkable(i * 2, 10, true);
            ds.update_cell(&grid, GridPos::new(i * 2, 10));
        }
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_some());
    }

    #[test]
    fn dstar_cost_change() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        let _path1 = ds.path(&grid).unwrap();

        // Make center cells expensive
        for y in 3..7 {
            for x in 3..7 {
                grid.set_cost(x, y, 100.0);
                ds.update_cell(&grid, GridPos::new(x, y));
            }
        }
        ds.compute_path(&grid);
        let path2 = ds.path(&grid).unwrap();
        // Path should change to avoid expensive area (or at least still be valid)
        assert!(!path2.is_empty());
        assert_eq!(*path2.last().unwrap(), GridPos::new(9, 9));
    }

    #[test]
    fn dstar_large_grid() {
        let grid = NavGrid::new(100, 100, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(99, 99)).unwrap();
        ds.compute_path(&grid);
        let path = ds.path(&grid);
        assert!(path.is_some());
    }

    #[test]
    fn dstar_complete_wall_off() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_some());

        // Wall off completely
        for y in 0..10 {
            grid.set_walkable(5, y, false);
            ds.update_cell(&grid, GridPos::new(5, y));
        }
        ds.compute_path(&grid);
        assert!(ds.path(&grid).is_none());
    }

    #[test]
    fn dstar_unwalkable_start_no_path() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        grid.set_walkable(0, 0, false);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        // Start is unwalkable, so no path should be found
        assert!(ds.path(&grid).is_none());
    }

    #[test]
    fn dstar_unwalkable_goal_no_path() {
        let mut grid = NavGrid::new(10, 10, 1.0);
        grid.set_walkable(9, 9, false);
        let mut ds = DStarLite::new(&grid, GridPos::new(0, 0), GridPos::new(9, 9)).unwrap();
        ds.compute_path(&grid);
        // Goal is unwalkable, so no path should be found
        assert!(ds.path(&grid).is_none());
    }
}