hexx 0.24.0

Hexagonal utilities
Documentation
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
use crate::{Hex, HexOrientation, OffsetHexMode, storage::HexStore};
use glam::{IVec2, UVec2};
#[cfg(feature = "rayon")]
use rayon::prelude::*;
use std::fmt::Debug;

/// [`Vec`] Based storage for rectangular maps.
///
/// > See [this article](https://www.redblobgames.com/grids/hexagons/#map-storage)
///
/// [`RectMap`] is made for _rectangular_ large _dense_ maps, utilizing some
/// tricks to map [`Hex`] coordinate to a positive 1D array.
///
/// It can be used only if:
/// - The map is a rectanglar shape
/// - The map is _dense_
/// - No coordinate will be added or removed from the map
///
/// If your use case doesn't match all of the above, use a
/// [`std::collections::HashMap`] instead
///
/// # Example
/// ```rust
/// use hexx::{
///     storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
///     *,
/// };
///
/// let rect_map = RectMetadata::from_half_size(UVec2 { x: 8, y: 4 })
///     .with_orientation(HexOrientation::Pointy)
///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
///     .build_default::<i32>();
///
/// assert_eq!(rect_map.get(Hex::new(0, 0)), Some(&0));
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(
    feature = "bevy_ecs",
    derive(bevy_ecs::resource::Resource, bevy_ecs::component::Component)
)]
#[derive(Clone)]
pub struct RectMap<T> {
    inner: Vec<T>,
    meta: RectMetadata,
}

/// Metadata struct for [`RectMap`]
///
/// # Example
/// ```rust
/// # use hexx::{
/// #    storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
/// #    *,
/// # };
/// let rect_hex_map = RectMetadata::from_half_size(UVec2::new(8, 12))
///     .with_orientation(HexOrientation::Pointy)
///     .with_offset_mode(OffsetHexMode::Odd)
///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
///     .build_default::<i32>();
/// let hex = Hex::new(0, 0);
///
/// assert_eq!(rect_hex_map.get(hex), Some(&0_i32));
/// assert_eq!(rect_hex_map.wrapped_get(hex), &0_i32);
/// ```
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(
    feature = "bevy_ecs",
    derive(bevy_ecs::resource::Resource, bevy_ecs::component::Component)
)]
pub struct RectMetadata {
    /// the hex layout of the map
    orientation: HexOrientation,
    /// the offset mode of the map
    offset_mode: OffsetHexMode,
    /// the offset coordinate for the start element of the flat vec
    ///
    /// it represent the minimum offset coordinate element-wise among whole map
    start: IVec2,
    /// dimension of the map
    dim: UVec2,
    /// the wrapping strategy for indexing
    ///
    /// this only affect result of [`RectMap::wrapped_get`] and
    /// [`RectMap::wrapped_get_mut`]
    wrap_strategies: [WrapStrategy; 2],
}

/// Wrapping Strategy for when try to [`RectMap::wrapped_get`] and
/// [`RectMap::wrapped_get_mut`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
pub enum WrapStrategy {
    /// Clamp (offset) coordinate to `min` and `max - 1`
    ///
    /// useful for latitude/vertical coordinate
    Clamp,
    /// Cycle (offset) coordinate to range of`min` and `max - 1`
    ///
    /// useful for longitude/horizontal coordinate
    Cycle,
}

