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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! A utility for translating between grid points and world space.
//!
//! You can specify a world position, size, and pivot for the grid when creating it.
//! These will affect the grid's bounds and tile points.
//!
//! **Example Grids**
//!
//! A 3x3 Pivot::Center grid:
//! ```text
//! |-1,-1| 0, 1| 1, 1|
//! |-1, 0| 0, 0| 1, 0|
//! |-1,-1| 0,-1| 1,-1|
//! ```
//!
//! A 3x3 Pivot::BottomLeft grid:
//! ```text
//! | 0, 2| 1, 2| 2, 2|
//! | 0, 1| 1, 1| 2, 1|
//! | 0, 0| 1, 0| 2, 0|
//! ```
//!
//! A 3x3 Pivot::TopRight grid:
//!
//! ```text
//! |-3,-1|-2,-1|-1,-1|
//! |-3,-2|-2,-2|-1,-2|
//! |-3,-3|-2,-3|-1,-3|
//! ```
//!
//! # Types of Points
//!
//! The api has several different "types" of positions that can be
//! referenced:
//! - **World Position**: The world offset of the grid.
//! - **Grid Position**: The local position of the grid's tiles relative to it's pivot.
//! - **Index**: The 1d index of a tile. (`0`..`width * height`)
//! - **2d Index**: The 2d index of a tile in the grid. `([0,0]`..`[width,height])`.
//! - **Tile Position**: The bottom-left point of a tile in the grid.
//! - **Tile Center**: The center of a tile in the grid.

use itertools::Itertools;

use glam::{IVec2, Vec2};

use crate::point::{Pivot, Point2d, Size2d};

/// A sized grid with a custom pivot for translating between aligned grid points
/// and world space.
#[derive(Default, Debug, Clone)]
pub struct WorldGrid {
    pub world_pos: Vec2,
    size: IVec2,
    /// Used when retrieving a tile center - accounts for centered/odd size grids.
    center_offset: Vec2,
    /// Used when retrieving a tile position - accounts for centered/odd sized grids.
    pos_offset: Vec2,
    /// Used when translating from a grid position to an index position.
    pivot_offset: Vec2,
    /// Axis, derived from pivot
    axis: Vec2,
}

impl WorldGrid {
    pub fn new(world_pos: impl Point2d, size: impl Size2d, pivot: Pivot) -> Self {
        let world_pos = world_pos.as_ivec2();
        let size = size.as_ivec2();

        let center_offset = match pivot {
            Pivot::Center => Vec2::select(
                (size % 2).cmpeq(IVec2::ZERO),
                Vec2::new(0.5, 0.5),
                Vec2::ZERO,
            ),
            _ => Vec2::new(0.5, 0.5),
        };

        let pos_offset = center_offset - Vec2::new(0.5, 0.5);

        let axis = pivot.axis().as_vec2();

        let pivot_offset = match pivot {
            Pivot::Center => -size.as_vec2() * Vec2::new(0.5, 0.5),
            _ => Vec2::ZERO,
        };

        WorldGrid {
            world_pos: world_pos.as_vec2(),
            size,
            center_offset,
            pivot_offset,
            pos_offset,
            axis,
        }
    }

    /// Create a grid with it's world position set to origin.
    pub fn origin(size: impl Size2d, pivot: Pivot) -> Self {
        WorldGrid::new(IVec2::ZERO, size, pivot)
    }

    /// Returns the tile position of a given tile.
    ///
    /// A tile's "position" refers to the bottom left point on the tile.
    #[inline]
    pub fn tile_pos(&self, grid_pos: impl Point2d) -> Vec2 {
        let grid_pos = grid_pos.as_ivec2().as_vec2();
        grid_pos + self.pos_offset
    }

    /// Returns the center point of a given tile.
    #[inline]
    pub fn tile_center(&self, grid_pos: impl Point2d) -> Vec2 {
        let grid_pos = grid_pos.as_ivec2().as_vec2();
        grid_pos + self.center_offset
    }

    /// Returns the position of the given tile in world space.
    ///
    /// A tile's "position" refers to the bottom left point on the tile.
    #[inline]
    pub fn tile_pos_world(&self, grid_pos: impl Point2d) -> Vec2 {
        self.tile_pos(grid_pos) + self.world_pos
    }

    /// Return's the center of the given tile in world space.
    #[inline]
    pub fn tile_center_world(&self, grid_pos: impl Point2d) -> Vec2 {
        self.tile_center(grid_pos) + self.world_pos
    }

