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
use std::{fmt, ops::Range};
use crate::{
coordinate_system::CoordinateSystem,
direction::Direction,
grid::{Grid, GridData, GridIndex, NodeRef},
};
use super::coordinates::{
Cartesian2D, Cartesian3D, CartesianCoordinates, CartesianPosition, GridDelta,
};
#[cfg(feature = "bevy")]
use bevy::ecs::component::Component;
#[cfg(feature = "reflect")]
use bevy::{ecs::reflect::ReflectComponent, reflect::Reflect};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
/// Definition of a grid
#[derive(Clone)]
#[cfg_attr(feature = "bevy", derive(Component, Default))]
#[cfg_attr(feature = "reflect", derive(Reflect), reflect(Component))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CartesianGrid<C: CoordinateSystem> {
size_x: u32,
size_y: u32,
size_z: u32,
looping_x: bool,
looping_y: bool,
looping_z: bool,
pub(crate) coord_system: C,
/// Cache value of `size_x` * `size_y` for index computations
size_xy: u32,
}
impl<C: CartesianCoordinates> Grid<C> for CartesianGrid<C> {
type Position = CartesianPosition;
/// Returns the total size of the grid
#[inline]
fn total_size(&self) -> usize {
(self.size_xy * self.size_z).try_into().unwrap()
}
#[inline]
fn directions_count(&self) -> usize {
self.coord_system.directions().len()
}
#[inline]
fn coord_system(&self) -> &C {
&self.coord_system
}
/// Will retrieve the next index in each direction.
///
/// - `neighbours_buffer` should be allocated by the caller and its size should be >= to `directions.len()`
fn get_neighbours_in_all_directions(
&self,
grid_index: GridIndex,
neighbours_buffer: &mut Vec<Option<GridIndex>>,
) {
let pos = self.pos_from_index(grid_index);
for dir in self.coord_system.directions() {
neighbours_buffer[usize::from(*dir)] = self.get_next_index_in_direction(&pos, *dir);
}
}
/// Returns a [`CartesianPosition`] from the index of an element in this [`CartesianGrid`].
///
/// Panics if the index is not a valid index.
#[inline]
fn pos_from_index(&self, grid_index: GridIndex) -> CartesianPosition {
let index = u32::try_from(grid_index).unwrap();
CartesianPosition {
x: index % self.size_x,
y: (index / self.size_x) % self.size_y,
z: index / self.size_xy,
}
}
/// Returns the index from a grid position.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
#[inline]
fn index_from_pos(&self, grid_position: &CartesianPosition) -> GridIndex {
self.index_from_coords(grid_position.x, grid_position.y, grid_position.z)
}
}
impl<C: CartesianCoordinates> fmt::Display for CartesianGrid<C> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"( size: {} {} {}, looping: {} {} {} )",
self.size_x, self.size_y, self.size_z, self.looping_x, self.looping_y, self.looping_z
)
}
}
impl CartesianGrid<Cartesian2D> {
/// Creates a new grid with a [`Cartesian2D`] coordinate system
///
/// Use `looping` to specify if the coordinates on an axis should loop when reaching the end of the axis.
pub fn new_cartesian_2d(
size_x: u32,
size_y: u32,
looping_x: bool,
looping_y: bool,
) -> CartesianGrid<Cartesian2D> {
Self::new(size_x, size_y, 1, looping_x, looping_y, false, Cartesian2D)
}
/// Returns the index from a grid position, ignoring the Z axis.
///
/// NO CHECK is done to verify that the given position is a valid position for this grid.
#[inline]
pub fn get_index_2d(&self, x: u32, y: u32) -> GridIndex {
(x + y * self.size_x).try_into().unwrap()
}
/// Returns the index from a grid position, ignoring the Z axis.
///
/// NO CHECK is done to verify that the given position is a valid position for this grid.
#[inline]
pub fn get_index_from_pos_2d(&self, grid_position: &CartesianPosition) -> GridIndex {
self.get_index_2d(grid_position.x, grid_position.y)
}
}
impl CartesianGrid<Cartesian3D> {
/// Creates a new grid with a [`Cartesian3D`] coordinate system
///
/// Use `looping` to specify if the coordinates on an axis should loop when reaching the end of the axis.
pub fn new_cartesian_3d(
size_x: u32,
size_y: u32,
size_z: u32,
looping_x: bool,
looping_y: bool,
looping_z: bool,
) -> CartesianGrid<Cartesian3D> {
Self::new(
size_x,
size_y,
size_z,
looping_x,
looping_y,
looping_z,
Cartesian3D,
)
}
}
impl<C: CartesianCoordinates> CartesianGrid<C> {
/// Creates a new [`CartesianGrid`]
pub fn new(
size_x: u32,
size_y: u32,
size_z: u32,
looping_x: bool,
looping_y: bool,
looping_z: bool,
coord_system: C,
) -> CartesianGrid<C> {
Self {
size_x,
size_y,
size_z,
looping_x,
looping_y,
looping_z,
coord_system,
size_xy: size_x * size_y,
}
}
/// Returns the size of the grid in the X axis.
#[inline]
pub fn size_x(&self) -> u32 {
self.size_x
}
/// Returns the size of the grid in the Y axis.
#[inline]
pub fn size_y(&self) -> u32 {
self.size_y
}
/// Returns the size of the grid in the Z axis.
#[inline]
pub fn size_z(&self) -> u32 {
self.size_z
}
/// Returns th value of `size_x` * `size_y
#[inline]
pub fn size_xy(&self) -> u32 {
self.size_xy
}
/// Returns the size of this grid as a tuple
#[inline]
pub fn size(&self) -> (u32, u32, u32) {
(self.size_x, self.size_y, self.size_z)
}
/// Returns a [`Range`] over all indexes in this grid
#[inline]
pub fn indexes(&self) -> Range<GridIndex> {
0..self.total_size()
}
/// Returns all the the [`CoordinateSystem`] used by this [`CartesianGrid`]
#[inline]
pub fn coord_system(&self) -> &C {
&self.coord_system
}
/// Returns the index from a grid position.
///
/// NO CHECK is done to verify that the given position is a valid position for this grid.
#[inline]
pub fn index_from_coords(&self, x: u32, y: u32, z: u32) -> GridIndex {
(x + y * self.size_x + z * self.size_xy).try_into().unwrap()
}
/// Returns the index from a grid position.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
#[inline]
pub fn index_from_pos(&self, grid_position: &CartesianPosition) -> GridIndex {
self.index_from_coords(grid_position.x, grid_position.y, grid_position.z)
}
/// Returns a [`CartesianPosition`] from the index of an element in this [`CartesianPosition`].
///
/// Panics if the index is not a valid index.
#[inline]
pub fn pos_from_index(&self, grid_index: GridIndex) -> CartesianPosition {
let index = u32::try_from(grid_index).unwrap();
CartesianPosition {
x: index % self.size_x,
y: (index / self.size_x) % self.size_y,
z: index / self.size_xy,
}
}
/// Returns the index of the next position in the grid when moving 1 unit in `direction` from `grid_position`.
///
/// Returns `None` if the destination is not in the grid.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
pub fn get_next_index_in_direction(
&self,
grid_position: &CartesianPosition,
direction: Direction,
) -> Option<GridIndex> {
let delta = &self.coord_system.deltas()[direction as usize];
match self.get_next_pos(grid_position, &delta) {
Some(next_pos) => Some(self.index_from_pos(&next_pos)),
None => None,
}
}
/// Returns the index of the next position in the grid when moving `units` in `direction` from `grid_position`.
///
/// Returns `None` if the destination is not in the grid.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
pub fn get_index_in_direction(
&self,
grid_position: &CartesianPosition,
direction: Direction,
units: i32,
) -> Option<GridIndex> {
let delta = self.coord_system.deltas()[direction as usize].clone() * units;
match self.get_next_pos(grid_position, &delta) {
Some(next_pos) => Some(self.index_from_pos(&next_pos)),
None => None,
}
}
/// Returns the the next position in the grid when moving 1 unit in `direction` from `grid_position`.
///
/// Returns `None` if the destination is not in the grid.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
pub fn get_next_pos_in_direction(
&self,
grid_position: &CartesianPosition,
direction: Direction,
) -> Option<CartesianPosition> {
let delta = &self.coord_system.deltas()[direction as usize];
match self.get_next_pos(grid_position, &delta) {
Some(next_pos) => Some(next_pos),
None => None,
}
}
/// Returns the next position in the grid when moving `delta` unit(s) in `direction` from `grid_position`.
///
/// Returns `None` if the destination is not in the grid.
///
/// NO CHECK is done to verify that the given `grid_position` is a valid position for this grid.
pub fn get_next_pos(
&self,
grid_position: &CartesianPosition,
delta: &GridDelta,
) -> Option<CartesianPosition> {
let mut next_pos = grid_position.get_delta_position(&delta);
for (looping, pos, size) in vec![
(self.looping_x, &mut next_pos.0, self.size_x),
(self.looping_y, &mut next_pos.1, self.size_y),
(self.looping_z, &mut next_pos.2, self.size_z),
] {
match looping {
true => {
if *pos < 0 {
*pos += size as i64
}
if *pos >= size as i64 {
*pos -= size as i64
}
}
false => {
if *pos < 0 || *pos >= size as i64 {
return None;
}
}
}
}
Some(CartesianPosition {
x: u32::try_from(next_pos.0).unwrap(),
y: u32::try_from(next_pos.1).unwrap(),
z: u32::try_from(next_pos.2).unwrap(),
})
}
/// Returns an approximate [Direction] when looking towards grid node `to` at grid node `from`.
///
/// When multiple coordinates are different, priority is given to the X coordinate, then to the Y.
pub fn direction(&self, from: GridIndex, to: GridIndex) -> Direction {
let from_pos = self.pos_from_index(from);
let to_pos = self.pos_from_index(to);
if from_pos.x < to_pos.x {
Direction::XForward
} else if from_pos.x > to_pos.x {
Direction::XBackward
} else if from_pos.y < to_pos.y {
Direction::YForward
} else if from_pos.y > to_pos.y {
Direction::YBackward
} else if from_pos.z < to_pos.z {
Direction::ZForward
} else {
Direction::ZBackward
}
}
/// Creates a default [`GridData`] with the size of the [`CartesianGrid`] with each element value set to its default one.
pub fn default_grid_data<D: Default + Clone>(&self) -> GridData<C, D, CartesianGrid<C>> {
GridData::new(self.clone(), vec![D::default(); self.total_size()])
}
/// Creates a [`GridData`] with the size of the [`CartesianGrid`] with each element value being a copy of the given one.
pub fn new_grid_data<D: Clone>(&self, element: D) -> GridData<C, D, CartesianGrid<C>> {
GridData::new(self.clone(), vec![element; self.total_size()])
}
}
impl<C: CartesianCoordinates> NodeRef<C, CartesianGrid<C>> for CartesianPosition {
#[inline]
fn to_index(&self, grid: &CartesianGrid<C>) -> GridIndex {
grid.index_from_pos(self)
}
}
impl<C: CartesianCoordinates> NodeRef<C, CartesianGrid<C>> for (u32, u32) {
#[inline]
fn to_index(&self, grid: &CartesianGrid<C>) -> GridIndex {
grid.index_from_coords(self.0, self.1, 0)
}
}
impl<C: CartesianCoordinates> NodeRef<C, CartesianGrid<C>> for (u32, u32, u32) {
#[inline]
fn to_index(&self, grid: &CartesianGrid<C>) -> GridIndex {
grid.index_from_coords(self.0, self.1, self.2)
}
}