impl RectMetadata {
    /// Create a new [`RectMetadata`] with half size
    ///
    /// # Arguments
    /// * `half_size` - the half span of the map
    ///
    /// the resulting map will have:
    /// - columns: `-half_size[0]..(half_size[0] - 1)`, and
    /// - rows: `-half_size[1]..(half_size[1] - 1)`, and
    #[must_use]
    pub fn from_half_size(half_size: impl Into<UVec2>) -> Self {
        let half_size = half_size.into();
        Self {
            start: -half_size.as_ivec2(),
            dim: 2 * half_size,
            orientation: HexOrientation::Pointy,
            offset_mode: OffsetHexMode::Odd,
            wrap_strategies: [WrapStrategy::Cycle, WrapStrategy::Clamp],
        }
    }
    /// Create a new [`RectMetadata`] with start and end
    ///
    /// # Arguments
    /// * `start` - the element wise minimum offset coordinate in the map
    /// * `end` - the element wise maximum offset coordinate in the map
    ///
    /// the resulting map will have:
    /// - columns: `start[0]..max(start[0], end[0])`
    /// - rows: `start[1]..max(start[1], end[1])`
    #[must_use]
    pub fn from_start_end(start: IVec2, end: IVec2) -> Self {
        Self {
            start,
            dim: (end.max(start) - start).as_uvec2(),
            orientation: HexOrientation::Pointy,
            offset_mode: OffsetHexMode::Odd,
            wrap_strategies: [WrapStrategy::Cycle, WrapStrategy::Clamp],
        }
    }
    /// create a new [`RectMetadata`] with start and dimension
    ///
    /// # Arguments
    /// * `start` - the element wise minimum offset coordinate in the map
    /// * `dim` - the dimension of the map
    ///
    /// the resulting map will have:
    /// - columns: `start[0]..(start[0] + dim[0])`
    /// - rows: `start[1]..(start[1] + dim[1])`
    #[must_use]
    pub const fn from_start_dim(start: IVec2, dim: UVec2) -> Self {
        Self {
            start,
            dim,
            orientation: HexOrientation::Pointy,
            offset_mode: OffsetHexMode::Odd,
            wrap_strategies: [WrapStrategy::Cycle, WrapStrategy::Clamp],
        }
    }
    /// Sets map half size
    ///
    /// # Arguments
    /// * `half_size` - the half span of the map
    ///
    /// the resulting map will have:
    /// - columns: `-half_size[0]..(half_size[0] - 1)`, and
    /// - rows: `-half_size[1]..(half_size[1] - 1)`, and
    #[must_use]
    pub fn with_half_size(mut self, half_size: IVec2) -> Self {
        self.start = -half_size.abs();
        self.dim = (2 * half_size.abs()).as_uvec2();
        self
    }
    /// Sets start and end coordinates
    ///
    /// # Arguments
    /// * `start` - the element wise minimum offset coordinate in the map
    /// * `end` - the element wise maximum offset coordinate in the map
    ///
    /// the resulting map will have:
    /// - columns: `start[0]..max(start[0], end[0])`
    /// - rows: `start[1]..max(start[1], end[1])`
    #[must_use]
    pub fn with_start_end(mut self, start: IVec2, end: IVec2) -> Self {
        self.start = start;
        self.dim = (end.max(start) - start).as_uvec2();
        self
    }
    /// Sets the start coordinate and map dimension
    ///
    /// # Arguments
    /// * `start` - the element wise minimum offset coordinate in the map
    /// * `dim` - the dimension of the map
    ///
    /// the resulting map will have:
    /// - columns: `start[0]..(start[0] + dim[0])`
    /// - rows: `start[1]..(start[1] + dim[1])`
    #[must_use]
    pub const fn with_start_dim(mut self, start: IVec2, dim: UVec2) -> Self {
        self.start = start;
        self.dim = dim;
        self
    }
    /// Sets Hexagonal orientation
    #[must_use]
    pub const fn with_orientation(mut self, orientation: HexOrientation) -> Self {
        self.orientation = orientation;
        self
    }
    /// Setes coordinate offset mode
    #[must_use]
    pub const fn with_offset_mode(mut self, offset_mode: OffsetHexMode) -> Self {
        self.offset_mode = offset_mode;
        self
    }
    /// Sets the wrapping strategy
    ///
    /// this only affect result of [`RectMap::wrapped_get`] and
    /// [`RectMap::wrapped_get_mut`]
    #[must_use]
    pub const fn with_wrap_strategies(mut self, wrap_strategies: [WrapStrategy; 2]) -> Self {
        self.wrap_strategies = wrap_strategies;
        self
    }

    /// Build the map with function to eval value
    /// # Example
    /// ```rust
    /// # use hexx::{
    /// #    storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
    /// #    *,
    /// # };
    /// let rect_map = RectMetadata::from_half_size(UVec2 { x: 8, y: 4 })
    ///     .with_orientation(HexOrientation::Pointy)
    ///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
    ///     .build(|hex| hex.x + hex.y);
    ///
    /// assert_eq!(rect_map.get(Hex::new(0, 0)), Some(&0));
    /// ```
    #[inline]
    pub fn build<T>(self, values: impl FnMut(Hex) -> T) -> RectMap<T> {
        RectMap::new(self, values)
    }

    /// Build the map with function to eval value using parallel processing with
    /// `rayon`
    #[inline]
    #[cfg(feature = "rayon")]
    pub fn build_parallel<T, F>(self, values: F) -> RectMap<T>
    where
        F: Fn(Hex) -> T + Send + Sync,
        T: Send,
    {
        RectMap::new_parallel(self, values)
    }

    /// Builds map with default values
    /// # Example
    /// ```rust
    /// # use hexx::{
    /// #    storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
    /// #    *,
    /// # };
    /// let rect_map = RectMetadata::from_half_size(UVec2 { x: 8, y: 4 })
    ///     .with_orientation(HexOrientation::Pointy)
    ///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
    ///     .build_default::<i32>();
    ///
    /// assert_eq!(rect_map.get(Hex::new(0, 0)), Some(&0));
    /// ```
    #[must_use]
    pub fn build_default<T: Default>(self) -> RectMap<T> {
        RectMap::default_values(self)
    }

