aboutsummaryrefslogtreecommitdiff
path: root/server/bot/src/pathfinding.rs
blob: 936f99dd4ac78601d592d595322ac461dee834b1 (plain)
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
/*
    Hurry Curry! - a game about cooking
    Copyright (C) 2025 Hurry Curry! Contributors

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, version 3 of the License only.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

*/
use hurrycurry_game_core::Game;
use hurrycurry_protocol::glam::{IVec2, Vec2};
#[cfg(feature = "debug_events")]
use hurrycurry_protocol::{DebugEvent, DebugEventDisplay, PlayerID};
use log::{debug, trace};
use std::{
    cmp::Ordering,
    collections::{BinaryHeap, HashMap},
    time::Instant,
};

#[derive(Debug, Clone)]
pub struct Path {
    segments: Vec<Vec2>,
    seg_time: f32,
}

impl Path {
    pub const EMPTY: Path = Path {
        seg_time: 0.,
        segments: Vec::new(),
    };
    pub fn next_direction(&mut self, position: Vec2, dt: f32) -> Vec2 {
        if let Some(next) = self.segments.last().copied() {
            trace!("next {next}");
            self.seg_time += dt;
            if next.distance(position) < if self.segments.len() == 1 { 0.1 } else { 0.6 } {
                self.seg_time = 0.;
                self.segments.pop();
            }
            (next - position).normalize_or_zero()
        } else {
            Vec2::ZERO
        }
    }
    pub fn is_done(&self) -> bool {
        self.segments.is_empty()
    }
    pub fn is_stuck(&self, thres: f32) -> bool {
        self.seg_time > thres
    }
    pub fn remaining_segments(&self) -> usize {
        self.segments.len()
    }

    #[cfg(feature = "debug_events")]
    pub fn debug(&self, id: PlayerID) -> DebugEvent {
        use crate::debug_player_color;
        DebugEvent {
            key: format!("path-{id}"),
            color: debug_player_color(id),
            display: DebugEventDisplay::Path {
                points: self.segments.clone(),
            },
        }
    }
}

pub fn find_path_to_neighbour(game: &Game, from: IVec2, to: IVec2) -> Option<Path> {
    let mut paths = Vec::new();
    for xo in -1..=1 {
        for yo in -1..=1 {
            let to = to + IVec2::new(xo, yo);
            if game.walkable.contains(&to) {
                paths.extend(find_path(game, from, to))
            }
        }
    }
    paths.into_iter().min_by_key(|p| p.segments.len())
}
pub fn find_path(game: &Game, from: IVec2, to: IVec2) -> Option<Path> {
    #[derive(Debug, PartialEq, Eq)]
    struct Open {
        heuristic: i32,
        pos: IVec2,
        prev_pos: IVec2,
        distance: i32,
    }
    impl PartialOrd for Open {
        fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
            Some(self.cmp(other))
        }
    }
    impl Ord for Open {
        fn cmp(&self, other: &Self) -> Ordering {
            self.heuristic.cmp(&other.heuristic)
        }
    }

    debug!("planning route from {from} to {to}");
    let start = Instant::now();
    let chair = game.data.get_tile_by_name("chair");
    let mut visited = HashMap::new();
    let mut open = BinaryHeap::new();
    open.push(Open {
        heuristic: 1,
        pos: from,
        prev_pos: from,
        distance: 0,
    });

    loop {
        let Open {
            pos,
            prev_pos,
            distance,
            ..
        } = open.pop()?;
        if visited.contains_key(&pos) {
            continue;
        }
        visited.insert(pos, prev_pos);
        if pos == to {
            break;
        }
        for dir in [IVec2::NEG_X, IVec2::NEG_Y, IVec2::X, IVec2::Y] {
            let next = pos + dir;
            if game.walkable.contains(&next) {
                let penalty = if let Some(chair) = chair
                    && let Some(set) = game.tile_index.get(&chair)
                    && set.contains(&next)
                {
                    8
                } else {
                    0
                };
                open.push(Open {
                    heuristic: -(distance + next.distance_squared(to).isqrt()),
                    pos: next,
                    prev_pos: pos,
                    distance: distance + penalty + 1,
                });
            }
        }
    }

    let mut segments = Vec::new();
    let mut c = to;
    loop {
        segments.push(c.as_vec2() + 0.5);
        let cn = visited[&c];
        if cn == c {
            break;
        }
        c = cn
    }

    debug!(
        "done in {:?} (distance={})",
        start.elapsed(),
        segments.len()
    );
    Some(Path {
        segments,
        seg_time: 0.,
    })
}