rpgx 0.1.3

Lightweight, modular, and extensible RPG game engine 2D, designed for flexibility, portability, and ease of use.
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
use std::{
    fmt,
    ops::{Add, Sub},
};

use crate::prelude::{Coordinates, Delta, Shape};

/// Errors related to [`Rect`] construction and manipulation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RectError {
    /// Returned when trying to construct a [`Rect`] from an empty list of rectangles.
    EmptyRectList,
}

#[doc = include_str!("../../docs/rect.md")]
/// A rectangular region on a 2D grid, aligned to the grid axes.
///
/// Represented by a top-left origin [`Coordinates`] and a [`Shape`] defining its width and height.
/// All dimensions and coordinates are unsigned and non-negative.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Rect {
    /// Top-left corner of the rectangle.
    pub origin: Coordinates,

    /// Dimensions of the rectangle (width × height).
    pub shape: Shape,
}

impl Rect {
    /// Creates a new `Rect` with the given origin and shape.
    pub fn new(origin: Coordinates, shape: Shape) -> Self {
        Self { origin, shape }
    }

    /// Creates a `Rect` with the given shape at origin (0, 0).
    pub fn from_shape(shape: Shape) -> Self {
        Self {
            origin: Coordinates { x: 0, y: 0 },
            shape,
        }
    }

    /// Creates a 1×1 `Rect` at the given origin.
    pub fn from_origin(origin: Coordinates) -> Self {
        Self {
            origin,
            shape: Shape::from_square(1),
        }
    }

    /// Attempts to create a single `Rect` that bounds a set of 1×1 rectangles.
    ///
    /// Returns an error if the input list is empty.
    ///
    /// # Errors
    /// Returns [`RectError::EmptyRectList`] if `rects` is empty.
    pub fn from_many(rects: Vec<Self>) -> Result<Self, RectError> {
        if rects.is_empty() {
            return Err(RectError::EmptyRectList);
        }

        let mut min_x = u32::MAX;
        let mut min_y = u32::MAX;
        let mut max_x = u32::MIN;
        let mut max_y = u32::MIN;

        for rect in rects {
            let Coordinates { x, y } = rect.origin;
            min_x = min_x.min(x);
            min_y = min_y.min(y);
            max_x = max_x.max(x);
            max_y = max_y.max(y);
        }

        let origin = Coordinates { x: min_x, y: min_y };
        let shape = Shape {
            width: max_x - min_x + 1,
            height: max_y - min_y + 1,
        };

        Ok(Rect { origin, shape })
    }

    /// Creates a new `Rect` from origin `(x, y)` and dimensions `(width, height)`.
    pub fn from_xywh(x: u32, y: u32, width: u32, height: u32) -> Self {
        Self {
            origin: Coordinates { x, y },
            shape: Shape { width, height },
        }
    }
}

impl Rect {
    /// Splits this `Rect` into multiple 1×1 `Rect`s, one per tile.
    ///
    /// This is useful for applying per-tile logic or reconstruction.
    ///
    pub fn into_many(&self) -> Vec<Self> {
        self.iter()
            .map(|coord| Rect {
                origin: coord,
                shape: Shape::from_square(1),
            })
            .collect()
    }

    pub fn into_single(&self) -> Vec<Self> {
        vec![*self]
    }