    /// Builds map with default values using parallel processing with
    /// `rayon`
    #[cfg(feature = "rayon")]
    #[must_use]
    pub fn build_default_parralel<T: Default + Send>(self) -> RectMap<T> {
        RectMap::default_values_parallel(self)
    }

    /// get the hex orientation of the map
    #[must_use]
    #[inline]
    pub const fn orientation(&self) -> HexOrientation {
        self.orientation
    }
    /// get the offset mode of the map
    #[must_use]
    #[inline]
    pub const fn offset_mode(&self) -> OffsetHexMode {
        self.offset_mode
    }
    /// get the dimension of the map
    #[must_use]
    #[inline]
    pub const fn dim(&self) -> UVec2 {
        self.dim
    }
    /// get the wrap strategies of the map
    #[must_use]
    #[inline]
    pub const fn wrap_strategies(&self) -> [WrapStrategy; 2] {
        self.wrap_strategies
    }

    // ================================
    // Forward Coordinate Conversion
    // ================================
    /// calculate hex coordinate from index
    ///
    /// infallible
    ///
    /// - `idx` `Vec` index
    /// - => `rc` 2D view of `Vec`
    /// - => `ij` offset coordinate
    /// - => `hex`
    fn idx_to_hex(&self, idx: usize) -> Hex {
        let ij = self.idx_to_ij(idx);
        self.ij_to_hex(ij)
    }

    #[expect(clippy::cast_possible_truncation)]
    fn idx_to_ij(&self, idx: usize) -> IVec2 {
        let idx = idx as u32;
        let rc = UVec2::new(idx % self.dim.x, idx / self.dim.x);
        rc.as_ivec2() + self.start
    }

    const fn ij_to_hex(&self, ij: IVec2) -> Hex {
        Hex::from_offset_coordinates(ij.to_array(), self.offset_mode, self.orientation)
    }

    // ================================
    // Backward Coordinate Conversion
    // ================================
    /// `None` if outside map
    fn hex_to_idx(&self, hex: Hex) -> Option<usize> {
        let ij = self.hex_to_offset(hex);
        self.contains_offset(ij).then(|| self.ij_to_idx(ij))
    }

    /// fallable input, internal
    ///
    /// - `ij` offset coordinate
    /// - => `rc` 2D view of `Vec`
    /// - => `idx` `Vec` index
    fn ij_to_idx(&self, ij: IVec2) -> usize {
        let rc = (ij - self.start).as_uvec2();
        (rc.x + rc.y * self.dim.x) as usize
    }

    /// Calculate offset coordinate from hex for map's orientation and offset
    /// mode
    #[must_use]
    pub fn hex_to_offset(&self, hex: Hex) -> IVec2 {
        hex.to_offset_coordinates(self.offset_mode, self.orientation)
            .into()
    }

    /// Wrap if `hex` lie outside of layout
    fn wrapped_hex_to_idx(&self, hex: Hex) -> usize {
        let ij = self.hex_to_offset(hex);
        let ij = self.wrap_offset(ij);
        self.ij_to_idx(ij)
    }

    /// Wrap a offset coordinate to ensure it fall inside the map
    #[must_use]
    pub fn wrap_offset(&self, offset: impl Into<IVec2>) -> IVec2 {
        let dim = self.dim.as_ivec2();
        let end = self.start + dim;
        let mut offset = offset.into();

        if self.wrap_strategies[0] == WrapStrategy::Cycle {
            while offset.x < self.start.x {
                offset.x += dim.x;
            }
            while offset.x >= end.x {
                offset.x -= dim.x;
            }
        } else {
            offset.x = offset.x.clamp(self.start.x, end.x - 1);
        }

        if self.wrap_strategies[1] == WrapStrategy::Cycle {
            while offset.y < self.start.y {
                offset.y += dim.y;
            }
            while offset.y >= end.y {
                offset.y -= dim.y;
            }
        } else {
            offset.y = offset.y.clamp(self.start.y, end.y - 1);
        }

        offset
    }

    /// Wrap a Hex to ensure it fall inside the map
    #[must_use]
    pub fn wrap_hex(&self, hex: Hex) -> Hex {
        let ij = self.hex_to_offset(hex);
        let ij = self.wrap_offset(ij);
        self.ij_to_hex(ij)
    }

