Skip to main content

flatland_pathfinding/
grid.rs

1//! Navigation world snapshot for pathfinding.
2
3use flatland_protocol::{
4    BuildingView, DoorView, LifeState, ResourceNodeState, TerrainKindView, TerrainZoneView,
5    ZPlatformView, ZTransitionView,
6};
7
8use crate::mode::PathMode;
9
10pub const PLAYER_RADIUS_M: f32 = 0.45;
11/// Extra clearance so paths don't hug walls.
12pub const PATH_CLEARANCE_M: f32 = 0.35;
13/// Sample spacing when testing straight segments against circle obstacles.
14pub const SEGMENT_SAMPLE_M: f32 = 0.3;
15/// Grass baseline A* cost (and Direct walkable cost). Fastest uses `BASE / speed`.
16pub const DEFAULT_COST: u16 = 10;
17
18#[derive(Debug, Clone, Copy)]
19pub struct NavBlockingCircle {
20    pub x: f32,
21    pub y: f32,
22    pub radius_m: f32,
23}
24
25/// Per-kind move speed + impassable flag from content (`terrain-kinds.yaml`).
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct TerrainKindNavParams {
28    pub move_speed_mult: f32,
29    pub impassable: bool,
30}
31
32impl Default for TerrainKindNavParams {
33    fn default() -> Self {
34        Self {
35            move_speed_mult: 1.0,
36            impassable: false,
37        }
38    }
39}
40
41/// Lookup table for path costs — populated from the terrain kind catalog (no hardcoded speeds).
42#[derive(Debug, Clone, Default)]
43pub struct TerrainNavTable {
44    params: Vec<(TerrainKindView, TerrainKindNavParams)>,
45}
46
47impl TerrainNavTable {
48    pub fn set(&mut self, kind: TerrainKindView, params: TerrainKindNavParams) {
49        if let Some(slot) = self.params.iter_mut().find(|(k, _)| *k == kind) {
50            slot.1 = params;
51        } else {
52            self.params.push((kind, params));
53        }
54    }
55
56    pub fn get(&self, kind: TerrainKindView) -> TerrainKindNavParams {
57        self.params
58            .iter()
59            .find(|(k, _)| *k == kind)
60            .map(|(_, p)| *p)
61            .unwrap_or_default()
62    }
63
64    pub fn iter(&self) -> impl Iterator<Item = (TerrainKindView, TerrainKindNavParams)> + '_ {
65        self.params.iter().copied()
66    }
67
68    /// Test / fixture helper: former baked-in speeds so unit tests stay self-contained.
69    pub fn unit_test_defaults() -> Self {
70        let mut t = Self::default();
71        let rows: &[(TerrainKindView, f32, bool)] = &[
72            (TerrainKindView::Grass, 1.0, false),
73            (TerrainKindView::Dirt, 0.98, false),
74            (TerrainKindView::Tilled, 0.95, false),
75            (TerrainKindView::Desert, 0.9, false),
76            (TerrainKindView::Hill, 0.92, false),
77            (TerrainKindView::Trail, 1.10, false),
78            (TerrainKindView::Road, 1.50, false),
79            (TerrainKindView::Rock, 0.85, true),
80            (TerrainKindView::Bog, 0.65, false),
81            (TerrainKindView::Beach, 0.94, false),
82            (TerrainKindView::ShallowWater, 0.55, false),
83            (TerrainKindView::DeepWater, 0.4, true),
84        ];
85        for &(kind, speed, impassable) in rows {
86            t.set(
87                kind,
88                TerrainKindNavParams {
89                    move_speed_mult: speed,
90                    impassable,
91                },
92            );
93        }
94        t
95    }
96}
97
98/// Map catalog id (`road`, `shallow_water`, …) to protocol view.
99pub fn terrain_kind_view_from_id(id: &str) -> Option<TerrainKindView> {
100    Some(match id {
101        "grass" => TerrainKindView::Grass,
102        "dirt" => TerrainKindView::Dirt,
103        "tilled" => TerrainKindView::Tilled,
104        "desert" => TerrainKindView::Desert,
105        "hill" => TerrainKindView::Hill,
106        "bog" => TerrainKindView::Bog,
107        "beach" => TerrainKindView::Beach,
108        "shallow_water" => TerrainKindView::ShallowWater,
109        "deep_water" => TerrainKindView::DeepWater,
110        "trail" => TerrainKindView::Trail,
111        "road" => TerrainKindView::Road,
112        "rock" => TerrainKindView::Rock,
113        _ => return None,
114    })
115}
116
117/// Static + dynamic obstacles for one path query.
118#[derive(Debug, Clone)]
119pub struct NavWorld {
120    pub world_width_m: f32,
121    pub world_height_m: f32,
122    pub terrain_zones: Vec<TerrainZoneView>,
123    pub z_platforms: Vec<ZPlatformView>,
124    pub z_transitions: Vec<ZTransitionView>,
125    pub buildings: Vec<BuildingView>,
126    pub doors: Vec<DoorView>,
127    pub circles: Vec<NavBlockingCircle>,
128    /// Kind → speed / impassable from content catalog.
129    pub kind_nav: TerrainNavTable,
130}
131
132impl NavWorld {
133    pub fn elevation_at(&self, x: f32, y: f32) -> f32 {
134        terrain_at(&self.terrain_zones, x, y)
135            .map(|z| z.elevation)
136            .unwrap_or(0.0)
137    }
138
139    pub fn terrain_kind_at(&self, x: f32, y: f32) -> TerrainKindView {
140        terrain_at(&self.terrain_zones, x, y)
141            .map(|z| z.kind)
142            .unwrap_or(TerrainKindView::Grass)
143    }
144}
145
146fn terrain_at(zones: &[TerrainZoneView], x: f32, y: f32) -> Option<&TerrainZoneView> {
147    // Match sim `WorldSegment::terrain_zone_at`: highest z_order wins; tie → later list index.
148    zones
149        .iter()
150        .enumerate()
151        .filter(|(_, zone)| x >= zone.x0 && x < zone.x1 && y >= zone.y0 && y < zone.y1)
152        .max_by(|(ia, a), (ib, b)| a.z_order.cmp(&b.z_order).then(ia.cmp(ib)))
153        .map(|(_, z)| z)
154}
155
156pub fn terrain_move_speed_mult(kind: TerrainKindView, table: &TerrainNavTable) -> f32 {
157    table.get(kind).move_speed_mult.max(0.01)
158}
159
160pub fn terrain_is_impassable(kind: TerrainKindView, table: &TerrainNavTable) -> bool {
161    table.get(kind).impassable
162}
163
164/// A* cell cost for `mode`. Impassable → `u16::MAX` (blocked).
165pub fn terrain_cost(kind: TerrainKindView, mode: PathMode, table: &TerrainNavTable) -> u16 {
166    if terrain_is_impassable(kind, table) {
167        return u16::MAX;
168    }
169    match mode {
170        PathMode::Direct => DEFAULT_COST,
171        PathMode::Fastest => {
172            let speed = terrain_move_speed_mult(kind, table);
173            let c = (DEFAULT_COST as f32 / speed).round();
174            c.clamp(1.0, (u16::MAX - 1) as f32) as u16
175        }
176    }
177}
178
179/// Minimum walkable cost for `mode` given zones present (admissible A* scale).
180pub fn min_walkable_cost(
181    mode: PathMode,
182    zones: &[TerrainZoneView],
183    table: &TerrainNavTable,
184) -> u16 {
185    match mode {
186        PathMode::Direct => DEFAULT_COST,
187        PathMode::Fastest => {
188            let mut min_c = DEFAULT_COST;
189            for z in zones {
190                let c = terrain_cost(z.kind, PathMode::Fastest, table);
191                if c != u16::MAX && c < min_c {
192                    min_c = c;
193                }
194            }
195            min_c
196        }
197    }
198}
199
200pub fn collides_player_at(x: f32, y: f32, world: &NavWorld) -> bool {
201    if world.circles.iter().any(|o| {
202        circle_overlap(x, y, PLAYER_RADIUS_M, o.x, o.y, o.radius_m)
203    }) {
204        return true;
205    }
206    let pad = PLAYER_RADIUS_M;
207    world.buildings.iter().any(|b| {
208        let hw = b.width_m / 2.0 + pad;
209        let hd = b.depth_m / 2.0 + pad;
210        x >= b.x - hw && x <= b.x + hw && y >= b.y - hd && y <= b.y + hd
211    })
212}
213
214fn circle_overlap(ax: f32, ay: f32, ar: f32, bx: f32, by: f32, br: f32) -> bool {
215    let dx = ax - bx;
216    let dy = ay - by;
217    let min_dist = ar + br;
218    dx * dx + dy * dy < min_dist * min_dist
219}
220
221pub(crate) fn block_circle(blocked: &mut [bool], width: i16, height: i16, cx: f32, cy: f32, radius_m: f32) {
222    let block_r = radius_m + PLAYER_RADIUS_M + PATH_CLEARANCE_M;
223    let r = block_r.ceil() as i16;
224    let ix = cx.floor() as i16;
225    let iy = cy.floor() as i16;
226    for dy in -r..=r {
227        for dx in -r..=r {
228            let cell_x = ix + dx;
229            let cell_y = iy + dy;
230            if cell_x < 0 || cell_y < 0 || cell_x >= width || cell_y >= height {
231                continue;
232            }
233            let cell_cx = cell_x as f32 + 0.5;
234            let cell_cy = cell_y as f32 + 0.5;
235            if (cell_cx - cx).hypot(cell_cy - cy) <= block_r {
236                let idx = (cell_y as usize) * (width as usize) + (cell_x as usize);
237                blocked[idx] = true;
238            }
239        }
240    }
241}
242
243pub(crate) fn mark_building_footprint(blocked: &mut [bool], width: i16, height: i16, building: &BuildingView) {
244    // Match `collides_player_at`: player radius only. Extra PATH_CLEARANCE here used to
245    // seal road cells beside buildings (e.g. West Storage eating the y=106 road) while
246    // the player could still walk that pavement — A* then detoured through grass.
247    let pad = PLAYER_RADIUS_M;
248    let hw = building.width_m / 2.0;
249    let hd = building.depth_m / 2.0;
250    let x0 = (building.x - hw - pad).floor() as i16;
251    let y0 = (building.y - hd - pad).floor() as i16;
252    let x1 = (building.x + hw + pad).ceil() as i16 - 1;
253    let y1 = (building.y + hd + pad).ceil() as i16 - 1;
254    if x1 < x0 || y1 < y0 {
255        return;
256    }
257    for x in x0..=x1 {
258        for y in y0..=y1 {
259            if x >= 0 && y >= 0 && x < width && y < height {
260                let idx = (y as usize) * (width as usize) + (x as usize);
261                blocked[idx] = true;
262            }
263        }
264    }
265}
266
267pub(crate) fn clear_door_cells(blocked: &mut [bool], width: i16, height: i16, doors: &[DoorView]) {
268    for door in doors {
269        if door.open {
270            let (x, y) = world_to_cell(door.x, door.y);
271            for dx in -1i16..=1 {
272                for dy in -1i16..=1 {
273                    if dx.abs() + dy.abs() <= 1 {
274                        let cx = x + dx;
275                        let cy = y + dy;
276                        if cx >= 0 && cy >= 0 && cx < width && cy < height {
277                            let idx = (cy as usize) * (width as usize) + (cx as usize);
278                            blocked[idx] = false;
279                        }
280                    }
281                }
282            }
283        }
284    }
285}
286
287pub(crate) fn world_to_cell(x: f32, y: f32) -> (i16, i16) {
288    (x.floor() as i16, y.floor() as i16)
289}
290
291pub(crate) fn cell_center(x: i16, y: i16) -> (f32, f32) {
292    (x as f32 + 0.5, y as f32 + 0.5)
293}
294
295/// Default nav radius when a placed prop has `blocking: true` but radius 0 in data.
296pub const DEFAULT_PLACED_PROP_BLOCK_RADIUS_M: f32 = 0.7;
297
298/// Blocking circles for placed props that have `blocking` on the item template (AOI view).
299pub fn circles_from_placed_containers(
300    containers: &[flatland_protocol::PlacedContainerView],
301) -> Vec<NavBlockingCircle> {
302    containers
303        .iter()
304        .filter(|c| c.blocking)
305        .map(|c| {
306            let radius_m = if c.blocking_radius_m > 0.0 {
307                c.blocking_radius_m
308            } else {
309                DEFAULT_PLACED_PROP_BLOCK_RADIUS_M
310            };
311            NavBlockingCircle {
312                x: c.x,
313                y: c.y,
314                radius_m,
315            }
316        })
317        .collect()
318}
319
320/// Outdoor travel goal snapped clear of buildings, trees, NPCs, and placed props.
321pub fn snap_nav_goal(world: &NavWorld, gx: f32, gy: f32) -> (f32, f32) {
322    if !nav_position_blocked(world, gx, gy, PATH_CLEARANCE_M) {
323        return (gx, gy);
324    }
325    for step in 1..=40 {
326        let d = step as f32 * 0.35;
327        for (dx, dy) in [
328            (0.0, -d),
329            (0.0, d),
330            (d, 0.0),
331            (-d, 0.0),
332            (d, -d),
333            (d, d),
334            (-d, -d),
335            (-d, d),
336        ] {
337            let nx = gx + dx;
338            let ny = gy + dy;
339            if !nav_position_blocked(world, nx, ny, PATH_CLEARANCE_M) {
340                return (nx, ny);
341            }
342        }
343    }
344    (gx, gy)
345}
346
347fn nav_position_blocked(world: &NavWorld, x: f32, y: f32, extra_pad_m: f32) -> bool {
348    let body = PLAYER_RADIUS_M + extra_pad_m.max(0.0);
349    if world.circles.iter().any(|o| {
350        circle_overlap(x, y, body, o.x, o.y, o.radius_m + extra_pad_m.max(0.0))
351    }) {
352        return true;
353    }
354    world.buildings.iter().any(|b| {
355        let hw = b.width_m / 2.0 + body;
356        let hd = b.depth_m / 2.0 + body;
357        x >= b.x - hw && x <= b.x + hw && y >= b.y - hd && y <= b.y + hd
358    })
359}
360
361/// Build blocking circles from protocol views (resource nodes + living NPCs).
362pub fn circles_from_views(
363    resource_nodes: &[flatland_protocol::ResourceNodeView],
364    npcs: &[flatland_protocol::NpcView],
365) -> Vec<NavBlockingCircle> {
366    let mut circles = Vec::new();
367    for node in resource_nodes {
368        if node.blocking
369            && matches!(
370                node.state,
371                ResourceNodeState::Available | ResourceNodeState::Harvesting
372            )
373        {
374            let radius = if node.blocking_radius_m > 0.0 {
375                node.blocking_radius_m
376            } else {
377                0.8
378            };
379            circles.push(NavBlockingCircle {
380                x: node.x,
381                y: node.y,
382                radius_m: radius,
383            });
384        }
385    }
386    for npc in npcs {
387        let alive =
388            npc.life_state != Some(LifeState::Dead) && npc.hp_pct.is_none_or(|h| h > 0.0);
389        if alive {
390            circles.push(NavBlockingCircle {
391                x: npc.x,
392                y: npc.y,
393                radius_m: 0.55,
394            });
395        }
396    }
397    circles
398}