    /// Returns the perimeter tiles of the rect as 1×1 `Rect`s offset inward by `offset`, with `size` thickness.
    ///
    /// Tiles are returned clockwise starting from the top-left corner of the outermost perimeter band.
    ///
    /// # Arguments
    /// * `offset` - Distance from the edge before the perimeter starts.
    /// * `size` - Thickness of the perimeter band.
    ///
    /// # Panics
    /// Panics if `offset + size` exceeds half the width or height.
    ///
    pub fn into_perimeter(&self, offset: u32, size: u32) -> Vec<Self> {
        let mut perimeter = Vec::new();

        if self.shape.width <= 2 * offset || self.shape.height <= 2 * offset {
            return perimeter;
        }

        let max_size = std::cmp::min(
            (self.shape.width / 2).saturating_sub(offset),
            (self.shape.height / 2).saturating_sub(offset),
        );

        let size = size.min(max_size);

        for s in 0..size {
            let left = self.origin.x + offset + s;
            let right = self.origin.x + self.shape.width - 1 - offset - s;
            let top = self.origin.y + offset + s;
            let bottom = self.origin.y + self.shape.height - 1 - offset - s;

            // Top edge
            for x in left..=right {
                perimeter.push(Rect::from_xywh(x, top, 1, 1));
            }
            // Right edge
            for y in (top + 1)..bottom {
                perimeter.push(Rect::from_xywh(right, y, 1, 1));
            }
            // Bottom edge
            if bottom > top {
                for x in (left..=right).rev() {
                    perimeter.push(Rect::from_xywh(x, bottom, 1, 1));
                }
            }
            // Left edge
            if right > left {
                for y in ((top + 1)..bottom).rev() {
                    perimeter.push(Rect::from_xywh(left, y, 1, 1));
                }
            }
        }

        perimeter
    }

    /// Returns a vertical or horizontal bisector band of 1×1 `Rect`s offset inward by `offset`, with `size` thickness.
    ///
    /// If the inner width is greater than or equal to height, returns a vertical band; otherwise, horizontal.
    ///
    /// # Arguments
    /// * `offset` - Distance from the edge before bisecting.
    /// * `size` - Thickness of the bisector (number of rows or columns).
    pub fn into_bisector(&self, offset: u32, size: u32) -> Vec<Self> {
        let mut bisector = Vec::new();

        if self.shape.width <= 2 * offset || self.shape.height <= 2 * offset {
            return bisector;
        }

        let left = self.origin.x + offset;
        let top = self.origin.y + offset;
        let width = self.shape.width - 2 * offset;
        let height = self.shape.height - 2 * offset;

        if width >= height {
            // Vertical strip
            let center_x = left + width / 2;
            let half = (size / 2) as i32;

            for dx in -half..=(half + (size % 2 == 0) as i32 - 1) {
                let x = center_x as i32 + dx;
                if x >= left as i32 && x < (left + width) as i32 {
                    for y in top..top + height {
                        bisector.push(Rect::from_xywh(x as u32, y, 1, 1));
                    }
                }
            }
        } else {
            // Horizontal strip
            let center_y = top + height / 2;
            let half = (size / 2) as i32;

            for dy in -half..=(half + (size % 2 == 0) as i32 - 1) {
                let y = center_y as i32 + dy;
                if y >= top as i32 && y < (top + height) as i32 {
                    for x in left..left + width {
                        bisector.push(Rect::from_xywh(x, y as u32, 1, 1));
                    }
                }
            }
        }

        bisector
    }

    /// Returns a center block of `size × size` 1×1 `Rect`s offset inward by `offset`.
    ///
    /// # Arguments
    /// * `offset` - Distance from the edge before selecting center.
    /// * `size` - Width and height of the center selection.
    ///
    /// # Notes
    /// If the rect is too small to fit the center block after offset, returns empty.
    pub fn into_center(&self, offset: u32, size: u32) -> Vec<Self> {
        let mut center = Vec::new();

        if self.shape.width <= 2 * offset || self.shape.height <= 2 * offset {
            return center;
        }

        let inner_width = self.shape.width - 2 * offset;
        let inner_height = self.shape.height - 2 * offset;

        if inner_width < size || inner_height < size {
            return center;
        }

        let left = self.origin.x + offset + (inner_width - size) / 2;
        let top = self.origin.y + offset + (inner_height - size) / 2;

        for x in left..left + size {
            for y in top..top + size {
                center.push(Rect::from_xywh(x, y, 1, 1));
            }
        }

        center
    }