    // ================================
    // Contains
    // ================================
    /// whether the map contains certain `Hex`
    #[must_use]
    pub fn contains_hex(&self, hex: Hex) -> bool {
        self.contains_offset(self.hex_to_offset(hex))
    }
    /// whether the map contains certain offset coordinate
    #[must_use]
    pub fn contains_offset(&self, offset_coord: impl Into<IVec2>) -> bool {
        let offset_coord = offset_coord.into();
        offset_coord
            == offset_coord.clamp(self.start, self.start + self.dim.as_ivec2() - IVec2::ONE)
            && !self.is_empty()
    }

    // ================================
    // Iteration
    // ================================
    /// total size of the map
    #[must_use]
    #[inline]
    pub fn len(&self) -> usize {
        self.dim.element_product() as usize
    }

    /// whether of not the map layout is empty
    #[must_use]
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// iterator over the hexagonal coordinates in the map.
    #[must_use]
    pub fn iter_hex(&self) -> impl ExactSizeIterator<Item = Hex> {
        (0..self.len()).map(|idx| self.idx_to_hex(idx))
    }
    /// Parallel iterator over the hexagonal coordinates in the map.
    #[cfg(feature = "rayon")]
    #[must_use]
    pub fn iter_par_hex(&self) -> impl IndexedParallelIterator<Item = Hex> {
        (0..self.len())
            .into_par_iter()
            .map(|idx| self.idx_to_hex(idx))
    }
    /// iterator over the offset coordinates in the map.
    #[must_use]
    pub fn iter_offset(&self) -> impl ExactSizeIterator<Item = IVec2> {
        (0..self.len()).map(|idx| self.idx_to_ij(idx))
    }
    /// Parallel iterator over the offset coordinates in the map.
    #[cfg(feature = "rayon")]
    #[must_use]
    pub fn iter_par_offset(&self) -> impl IndexedParallelIterator<Item = IVec2> {
        (0..self.len())
            .into_par_iter()
            .map(|idx| self.idx_to_ij(idx))
    }
}

impl<T> RectMap<T> {
    /// Creates and fills a rectangular shaped map
    ///
    /// # Arguments
    /// * `meta` - The meta data for the map to create.
    /// * `values` - Function called for each coordinate to fill the map
    ///
    /// # Example
    /// ```
    /// # use hexx::{
    /// #     storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
    /// #     *,
    /// # };
    ///
    /// let meta = RectMetadata::from_half_size(UVec2 { x: 8, y: 4 })
    ///     .with_orientation(HexOrientation::Pointy)
    ///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp]);
    /// let rect_map = RectMap::new(meta, |hex| hex.x + hex.y);
    ///
    /// assert_eq!(rect_map.get(Hex::new(0, 0)), Some(&0));
    /// ```
    #[must_use]
    pub fn new(meta: RectMetadata, values: impl FnMut(Hex) -> T) -> Self {
        let inner = meta.iter_hex().map(values).collect();
        Self { inner, meta }
    }

    /// Creates and fills a rectangular shaped map using parallel processing
    /// with `rayon`
    ///
    /// # Arguments
    /// * `meta` - The meta data for the map to create.
    /// * `values` - Function called for each coordinate to fill the map
    #[cfg(feature = "rayon")]
    pub fn new_parallel<F>(meta: RectMetadata, values: F) -> Self
    where
        F: Fn(Hex) -> T + Send + Sync,
        T: Send,
    {
        let mut inner = Vec::with_capacity(meta.len());
        meta.iter_par_hex().map(values).collect_into_vec(&mut inner);
        Self { inner, meta }
    }

    /// get the [`RectMetadata`] of the map.
    #[must_use]
    #[inline]
    pub const fn meta(&self) -> &RectMetadata {
        &self.meta
    }

    /// Creates and fills a rectangular shaped map using default values
    ///
    /// # Arguments
    /// * `meta` - The meta data for the map to create.
    ///
    /// # Example
    /// ```
    /// # use hexx::{
    /// #    storage::{HexStore, RectMap, RectMetadata, WrapStrategy},
    /// #    *,
    /// # };
    ///
    /// let meta = RectMetadata::from_half_size(UVec2 { x: 8, y: 4 })
    ///     .with_orientation(HexOrientation::Pointy)
    ///     .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp]);
    /// let rect_map = RectMap::default_values(meta);
    ///
    /// assert_eq!(rect_map.get(Hex::new(0, 0)), Some(&0));
    /// ```
    #[must_use]
    #[inline]
    pub fn default_values(meta: RectMetadata) -> Self
    where
        T: Default,
    {
        Self::new(meta, |_| Default::default())
    }

    /// Creates and fills a rectangular shaped map using default values and
    /// parallel processing with `rayon`
    ///
    /// # Arguments
    /// * `meta` - The meta data for the map to create.
    #[cfg(feature = "rayon")]
    #[must_use]
    #[inline]
    pub fn default_values_parallel(meta: RectMetadata) -> Self
    where
        T: Default + Send,
    {
        Self::new_parallel(meta, |_| Default::default())
    }

