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
use glam::{IVec2, Vec2};
use crate::{GridPoint, Size2d};
#[derive(Eq, PartialEq, Clone, Copy)]
pub enum Pivot {
TopLeft,
TopRight,
Center,
BottomLeft,
BottomRight,
}
impl Pivot {
pub fn axis(&self) -> IVec2 {
match self {
Pivot::TopLeft => IVec2::new(1, -1),
Pivot::TopRight => IVec2::new(-1, -1),
Pivot::Center => IVec2::new(1, 1),
Pivot::BottomLeft => IVec2::new(1, 1),
Pivot::BottomRight => IVec2::new(-1, 1),
}
}
#[inline]
pub fn pivot_aligned_point(&self, point: impl GridPoint, size: impl Size2d) -> IVec2 {
let point = point.as_ivec2();
let align_offset = size.as_ivec2().as_vec2() - Vec2::ONE;
let align_offset = (align_offset * Vec2::from(*self)).as_ivec2();
point * self.axis() + align_offset
}
}
impl From<Pivot> for Vec2 {
fn from(p: Pivot) -> Self {
match p {
Pivot::TopLeft => Vec2::new(0.0, 1.0),
Pivot::TopRight => Vec2::new(1.0, 1.0),
Pivot::Center => Vec2::new(0.5, 0.5),
Pivot::BottomLeft => Vec2::new(0.0, 0.0),
Pivot::BottomRight => Vec2::new(1.0, 0.0),
}
}
}
#[derive(Clone, Copy)]
pub struct PivotedPoint {
pub point: IVec2,
pub pivot: Pivot,
}
impl PivotedPoint {
pub fn pivot_point(&self) -> IVec2 {
self.point
}
}
impl GridPoint for PivotedPoint {
#[inline]
fn x(&self) -> i32 {
self.point.x
}
#[inline]
fn y(&self) -> i32 {
self.point.y
}
#[inline]
fn aligned(&self, size: impl Size2d) -> IVec2 {
self.pivot.pivot_aligned_point(self.point, size)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pivot_point() {
let p = [0, 0].pivot(Pivot::TopRight);
assert_eq!([9, 9], p.aligned([10, 10]).to_array());
let p = [3, 3].pivot(Pivot::TopLeft);
assert_eq!([3, 6], p.aligned([10, 10]).to_array());
}
}