    /// Returns tiles approximating a rhombus (diamond-shaped) area around the center,
    /// including all tiles within `dial` distance (Manhattan distance) from the center tile(s).
    ///
    /// The circle is clamped to the rectangle bounds.
    pub fn into_rhombus(&self, dial: u32) -> Vec<Self> {
        let mut tiles = Vec::new();

        if self.shape.width == 0 || self.shape.height == 0 {
            return tiles;
        }

        let left = self.origin.x;
        let top = self.origin.y;
        let width = self.shape.width;
        let height = self.shape.height;

        // Find center coordinates (can be 1 or 4 tiles for even dimensions)
        let center_x = left + width / 2;
        let center_y = top + height / 2;

        // For even width or height, center is between tiles, so consider all 1x1 tiles near center:
        // We'll just consider center points as in into_center:
        let centers = if width % 2 == 1 && height % 2 == 1 {
            vec![(center_x, center_y)]
        } else {
            let cx_start = if width % 2 == 0 {
                center_x - 1
            } else {
                center_x
            };
            let cy_start = if height % 2 == 0 {
                center_y - 1
            } else {
                center_y
            };

            vec![
                (cx_start, cy_start),
                (cx_start + 1, cy_start),
                (cx_start, cy_start + 1),
                (cx_start + 1, cy_start + 1),
            ]
        };

        // Collect tiles within dial (Manhattan distance) from any center tile, clamped to rect bounds
        for x in left..left + width {
            for y in top..top + height {
                if centers.iter().any(|&(cx, cy)| {
                    let dist = (cx as i32 - x as i32).abs() + (cy as i32 - y as i32).abs();
                    dist as u32 <= dial
                }) {
                    tiles.push(Rect::from_xywh(x, y, 1, 1));
                }
            }
        }

        tiles
    }

    pub fn into_circle(&self) -> Vec<Rect> {
        let center = self.center();
        let radius_x = self.shape.width as f32 / 2.0;
        let radius_y = self.shape.height as f32 / 2.0;

        self.iter()
            .filter(|coord| {
                // Normalize coordinates relative to center
                let dx = (coord.x as f32 + 0.5) - (center.x as f32 + 0.5);
                let dy = (coord.y as f32 + 0.5) - (center.y as f32 + 0.5);

                // Use ellipse equation (dx/rx)^2 + (dy/ry)^2 <= 1
                (dx * dx) / (radius_x * radius_x) + (dy * dy) / (radius_y * radius_y) <= 1.0
            })
            .map(|coord| Rect::new(coord, Shape::from_square(1)))
            .collect()
    }

    /// Returns all 1×1 tiles within the `Rect` that are located on odd (x + y) sum positions.
    ///
    /// Useful for checkerboard or diagonal pattern logic.
    pub fn into_odds(&self) -> Vec<Rect> {
        self.iter()
            .filter(|coord| coord.x % 2 == 1 && coord.y % 2 == 1)
            .map(|coord| Rect::new(coord, Shape::from_square(1)))
            .collect()
    }

    /// Returns all 1×1 tiles within the `Rect` that are located on even (x + y) sum positions.
    ///
    /// Useful for checkerboard or diagonal pattern logic.
    pub fn into_evens(&self) -> Vec<Rect> {
        self.iter()
            .filter(|coord| coord.x % 2 == 0 && coord.y % 2 == 0)
            .map(|coord| Rect::new(coord, Shape::from_square(1)))
            .collect()
    }
}

impl Rect {
    /// Returns the top-left corner of the rectangle (equal to `origin`).
    pub fn top_left(&self) -> Coordinates {
        self.origin
    }

    /// Returns the top-right corner of the rectangle.
    pub fn top_right(&self) -> Coordinates {
        Coordinates {
            x: self.origin.x + self.shape.width.saturating_sub(1),
            y: self.origin.y,
        }
    }

    /// Returns the bottom-left corner of the rectangle.
    pub fn bottom_left(&self) -> Coordinates {
        Coordinates {
            x: self.origin.x,
            y: self.origin.y + self.shape.height.saturating_sub(1),
        }
    }

    /// Returns the bottom-right corner of the rectangle.
    pub fn bottom_right(&self) -> Coordinates {
        Coordinates {
            x: self.origin.x + self.shape.width.saturating_sub(1),
            y: self.origin.y + self.shape.height.saturating_sub(1),
        }
    }

    /// Returns the center point of the rectangle using integer division.
    ///
    /// For even dimensions, this returns the upper-left center tile.
    pub fn center(&self) -> Coordinates {
        Coordinates {
            x: self.origin.x + self.shape.width / 2,
            y: self.origin.y + self.shape.height / 2,
        }
    }