    /// Returns a reference the stored value associated with offset coordinate.
    /// Returns `None` if `offset_coord` is out of bounds
    #[must_use]
    pub fn get_by_offset(&self, offset_coord: impl Into<IVec2>) -> Option<&T> {
        let offset_coord = offset_coord.into();
        if self.contains_offset(offset_coord) {
            let idx = self.ij_to_idx(offset_coord);
            Some(&self.inner[idx])
        } else {
            None
        }
    }
    /// Returns a mutable reference the stored value associated with offset
    /// coordinate. Returns `None` if `offset_coord` is out of bounds
    #[must_use]
    pub fn get_mut_by_offset(&mut self, offset_coord: impl Into<IVec2>) -> Option<&mut T> {
        let offset_coord = offset_coord.into();
        if self.contains_offset(offset_coord) {
            let idx = self.ij_to_idx(offset_coord);
            Some(&mut self.inner[idx])
        } else {
            None
        }
    }

    // ================================
    // Wrapped Index
    // ================================
    /// Returns a reference the stored value associated with hexagonal
    /// coordinate Wrap if `hex` lie outside of layout
    #[must_use]
    pub fn wrapped_get(&self, hex: Hex) -> &T {
        let idx = self.wrapped_hex_to_idx(hex);
        &self.inner[idx]
    }

    /// Returns a mutable reference the stored value associated with hexagonal
    /// coordinate Wrap if `hex` lie outside of layout
    #[must_use]
    pub fn wrapped_get_mut(&mut self, hex: Hex) -> &mut T {
        let idx = self.wrapped_hex_to_idx(hex);
        &mut self.inner[idx]
    }

    /// Returns a reference the stored value associated with offset coordinate
    /// Wrap if `hex` lie outside of layout
    #[must_use]
    pub fn wrapped_get_by_offset(&self, offset_coord: impl Into<IVec2>) -> &T {
        let wrapped = self.wrap_offset(offset_coord);
        let idx = self.ij_to_idx(wrapped);
        &self.inner[idx]
    }
    /// Returns a mutable reference the stored value associated with offset
    /// coordinate Wrap if `hex` lie outside of layout
    #[must_use]
    pub fn wrapped_get_mut_by_offset(&mut self, offset_coord: impl Into<IVec2>) -> &mut T {
        let wrapped = self.wrap_offset(offset_coord);
        let idx = self.ij_to_idx(wrapped);
        &mut self.inner[idx]
    }
}

impl<T> std::ops::Deref for RectMap<T> {
    type Target = RectMetadata;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.meta()
    }
}

impl<T> HexStore<T> for RectMap<T> {
    fn get(&self, hex: crate::Hex) -> Option<&T> {
        let idx = self.meta.hex_to_idx(hex)?;
        self.inner.get(idx)
    }
    fn get_mut(&mut self, hex: crate::Hex) -> Option<&mut T> {
        let idx = self.meta.hex_to_idx(hex)?;
        self.inner.get_mut(idx)
    }
    #[inline]
    fn values<'s>(&'s self) -> impl ExactSizeIterator<Item = &'s T>
    where
        T: 's,
    {
        self.inner.iter()
    }
    #[inline]
    fn values_mut<'s>(&'s mut self) -> impl ExactSizeIterator<Item = &'s mut T>
    where
        T: 's,
    {
        self.inner.iter_mut()
    }
    #[inline]
    fn iter<'s>(&'s self) -> impl ExactSizeIterator<Item = (crate::Hex, &'s T)>
    where
        T: 's,
    {
        self.values().enumerate().map(|(i, value)| {
            let hex = self.meta.idx_to_hex(i);
            (hex, value)
        })
    }
    #[inline]
    fn iter_mut<'s>(&'s mut self) -> impl ExactSizeIterator<Item = (crate::Hex, &'s mut T)>
    where
        T: 's,
    {
        let meta = self.meta.clone();
        self.values_mut().enumerate().map(move |(i, value)| {
            let hex = meta.idx_to_hex(i);
            (hex, value)
        })
    }
}

impl<T: Debug> Debug for RectMap<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RectMap")
            .field("inner", &self.inner)
            .field("meta", &self.meta)
            .finish()
    }
}

#[cfg(test)]
mod half_size_test {
    use super::*;

    // Test dimensions for creating RectHexMap instances.
    const HALF_SIZES: &[[u32; 2]] = &[
        [0, 0],
        [0, 1],
        [1, 1],
        [2, 2],
        [8, 4],
        [16, 8],
        [28, 8],
        [64, 128],
        [127, 201],
        [256, 512],
    ];