    /// Whether or not the given grid position is inside the grid bounds.
    ///
    /// A grid's bounds are determined by it's pivot - a grid's pivot always
    /// sits on the world origin.
    #[inline]
    pub fn grid_pos_in_bounds(&self, grid_pos: impl Point2d) -> bool {
        self.try_grid_to_index_2d(grid_pos).is_some()
    }

    /// Whether or not the given 2d index is inside the grid bounds.
    #[inline]
    pub fn index_2d_in_bounds(&self, index: impl Point2d) -> bool {
        let index = index.as_ivec2();
        index.cmpge(IVec2::ZERO).all() && index.cmplt(self.size()).all()
    }

    /// Convert a grid point to it's corresponding 2d index.
    ///
    /// Returns none if the given grid point is out of bounds.
    pub fn try_grid_to_index_2d(&self, grid_pos: impl Point2d) -> Option<IVec2> {
        let center = self.tile_center(grid_pos);
        let index = center * self.axis - self.pivot_offset;

        if index.cmpge(Vec2::ZERO).all() && index.cmplt(self.size.as_vec2()).all() {
            return Some(index.as_ivec2());
        };
        None
    }

    /// Converts from a local grid position to it's corresponding 2d index.
    ///
    /// This function will return out of bounds values if given out of bounds grid positions.
    /// For a bound-checked version use `try_grid_to_index_2d`
    pub fn grid_to_index_2d(&self, grid_pos: impl Point2d) -> IVec2 {
        let center = self.tile_center(grid_pos);
        let index = center * self.axis - self.pivot_offset;
        index.as_ivec2()
    }

    /// Convert from a 2d index to it's corresponding grid position.
    pub fn index_2d_to_grid(&self, i: impl Point2d) -> IVec2 {
        let p = i.as_ivec2().as_vec2();
        let p = (self.pivot_offset - self.pos_offset) + p;
        let p = p + self.center_offset;
        let p = (p * self.axis).floor();
        p.as_ivec2()
    }

    pub fn width(&self) -> usize {
        self.size.x as usize
    }

    pub fn height(&self) -> usize {
        self.size.y as usize
    }

    pub fn size(&self) -> IVec2 {
        self.size
    }

    /// An iterator over the tile position of every tile in the grid.
    ///
    /// A tile's "position" refers to the bottom left point on the tile.
    pub fn tile_pos_iter(&self) -> impl Iterator<Item = Vec2> {
        self.iter(self.pivot_offset, self.axis)
    }

    /// An iterator over the tile center of every tile in the grid.
    pub fn tile_center_iter(&self) -> impl Iterator<Item = Vec2> {
        self.iter(self.pivot_offset + Vec2::new(0.5, 0.5), self.axis)
    }

    /// An iterator over the tile position of every tile in the grid.
    ///
    /// A tile's "position" refers to the bottom left point on the tile.
    pub fn tile_pos_iter_world(&self) -> impl Iterator<Item = Vec2> {
        let offset = self.world_pos;
        self.iter(self.pivot_offset + offset, self.axis)
    }

    /// Iterate over every tile in the grid, applying the given offset.
    #[inline]
    fn iter(&self, offset: Vec2, axis: Vec2) -> impl Iterator<Item = Vec2> {
        (0..self.height())
            .cartesian_product(0..self.width())
            .map(move |(y, x)| (Vec2::new(x as f32, y as f32) + offset) * axis)
    }
}

#[cfg(test)]
mod test {
    use crate::point::Pivot;

    use super::WorldGrid;

    #[test]
    fn center_iter_odd() {
        let grid = WorldGrid::origin([3, 3], Pivot::Center);
        let tiles: Vec<_> = grid.tile_center_iter().map(|p| (p.x, p.y)).collect();

        assert_eq!(tiles.len(), 9);
        assert_eq!(tiles[0], (-1.0, -1.0));
        assert_eq!(tiles[1], (0.0, -1.0));
        assert_eq!(tiles[2], (1.0, -1.0));
        assert_eq!(tiles[3], (-1.0, 0.0));
        assert_eq!(tiles[4], (0.0, 0.0));
        assert_eq!(tiles[8], (1.0, 1.0));
    }

    #[test]
    fn center_iter_even() {
        let grid = WorldGrid::origin([10, 10], Pivot::Center);

        let tiles: Vec<_> = grid.tile_center_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles.len(), 100);
        assert_eq!(tiles[0], (-4.5, -4.5));
        assert_eq!(tiles[1], (-3.5, -4.5));
        assert_eq!(tiles[2], (-2.5, -4.5));
        assert_eq!(tiles[3], (-1.5, -4.5));
        assert_eq!(tiles[99], (4.5, 4.5));