    /// Returns `true` if the given coordinates fall within the bounds of the rectangle.
    ///
    /// Bounds are inclusive at the top-left and exclusive at the bottom-right.
    pub fn contains(&self, pt: &Coordinates) -> bool {
        let x = pt.x;
        let y = pt.y;
        let ox = self.origin.x;
        let oy = self.origin.y;
        let w = self.shape.width;
        let h = self.shape.height;
        x >= ox && x < ox + w && y >= oy && y < oy + h
    }

    /// Returns an iterator over all coordinates contained in this rectangle.
    ///
    /// Iteration order is row-major (left to right, top to bottom).
    pub fn iter(&self) -> impl Iterator<Item = Coordinates> {
        let ox = self.origin.x;
        let oy = self.origin.y;
        let w = self.shape.width;
        let h = self.shape.height;
        (0..h).flat_map(move |dy| {
            (0..w).map(move |dx| Coordinates {
                x: ox + dx,
                y: oy + dy,
            })
        })
    }
}

impl Rect {
    /// Offsets the rectangle’s origin by the given delta.
    ///
    /// The result is clamped to non-negative values (0, 0 minimum).
    ///
    pub fn offset(&mut self, delta: Delta) {
        let new_x = self.origin.x as i32 + delta.dx;
        let new_y = self.origin.y as i32 + delta.dy;

        self.origin.x = new_x.max(0) as u32;
        self.origin.y = new_y.max(0) as u32;
    }

    /// Returns a new `Rect` translated by the given `Delta`, clamped at zero.
    pub fn translate(&self, delta: Delta) -> Self {
        let mut rect = *self;
        rect.offset(delta);
        rect
    }
}

impl fmt::Display for Rect {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Rect(origin: {}, {}, shape: {}×{})",
            self.origin.x, self.origin.y, self.shape.width, self.shape.height
        )
    }
}

impl Add<Delta> for Rect {
    type Output = Self;

    fn add(self, delta: Delta) -> Self {
        self.translate(delta)
    }
}

impl Sub<Delta> for Rect {
    type Output = Self;