    const WRAP_STRATEGIES: &[[WrapStrategy; 2]] = &[
        [WrapStrategy::Clamp, WrapStrategy::Clamp],
        [WrapStrategy::Clamp, WrapStrategy::Cycle],
        [WrapStrategy::Cycle, WrapStrategy::Clamp],
        [WrapStrategy::Cycle, WrapStrategy::Cycle],
    ];

    /// Tests the conversion between index and hexagonal coordinates.
    #[test]
    fn idx_hex_test() {
        for dim in HALF_SIZES {
            let rect_map = RectMetadata::from_half_size(UVec2::from_array(*dim))
                .with_orientation(HexOrientation::Pointy)
                .with_offset_mode(OffsetHexMode::Odd)
                .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
                .build_default::<i32>();

            for idx in 0..rect_map.len() {
                let hex = rect_map.idx_to_hex(idx);
                assert!(rect_map.contains_hex(hex));
                let _idx = rect_map.hex_to_idx(hex);
                assert_eq!(Some(idx), _idx);
            }
            assert_eq!(rect_map.iter().count(), rect_map.len());
        }
    }

    /// Tests the containment of ij coordinates within the map.
    #[test]
    fn contains_test() {
        for dim in HALF_SIZES {
            let rect_map = RectMetadata::from_half_size(UVec2::from_array(*dim))
                .with_orientation(HexOrientation::Pointy)
                .with_offset_mode(OffsetHexMode::Odd)
                .with_wrap_strategies([WrapStrategy::Cycle, WrapStrategy::Clamp])
                .build_default::<i32>();

            let dim = [dim[0] as i32, dim[1] as i32];

            for a in -2..2 {
                for b in -2..2 {
                    for i in (2 * a * dim[0])..((2 * a + 1) * dim[0]) {
                        for j in (2 * b * dim[1])..((2 * b + 1) * dim[1]) {
                            assert_eq!(
                                a == 0 && b == 0,
                                rect_map.contains_offset(IVec2::new(i, j))
                            );
                            assert_eq!(
                                a == 0 && b == 0,
                                rect_map.get_by_offset(IVec2::new(i, j)).is_some()
                            );
                        }
                    }
                }
            }
        }
    }