        let tiles: Vec<_> = grid.tile_pos_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles.len(), 100);
        assert_eq!(tiles[0], (-5.0, -5.0));
        assert_eq!(tiles[1], (-4.0, -5.0));
        assert_eq!(tiles[2], (-3.0, -5.0));
        assert_eq!(tiles[3], (-2.0, -5.0));
        assert_eq!(tiles[99], (4.0, 4.0));
    }

    #[test]
    fn bottom_left_iter_odd() {
        let grid = WorldGrid::origin([5, 5], Pivot::BottomLeft);

        let tiles: Vec<_> = grid.tile_center_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles.len(), 25);
        assert_eq!(tiles[0], (0.5, 0.5));
        assert_eq!(tiles[1], (1.5, 0.5));
        assert_eq!(tiles[2], (2.5, 0.5));
        assert_eq!(tiles[3], (3.5, 0.5));
        assert_eq!(tiles[24], (4.5, 4.5));

        let tiles: Vec<_> = grid.tile_pos_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles[0], (0.0, 0.0));
        assert_eq!(tiles[1], (1.0, 0.0));
        assert_eq!(tiles[2], (2.0, 0.0));
        assert_eq!(tiles[3], (3.0, 0.0));
        assert_eq!(tiles[24], (4.0, 4.0));
    }

    #[test]
    fn top_left_iter_odd() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopLeft);

        let tiles: Vec<_> = grid.tile_center_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles.len(), 25);
        assert_eq!(tiles[0], (0.5, -0.5));
        assert_eq!(tiles[1], (1.5, -0.5));
        assert_eq!(tiles[2], (2.5, -0.5));
        assert_eq!(tiles[3], (3.5, -0.5));
        assert_eq!(tiles[24], (4.5, -4.5));
    }

    #[test]
    fn bottom_right_iter_odd() {
        let grid = WorldGrid::origin([5, 5], Pivot::BottomRight);

        let tiles: Vec<_> = grid.tile_center_iter().map(|p| (p.x, p.y)).collect();
        assert_eq!(tiles.len(), 25);
        assert_eq!(tiles[0], (-0.5, 0.5));
        assert_eq!(tiles[1], (-1.5, 0.5));
        assert_eq!(tiles[2], (-2.5, 0.5));
        assert_eq!(tiles[3], (-3.5, 0.5));
        assert_eq!(tiles[24], (-4.5, 4.5));
    }

    #[test]
    fn center_bounds() {
        let grid = WorldGrid::origin([5, 5], Pivot::Center);

        assert!(!grid.grid_pos_in_bounds([-3, -3]));
        assert!(grid.grid_pos_in_bounds([-2, -2]));
        assert!(grid.grid_pos_in_bounds([-1, -1]));
        assert!(grid.grid_pos_in_bounds([0, 0]));
        assert!(grid.grid_pos_in_bounds([1, 1]));
        assert!(grid.grid_pos_in_bounds([2, 2]));
    }

    #[test]
    fn bottom_left_bounds() {
        let grid = WorldGrid::origin([5, 5], Pivot::BottomLeft);

        assert!(!grid.grid_pos_in_bounds([-1, -1]));
        assert!(grid.grid_pos_in_bounds([0, 0]));
        assert!(grid.grid_pos_in_bounds([1, 1]));
        assert!(grid.grid_pos_in_bounds([2, 2]));
        assert!(grid.grid_pos_in_bounds([3, 3]));
        assert!(grid.grid_pos_in_bounds([4, 4]));
        assert!(!grid.grid_pos_in_bounds([5, 5]));
    }

    #[test]
    fn top_right_bounds() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopRight);

        assert!(!grid.grid_pos_in_bounds([1, 1]));
        assert!(!grid.grid_pos_in_bounds([0, 0]));
        assert!(!grid.grid_pos_in_bounds([0, -1]));
        assert!(grid.grid_pos_in_bounds([-1, -2]));
        assert!(grid.grid_pos_in_bounds([-2, -3]));
        assert!(grid.grid_pos_in_bounds([-4, -4]));
    }

    #[test]
    fn top_right_grid_to_index_2d() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopRight);
        assert_eq!([0, 0], grid.grid_to_index_2d([-1, -1]).to_array());
        assert_eq!([1, 1], grid.grid_to_index_2d([-2, -2]).to_array());
        assert_eq!([2, 2], grid.grid_to_index_2d([-3, -3]).to_array());
    }

    #[test]
    fn top_right_grid_to_grid() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopRight);

        assert_eq!([-1, -1], grid.index_2d_to_grid([0, 0]).to_array());
        assert_eq!([-2, -2], grid.index_2d_to_grid([1, 1]).to_array());
        assert_eq!([-3, -3], grid.index_2d_to_grid([2, 2]).to_array());
    }

    #[test]
    fn top_left_grid_to_grid() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopLeft);

        assert_eq!([0, -1], grid.index_2d_to_grid([0, 0]).to_array());
        assert_eq!([1, -2], grid.index_2d_to_grid([1, 1]).to_array());
        assert_eq!([2, -3], grid.index_2d_to_grid([2, 2]).to_array());
    }

    #[test]
    fn bottom_left_grid_to_grid() {
        let grid = WorldGrid::origin([5, 5], Pivot::BottomLeft);

        assert_eq!([0, 0], grid.index_2d_to_grid([0, 0]).to_array());
    }

    #[test]
    fn top_left_grid_to_index_2d() {
        let grid = WorldGrid::origin([5, 5], Pivot::TopLeft);
        assert_eq!([0, 0], grid.grid_to_index_2d([0, -1]).to_array());
        assert_eq!([1, 1], grid.grid_to_index_2d([1, -2]).to_array());
        assert_eq!([2, 2], grid.grid_to_index_2d([2, -3]).to_array());
    }

    #[test]
    fn bottom_left_grid_to_index_2d() {
        let grid = WorldGrid::origin([5, 5], Pivot::BottomLeft);

        assert_eq!([0, 0], grid.grid_to_index_2d([0, 0]).to_array());
        assert_eq!([1, 1], grid.grid_to_index_2d([1, 1]).to_array());
        assert_eq!([2, 2], grid.grid_to_index_2d([2, 2]).to_array());
    }

    #[test]
    fn center_grid_to_index_2d() {
        let grid = WorldGrid::origin([5, 5], Pivot::Center);
        assert_eq!([0, 0], grid.grid_to_index_2d([-2, -2]).to_array());
        assert_eq!([1, 1], grid.grid_to_index_2d([-1, -1]).to_array());
        assert_eq!([2, 2], grid.grid_to_index_2d([0, 0]).to_array());
        assert_eq!([3, 3], grid.grid_to_index_2d([1, 1]).to_array());
        assert_eq!([4, 4], grid.grid_to_index_2d([2, 2]).to_array());
    }

    #[test]
    fn center_grid_to_grid() {
        let grid = WorldGrid::origin([5, 5], Pivot::Center);

        assert_eq!([-2, -2], grid.index_2d_to_grid([0, 0]).to_array());
        assert_eq!([-1, -1], grid.index_2d_to_grid([1, 1]).to_array());
        assert_eq!([0, 0], grid.index_2d_to_grid([2, 2]).to_array());
        assert_eq!([1, 1], grid.index_2d_to_grid([3, 3]).to_array());
        assert_eq!([2, 2], grid.index_2d_to_grid([4, 4]).to_array());
    }

    #[test]
    fn top_right_tile_center() {
        let grid = WorldGrid::origin([3, 3], Pivot::TopRight);

        assert_eq!([-0.5, -0.5], grid.tile_center([-1, -1]).to_array());
        assert_eq!([-1.5, -1.5], grid.tile_center([-2, -2]).to_array());
    }

    #[test]
    fn top_left_tile_center() {
        let grid = WorldGrid::origin([3, 3], Pivot::TopLeft);

        assert_eq!([0.5, -0.5], grid.tile_center([0, -1]).to_array());
        assert_eq!([1.5, -1.5], grid.tile_center([1, -2]).to_array());
    }

    #[test]
    fn center_tile_center_odd() {
        let grid = WorldGrid::origin([3, 3], Pivot::Center);

        assert_eq!([0.0, 0.0], grid.tile_center([0, 0]).to_array());
        assert_eq!([-1.0, -1.0], grid.tile_center([-1, -1]).to_array());
    }

    #[test]
    fn center_tile_center_even() {
        let grid = WorldGrid::origin([4, 4], Pivot::Center);

        assert_eq!([0.5, 0.5], grid.tile_center([0, 0]).to_array());
        assert_eq!([1.5, 1.5], grid.tile_center([1, 1]).to_array());
    }

    #[test]
    fn center_tile_pos_odd() {
        let grid = WorldGrid::origin([3, 3], Pivot::Center);

        assert_eq!([-0.5, -0.5], grid.tile_pos([0, 0]).to_array());
        assert_eq!([-1.5, -1.5], grid.tile_pos([-1, -1]).to_array());
    }

    #[test]
    fn center_tile_pos_even() {
        let grid = WorldGrid::origin([4, 4], Pivot::Center);

        assert_eq!([0.0, 0.0], grid.tile_pos([0, 0]).to_array());
        assert_eq!([-1.0, -1.0], grid.tile_pos([-1, -1]).to_array());
    }
}