    fn sub(self, delta: Delta) -> Self {
        self.translate(Delta {
            dx: -delta.dx,
            dy: -delta.dy,
        })
    }
}

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

    pub fn rect_6x6() -> Rect {
        Rect::new(
            Coordinates { x: 0, y: 0 },
            Shape {
                width: 6,
                height: 6,
            },
        )
    }

    #[test]
    pub fn is_bound_exclusive() {
        let rect = Rect::new(
            Coordinates { x: 2, y: 3 },
            Shape {
                width: 4,
                height: 5,
            },
        );

        assert!(rect.contains(&Coordinates { x: 2, y: 3 }));
        assert!(rect.contains(&Coordinates { x: 5, y: 7 }));
        assert!(!rect.contains(&Coordinates { x: 6, y: 3 }));
        assert!(!rect.contains(&Coordinates { x: 2, y: 8 }));
        assert!(!rect.contains(&Coordinates { x: 6, y: 8 }));
        assert!(!rect.contains(&Coordinates { x: 1, y: 3 }));
        assert!(!rect.contains(&Coordinates { x: 2, y: 2 }));
    }

    #[test]
    pub fn splits_into_many() {
        let rect = rect_6x6();
        let many = rect.into_many();
        assert_eq!(many.len(), 36);

        let expected_coords: Vec<_> = rect.iter().collect();
        for (i, tile_rect) in many.iter().enumerate() {
            assert_eq!(tile_rect.origin, expected_coords[i]);
            assert_eq!(tile_rect.shape, Shape::from_square(1));
        }
    }

    #[test]
    pub fn joins_into() {
        let rects = vec![
            Rect::new(Coordinates { x: 4, y: 5 }, Shape::from_square(1)),
            Rect::new(Coordinates { x: 5, y: 5 }, Shape::from_square(1)),
            Rect::new(Coordinates { x: 6, y: 5 }, Shape::from_square(1)),
            Rect::new(Coordinates { x: 4, y: 6 }, Shape::from_square(1)),
            Rect::new(Coordinates { x: 5, y: 6 }, Shape::from_square(1)),
            Rect::new(Coordinates { x: 6, y: 6 }, Shape::from_square(1)),
        ];

        let joined = Rect::from_many(rects);
        let expected = Rect::new(
            Coordinates { x: 4, y: 5 },
            Shape {
                width: 3,
                height: 2,
            },
        );

        assert_eq!(joined.unwrap(), expected);
    }

    #[test]
    pub fn splits_and_rejoins() {
        let rect = rect_6x6();
        let many = rect.into_many();
        let new_rect = Rect::from_many(many);
        assert_eq!(rect, new_rect.unwrap())
    }

    #[test]
    pub fn offsets() {
        let mut rect = Rect::new(
            Coordinates { x: 10, y: 10 },
            Shape {
                width: 4,
                height: 4,
            },
        );

        rect.offset(Delta { dx: 5, dy: 3 });
        assert_eq!(rect.origin, Coordinates { x: 15, y: 13 });

        rect.offset(Delta { dx: -10, dy: -10 });
        assert_eq!(rect.origin, Coordinates { x: 5, y: 3 });

        rect.offset(Delta { dx: -10, dy: -10 });
        assert_eq!(rect.origin, Coordinates { x: 0, y: 0 });
    }

    #[test]
    pub fn computes_center() {
        let rect = Rect::new(
            Coordinates { x: 2, y: 4 },
            Shape {
                width: 5,
                height: 3,
            },
        );

        assert_eq!(rect.center(), Coordinates { x: 4, y: 5 });

        let even_rect = Rect::new(
            Coordinates { x: 0, y: 0 },
            Shape {
                width: 4,
                height: 4,
            },
        );

        assert_eq!(even_rect.center(), Coordinates { x: 2, y: 2 });
    }

    #[test]
    pub fn computes_bounds() {
        let rect = Rect::new(
            Coordinates { x: 3, y: 7 },
            Shape {
                width: 5,
                height: 4,
            },
        );

        assert_eq!(rect.top_left(), Coordinates { x: 3, y: 7 });
        assert_eq!(rect.top_right(), Coordinates { x: 7, y: 7 });
        assert_eq!(rect.bottom_left(), Coordinates { x: 3, y: 10 });
        assert_eq!(rect.bottom_right(), Coordinates { x: 7, y: 10 });
    }

    #[test]
    pub fn iterates_all_points() {
        let rect = Rect::new(
            Coordinates { x: 1, y: 1 },
            Shape {
                width: 2,
                height: 2,
            },
        );

        let expected = vec![
            Coordinates { x: 1, y: 1 },
            Coordinates { x: 2, y: 1 },
            Coordinates { x: 1, y: 2 },
            Coordinates { x: 2, y: 2 },
        ];

        let actual: Vec<_> = rect.iter().collect();
        assert_eq!(actual, expected);
    }

    #[test]
    pub fn translate_produces_offset_rect() {
        let base = Rect::new(
            Coordinates { x: 5, y: 5 },
            Shape {
                width: 3,
                height: 3,
            },
        );

        let delta = Delta { dx: 2, dy: -1 };
        let translated = base.translate(delta);

        assert_eq!(
            translated.origin,
            Coordinates { x: 7, y: 4 },
            "translate should move origin correctly"
        );

        assert_eq!(translated.shape, base.shape, "shape should not change");
    }

    #[test]
    pub fn into_evens_returns_even_coordinates() {
        let rect = Rect::from_shape(Shape {
            width: 4,
            height: 4,
        });
        let evens = rect.into_evens();
        for tile in evens {
            assert_eq!(tile.origin.x % 2, 0);
            assert_eq!(tile.origin.y % 2, 0);
        }
    }

    #[test]
    pub fn into_odds_returns_odd_coordinates() {
        let rect = Rect::from_shape(Shape {
            width: 5,
            height: 5,
        });
        let odds = rect.into_odds();
        for tile in odds {
            assert_eq!(tile.origin.x % 2, 1);
            assert_eq!(tile.origin.y % 2, 1);
        }
    }
}