    /// Tests the wrapping functionality of ij coordinates.
    #[test]
    fn wrap_test() {
        for dim in HALF_SIZES {
            for wrap_strategies in WRAP_STRATEGIES {
                let rect_map = RectMetadata::from_half_size(UVec2::from_array(*dim))
                    .with_orientation(HexOrientation::Pointy)
                    .with_offset_mode(OffsetHexMode::Odd)
                    .with_wrap_strategies(*wrap_strategies)
                    .build_default::<i32>();

                let dim = [dim[0] as i32, dim[1] as i32];

                for a in -2..2 {
                    for b in -2..2 {
                        let i_iter_a = (2 * a * dim[0] - dim[0])..((2 * a) * dim[0] + dim[0]);
                        let i_iter_b: Box<dyn Iterator<Item = i32>> =
                            if wrap_strategies[0] == WrapStrategy::Cycle {
                                Box::new(-dim[0]..dim[0])
                            } else {
                                Box::new(i_iter_a.clone().map(|i| i.clamp(-dim[0], dim[0] - 1)))
                            };

                        for (ia, ib) in i_iter_a.zip(i_iter_b) {
                            let j_iter_a = (2 * b * dim[1] - dim[1])..((2 * b) * dim[1] + dim[1]);
                            let j_iter_b: Box<dyn Iterator<Item = i32>> =
                                if wrap_strategies[1] == WrapStrategy::Cycle {
                                    Box::new(-dim[1]..dim[1])
                                } else {
                                    Box::new(j_iter_a.clone().map(|j| j.clamp(-dim[1], dim[1] - 1)))
                                };

                            for (ja, jb) in j_iter_a.zip(j_iter_b) {
                                let ij_a = IVec2::new(ia, ja);
                                let ij_b = IVec2::new(ib, jb);

                                let wij_a = rect_map.wrap_offset(ij_a);
                                let wij_b = rect_map.wrap_offset(ij_b);

                                assert_eq!(wij_a, wij_b);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Tests value construction
    #[test]
    fn construction_test() {
        for dim in HALF_SIZES {
            let rect_map =
                RectMetadata::from_half_size(UVec2::from_array(*dim)).build(|h| h.x * 1000 + h.y);

            for (h, v) in rect_map.iter() {
                assert_eq!(h.x * 1000 + h.y, *v);
            }
        }
    }
}

#[cfg(test)]
mod start_end_test {
    // ================================
    // Start End Test
    // ================================
    use super::*;

    const START_END: &[([i32; 2], [i32; 2])] = &[
        ([0, 0], [0, 0]),
        ([0, 0], [1, 1]),
        ([-1, -1], [1, 1]),
        ([-10, -10], [10, 10]),
        ([-10, -10], [15, 15]),
        ([0, 0], [15, 15]),
        ([0, 0], [-30, -30]),
        ([-17, -13], [31, 41]),
        ([-64, -64], [64, 64]),
    ];

    const WRAP_STRATEGIES: &[[WrapStrategy; 2]] = &[
        [WrapStrategy::Clamp, WrapStrategy::Clamp],
        [WrapStrategy::Clamp, WrapStrategy::Cycle],
        [WrapStrategy::Cycle, WrapStrategy::Clamp],
        [WrapStrategy::Cycle, WrapStrategy::Cycle],
    ];

    /// Tests the conversion between index and hexagonal coordinates.
    #[test]
    fn idx_hex_test() {
        for (start, end) in START_END {
            let rect_map =
                RectMetadata::from_start_end((*start).into(), (*end).into()).build_default::<i32>();

            for idx in 0..rect_map.len() {
                let hex = rect_map.idx_to_hex(idx);
                assert!(rect_map.contains_hex(hex));
                let ij = rect_map.hex_to_offset(hex);
                assert!(rect_map.contains_offset(ij));
                assert_eq!(Some(idx), rect_map.hex_to_idx(hex));
            }
            assert_eq!(rect_map.iter().count(), rect_map.len());
        }
    }

    /// Tests the containment of ij coordinates within the map.
    #[test]
    fn contains_test() {
        for (start, end) in START_END {
            let rect_map =
                RectMetadata::from_start_end((*start).into(), (*end).into()).build_default::<i32>();

            for i in (start[0] - 10)..(end[0] + 10) {
                for j in (start[1] - 10)..(end[1] + 10) {
                    let contain = (i >= start[0] && i < end[0]) && (j >= start[1] && j < end[1]);

                    println!(
                        "{:?} || {:?} - {:?} | {}, {} | {}",
                        rect_map.dim, start, end, i, j, contain
                    );

                    assert_eq!(rect_map.contains_offset([i, j]), contain);
                    assert_eq!(rect_map.get_by_offset([i, j]).is_some(), contain);
                }
            }
        }
    }

    /// Tests the wrapping functionality of ij coordinates.
    #[test]
    fn wrap_test() {
        for (start, end) in START_END {
            for wrap_strategies in WRAP_STRATEGIES {
                let rect_map = RectMetadata::from_start_end((*start).into(), (*end).into())
                    .with_wrap_strategies(*wrap_strategies)
                    .build_default::<i32>();

                let dim = [(end[0] - start[0]).max(0), (end[1] - start[1]).max(0)];

                for a in -2..2 {
                    for b in -2..2 {
                        let i_iter_a = (2 * a * dim[0] - dim[0])..((2 * a) * dim[0] + dim[0]);
                        let i_iter_b: Box<dyn Iterator<Item = i32>> =
                            if wrap_strategies[0] == WrapStrategy::Cycle {
                                Box::new(-dim[0]..dim[0])
                            } else {
                                Box::new(i_iter_a.clone().map(|i| i.clamp(-dim[0], dim[0] - 1)))
                            };

                        for (ia, ib) in i_iter_a.zip(i_iter_b) {
                            let j_iter_a = (2 * b * dim[1] - dim[1])..((2 * b) * dim[1] + dim[1]);
                            let j_iter_b: Box<dyn Iterator<Item = i32>> =
                                if wrap_strategies[1] == WrapStrategy::Cycle {
                                    Box::new(-dim[1]..dim[1])
                                } else {
                                    Box::new(j_iter_a.clone().map(|j| j.clamp(-dim[1], dim[1] - 1)))
                                };

                            for (ja, jb) in j_iter_a.zip(j_iter_b) {
                                let ij_a = IVec2::new(ia, ja);
                                let ij_b = IVec2::new(ib, jb);

                                let wij_a = rect_map.wrap_offset(ij_a);
                                let wij_b = rect_map.wrap_offset(ij_b);

                                assert_eq!(wij_a, wij_b);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Tests value construction
    #[test]
    fn construction_test() {
        for (start, end) in START_END {
            let rect_map = RectMetadata::from_start_end((*start).into(), (*end).into())
                .build(|h| h.x * 1000 + h.y);

            for (h, v) in rect_map.iter() {
                assert_eq!(h.x * 1000 + h.y, *v);
            }
        }
    }
}

#[cfg(test)]
mod start_dim_test {
    // ================================
    // Start End Test
    // ================================
    use super::*;

    const START_END: &[([i32; 2], [u32; 2])] = &[
        ([0, 0], [0, 0]),
        ([0, 0], [1, 1]),
        ([-1, -1], [1, 1]),
        ([-10, -10], [10, 10]),
        ([-10, -10], [15, 15]),
        ([0, 0], [15, 15]),
        ([0, 0], [30, 30]),
        ([-17, -13], [31, 41]),
        ([-64, -64], [64, 64]),
    ];

    const WRAP_STRATEGIES: &[[WrapStrategy; 2]] = &[
        [WrapStrategy::Clamp, WrapStrategy::Clamp],
        [WrapStrategy::Clamp, WrapStrategy::Cycle],
        [WrapStrategy::Cycle, WrapStrategy::Clamp],
        [WrapStrategy::Cycle, WrapStrategy::Cycle],
    ];

    /// Tests the conversion between index and hexagonal coordinates.
    #[test]
    fn idx_hex_test() {
        for (start, dim) in START_END {
            let rect_map =
                RectMetadata::from_start_dim((*start).into(), (*dim).into()).build_default::<i32>();

            for idx in 0..rect_map.len() {
                let hex = rect_map.idx_to_hex(idx);
                assert!(rect_map.contains_hex(hex));
                let ij = rect_map.hex_to_offset(hex);
                assert!(rect_map.contains_offset(ij));
                assert_eq!(Some(idx), rect_map.hex_to_idx(hex));
            }
            assert_eq!(rect_map.iter().count(), rect_map.len());
        }
    }

    /// Tests the containment of ij coordinates within the map.
    #[test]
    fn contains_test() {
        for (start, dim) in START_END {
            let rect_map =
                RectMetadata::from_start_dim((*start).into(), (*dim).into()).build_default::<i32>();

            for i in (start[0] - 10)..(start[0] + dim[0] as i32 + 10) {
                for j in (start[1] - 10)..(start[1] + dim[1] as i32 + 10) {
                    let contain = (i >= start[0] && i < start[0] + dim[0] as i32)
                        && (j >= start[1] && j < start[1] + dim[1] as i32);
                    assert_eq!(rect_map.contains_offset([i, j]), contain);
                    assert_eq!(rect_map.get_by_offset([i, j]).is_some(), contain);
                }
            }
        }
    }

    /// Tests the wrapping functionality of ij coordinates.
    #[test]
    fn wrap_test() {
        for (start, dim) in START_END {
            for wrap_strategies in WRAP_STRATEGIES {
                let rect_map = RectMetadata::from_start_dim((*start).into(), (*dim).into())
                    .with_wrap_strategies(*wrap_strategies)
                    .build_default::<i32>();

                let dim = [dim[0] as i32, dim[1] as i32];

                for a in -2..2 {
                    for b in -2..2 {
                        let i_iter_a = (2 * a * dim[0] - dim[0])..((2 * a) * dim[0] + dim[0]);
                        let i_iter_b: Box<dyn Iterator<Item = i32>> =
                            if wrap_strategies[0] == WrapStrategy::Cycle {
                                Box::new(-dim[0]..dim[0])
                            } else {
                                Box::new(i_iter_a.clone().map(|i| i.clamp(-dim[0], dim[0] - 1)))
                            };

                        for (ia, ib) in i_iter_a.zip(i_iter_b) {
                            let j_iter_a = (2 * b * dim[1] - dim[1])..((2 * b) * dim[1] + dim[1]);
                            let j_iter_b: Box<dyn Iterator<Item = i32>> =
                                if wrap_strategies[1] == WrapStrategy::Cycle {
                                    Box::new(-dim[1]..dim[1])
                                } else {
                                    Box::new(j_iter_a.clone().map(|j| j.clamp(-dim[1], dim[1] - 1)))
                                };

                            for (ja, jb) in j_iter_a.zip(j_iter_b) {
                                let ij_a = IVec2::new(ia, ja);
                                let ij_b = IVec2::new(ib, jb);

                                let wij_a = rect_map.wrap_offset(ij_a);
                                let wij_b = rect_map.wrap_offset(ij_b);

                                assert_eq!(wij_a, wij_b);
                            }
                        }
                    }
                }
            }
        }
    }

    /// Tests value construction
    #[test]
    fn construction_test() {
        for (start, dim) in START_END {
            let rect_map = RectMetadata::from_start_dim((*start).into(), (*dim).into())
                .build(|h| h.x * 1000 + h.y);

            for (h, v) in rect_map.iter() {
                assert_eq!(h.x * 1000 + h.y, *v);
            }
        }
    }
}