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
//! Graph module for managing nodes and edges in relative space.
use bevy::{log, math::UVec3, platform::collections::HashMap};
use crate::{chunk::Chunk, dir::Dir, node::Node, path::Path, NodeId};
/// A graph structure that holds nodes and their connections (edges).
pub(crate) struct Graph {
/// `Node` storage.
nodes: slab::Slab<Node>,
/// A mapping from node `UVec3` positions to their IDs in the slab.
node_ids: HashMap<UVec3, NodeId>,
}
impl Graph {
pub(crate) fn new() -> Self {
Graph {
nodes: slab::Slab::new(),
node_ids: HashMap::new(),
}
}
/// Returns the `Node` at the given position, if it exists.
pub(crate) fn node_at(&self, pos: UVec3) -> Option<&Node> {
self.node_ids.get(&pos).and_then(|&id| self.nodes.get(id))
}
/// Returns all `Node`s in the `Graph`.
pub(crate) fn nodes(&self) -> Vec<&Node> {
self.nodes.iter().map(|(_, node)| node).collect()
}
/// Returns all `Node`s that exist in the given `Chunk`.
pub(crate) fn nodes_in_chunk(&self, chunk: &Chunk) -> Vec<&Node> {
let nodes = self
.nodes
.iter()
.filter(|(_, node)| node.chunk_index == chunk.index())
.map(|(_, node)| node)
.collect();
nodes
}
/// Add a new `Node` to the graph at the given position with the specified `Chunk`
/// and optional direction.
pub(crate) fn add_node(&mut self, node: Node) -> NodeId {
if let Some(old_id) = self.node_ids.insert(node.pos, usize::MAX) {
self.nodes.remove(old_id);
}
let id = self.nodes.insert(node.clone());
self.node_ids.insert(node.pos, id);
id
}
/// Add a list of `Node`s to the graph.
/// This will insert the nodes into the graph and update the `node_ids` mapping.
/// If a node with the same position already exists, it will be replaced.
/// This is useful for bulk adding nodes to the graph.
/// The `nodes` parameter is a vector of `Node`s to be added.
pub(crate) fn add_nodes(&mut self, nodes: &Vec<Node>) {
for node in nodes {
if let Some(old_id) = self.node_ids.insert(node.pos, usize::MAX) {
self.nodes.remove(old_id);
}
let id = self.nodes.insert(node.clone());
self.node_ids.insert(node.pos, id);
}
}
/// Remove a `Node` from the graph at the given position.
#[allow(dead_code)]
pub(crate) fn remove_node(&mut self, pos: UVec3) {
if let Some(id) = self.node_ids.remove(&pos) {
self.nodes.remove(id);
}
}
// Removes the edges for a given node
#[allow(dead_code)]
pub(crate) fn remove_edges_to(&mut self, positions: &[UVec3]) {
for node in self.nodes.iter_mut() {
node.1.remove_edges_to_positions(positions);
}
}
/// Remove all nodes for edge directions in the Chunk.
/// This is used to clean up nodes that are no longer needed
/// when edges are rebuilt.
pub(crate) fn remove_nodes_for_edges(&mut self, chunk: &Chunk, dirs: &[Dir]) {
// Collect all nodes for all specified edges
let edge_nodes: Vec<(UVec3, NodeId)> = self
.nodes_in_chunk(chunk)
.iter()
.filter(|node| node.dir.is_some() && dirs.contains(&node.dir.unwrap()))
.filter_map(|node| self.node_ids.get(&node.pos).map(|&id| (node.pos, id)))
.collect();
// Remove nodes from slab and mapping
for (pos, id) in &edge_nodes {
if self.nodes.contains(*id) {
self.nodes.remove(*id);
self.node_ids.remove(pos);
} else {
log::warn!(
"Tried to remove node {:?} with id {:?} from Chunk {:?}, but it was already gone",
pos, id, chunk
);
}
}
// Remove edges from all nodes pointing to removed positions
let removed_positions: Vec<UVec3> = edge_nodes.iter().map(|(pos, _)| *pos).collect();
for node in self.nodes.iter_mut() {
node.1.remove_edges_to_positions(&removed_positions);
}
}
/*pub(crate) fn remove_nodes_at_edge(&mut self, chunk: &Chunk, dir: Dir) {
// Collect all nodes in the edge and their IDs
let edge_nodes: Vec<(UVec3, NodeId)> = self
.nodes_in_chunk(chunk)
.iter()
.filter(|node| node.dir == Some(dir))
.filter_map(|node| self.node_ids.get(&node.pos).map(|&id| (node.pos, id)))
.collect();
// Remove all nodes from the slab and node_ids mapping
for (pos, id) in &edge_nodes {
if self.nodes.contains(*id) {
self.nodes.remove(*id);
self.node_ids.remove(pos);
} else {
log::warn!("Tried to remove node {:?} with id {:?} from Chunk {:?}, but it was already gone", pos, id, chunk);
}
}
// Remove any edges in other nodes that point to the removed positions
let positions: Vec<UVec3> = edge_nodes.iter().map(|(pos, _)| *pos).collect();
for node in self.nodes.iter_mut() {
node.1.remove_edges_to_positions(&positions);
}
}*/
pub(crate) fn remove_edges_for_chunk(&mut self, chunk: &Chunk) {
// Get all the ndoes in the chunk
let nodes_in_chunk = self.nodes_in_chunk(chunk);
// Collect all positions in the chunk
let positions: Vec<UVec3> = nodes_in_chunk.iter().map(|node| node.pos).collect();
// Now iterate over all nodes in the chunk and remove edges to those positions
for node in self.nodes.iter_mut() {
node.1.remove_edges_to_positions(&positions);
}
}
/// Connect two nodes in the graph with a provided `Path`.
/// The path will be used as a cached path between the two nodes.
pub(crate) fn connect_node(&mut self, from: UVec3, to: UVec3, path: Path) {
if let Some(&from_id) = self.node_ids.get(&from) {
self.nodes.get_mut(from_id).unwrap().edges.insert(to, path);
}
}
/// Returns the cost of the edge between two node positions.
pub(crate) fn edge_cost(&self, from: UVec3, to: UVec3) -> Option<u32> {
self.node_ids
.get(&from)
.and_then(|&from_id| self.nodes.get(from_id))
.and_then(|node| node.edges.get(&to).map(|path| path.cost()))
}
/// Returns the cached edge path
pub(crate) fn edge_path(&self, from: UVec3, to: UVec3) -> Option<&Path> {
self.node_ids
.get(&from)
.and_then(|&from_id| self.nodes.get(from_id))
.and_then(|node| node.edges.get(&to))
}
/// Returns all cached `Path`s in the graph.
pub(crate) fn all_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
for node in self.nodes.iter().map(|(_, node)| node) {
for path in node.edges.values() {
paths.push(path.clone());
}
}
paths
}
#[allow(dead_code)]
pub(crate) fn validate_slab(&self) {
for (pos, id) in &self.node_ids {
if !self.nodes.contains(*id) {
log::error!(
"validate: node_ids maps pos {:?} to id {:?}, but slab has no entry!",
pos,
id
);
} else {
let node = &self.nodes[*id];
if node.pos != *pos {
log::error!(
"validate: node_ids maps pos {:?} to id {:?}, but slab node has pos {:?}!",
pos,
id,
node.pos
);
}
}
}
for (id, node) in self.nodes.iter() {
if let Some(mapped_id) = self.node_ids.get(&node.pos) {
if *mapped_id != id {
log::error!(
"validate: slab node at id {:?} has pos {:?}, but node_ids maps to different id {:?}",
id,
node.pos,
mapped_id
);
}
} else {
log::error!(
"validate: slab has node at pos {:?}, but node_ids has no entry",
node.pos
);
}
}
}
/// Returns the number of nodes in the graph.
#[allow(dead_code)]
pub(crate) fn node_count(&self) -> usize {
self.nodes.len()
}
/// Returns the number of edges in the graph.
#[allow(dead_code)]
pub(crate) fn edge_count(&self) -> usize {
self.nodes.iter().map(|(_, node)| node.edges.len()).sum()
}
/// Ensure that there are no `Node`s with duplicate positions in the graph.
#[allow(dead_code)]
pub(crate) fn clear_duplicates(&mut self) {
let mut to_remove = Vec::new();
for (id, node) in self.nodes.iter() {
if let Some(&other_id) = self.node_ids.get(&node.pos) {
if id != other_id {
to_remove.push(id);
}
}
}
for id in to_remove {
self.nodes.remove(id);
}
}
/// Returns the closest `Node` to the given position in the specified `Chunk`.
#[allow(dead_code)]
pub(crate) fn closest_node_in_chunk(&self, pos: UVec3, chunk: &Chunk) -> Option<&Node> {
let node = self
.nodes_in_chunk(chunk)
.iter()
.min_by_key(|node| {
let dx = (node.pos.x as i32 - pos.x as i32).abs();
let dy = (node.pos.y as i32 - pos.y as i32).abs();
let dz = (node.pos.z as i32 - pos.z as i32).abs();
(dx + dy + dz) as u32
})
.cloned();
node
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_add_node() {
let mut graph = Graph::new();
let pos = UVec3::new(0, 0, 0);
let chunk = Chunk::new((0, 0, 0), UVec3::new(0, 0, 0), UVec3::new(16, 16, 16));
let id = graph.add_node(Node::new(pos, chunk.clone(), None));
let node = graph.node_at(pos).unwrap();
assert_eq!(node.pos, pos);
assert_eq!(node.chunk_index, chunk.index());
assert_eq!(node.dir, None);
assert_eq!(id, 0);
}
#[test]
fn test_all_nodes_in_chunk() {
let mut graph = Graph::new();
let pos1 = UVec3::new(0, 0, 0);
let pos2 = UVec3::new(1, 1, 1);
let chunk = Chunk::new((0, 0, 0), UVec3::new(0, 0, 0), UVec3::new(16, 16, 16));
graph.add_node(Node::new(pos1, chunk.clone(), None));
graph.add_node(Node::new(pos2, chunk.clone(), None));
let nodes = graph.nodes_in_chunk(&chunk);
assert_eq!(nodes.len(), 2);
assert_eq!(nodes[0].pos, pos1);
assert_eq!(nodes[1].pos, pos2);
}
#[test]
fn test_closest_node_in_chunk() {
let mut graph = Graph::new();
let pos1 = UVec3::new(0, 0, 0);
let pos2 = UVec3::new(1, 1, 1);
let chunk = Chunk::new((0, 0, 0), UVec3::new(0, 0, 0), UVec3::new(16, 16, 16));
graph.add_node(Node::new(pos1, chunk.clone(), None));
graph.add_node(Node::new(pos2, chunk.clone(), None));
let pos = UVec3::new(0, 1, 0);
let node = graph.closest_node_in_chunk(pos, &chunk).unwrap();
assert_eq!(node.pos, pos1);
}
}