aboutsummaryrefslogtreecommitdiff
path: root/server/client-lib/src/spatial_index.rs
blob: 3f0d5ad03417739e0d5e913517de91e8de2fd36c (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
/*
    Hurry Curry! - a game about cooking
    Copyright 2024 metamuffin

    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_protocol::glam::{IVec2, Vec2};
use std::{collections::HashMap, hash::Hash};

// TODO stub implementation. please implement
pub struct SpatialIndex<T> {
    entries: HashMap<T, Vec2>,
    bins: HashMap<IVec2, Vec<T>>,
}

impl<T: Eq + Hash + Copy> SpatialIndex<T> {
    pub fn update_entry(&mut self, id: T, position: Vec2) {
        self.entries.insert(id, position);
        let e = self.bins.entry(position.as_ivec2()).or_default();
        if !e.contains(&id) {
            e.push(id);
        }
    }
    pub fn remove_entry(&mut self, id: T) {
        if let Some(pos) = self.entries.remove(&id) {
            self.bins
                .entry(pos.as_ivec2())
                .or_default()
                .retain(|e| *e != id);
        }
    }
    pub fn all(&self, mut cb: impl FnMut(T, Vec2)) {
        for (&e, &pos) in &self.entries {
            cb(e, pos)
        }
    }
    pub fn query(&self, position: Vec2, radius: f32, mut cb: impl FnMut(T, Vec2)) {
        // TODO query bins
        self.all(|pl, p| {
            if p.distance(position) < radius {
                cb(pl, p)
            }
        })
    }
}
impl<T> Default for SpatialIndex<T> {
    fn default() -> Self {
        Self {
            entries: Default::default(),
            bins: Default::default(),
        }
    }
}