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
//! Create and use 2D vectors
//!
//! # Example
//!
//! ```
//! use vector2::Vector2;
//!
//! // Create a Vector2
//! let vector2 = Vector2::new(1.0, 0.5);
//!
//! // (1.0, 0.0)
//! let other = Vector2::RIGHT;
//!
//! // Add two Vector2s
//! let added = vector2 + other;
//!
//! assert_eq!(added.x, 2.0);
//! assert_eq!(added.y, 0.5);

use std::fmt;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Vector2 {
    /// X component of the vector.
    pub x: f64,

    /// Y component of the vector.
    pub y: f64,
}

impl Vector2 {
    /// Shorthand for writing `Vector2::new(0.0, -1.0)`.
    pub const DOWN: Self = Self { x: 0.0, y: -1.0 };

    /// Shorthand for writing `Vector2::new(-1.0, 0.0)`.
    pub const LEFT: Self = Self { x: -1.0, y: 0.0 };

    /// Shorthand for writing `Vector2::new(f64::NEG_INFINITY, f64::NEG_INFINITY)`.
    pub const NEGATIVE_INFINITY: Self = Self {
        x: f64::NEG_INFINITY,
        y: f64::NEG_INFINITY,
    };

    /// Shorthand for writing `Vector2::new(1.0, 1.0)`.
    pub const ONE: Self = Self { x: 1.0, y: 1.0 };

    /// Shorthand for writing `Vector2::new(f64::INFINITY, f64::INFINITY)`.
    pub const POSITIVE_INFINITY: Self = Self {
        x: f64::INFINITY,
        y: f64::INFINITY,
    };

    /// Shorthand for writing `Vector2::new(1.0, 0.0)`.
    pub const RIGHT: Self = Self { x: 1.0, y: 0.0 };

    /// Shorthand for writing `Vector2::new(0.0, 1.0)`.
    pub const UP: Self = Self { x: 0.0, y: 1.0 };

    /// Shorthand for writing `Vector2::new(0.0, 0.0)`.
    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };

    /// Constructs a new vector with given x, y components.
    pub fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }

    /// Returns the length of this vector.
    pub fn magnitude(&self) -> f64 {
        f64::sqrt((self.x * self.x) + (self.y * self.y))
    }

    /// Returns the squared length of this vector.
    pub fn sqr_magnitude(&self) -> f64 {
        (self.x * self.x) + (self.y * self.y)
    }

    /// Returns this vector with a magnitude of 1.
    pub fn normalized(&self) -> Self {
        let mut v = Self::new(self.x, self.y);
        v.normalize();
        v
    }

    /// Makes this vector have a magnitude of 1.
    pub fn normalize(&mut self) {
        let magnitude = self.magnitude();
        if magnitude > Self::K_EPSILON {
            *self = *self / magnitude;
        } else {
            *self = Self::ZERO;
        }
    }

    /// Set x and y components of an existing Vector2.
    pub fn set(&mut self, new_x: f64, new_y: f64) {
        self.x = new_x;
        self.y = new_y;
    }

    /// Gets the unsigned angle in degrees between from and to.
    pub fn angle(from: Self, to: Self) -> f64 {
        let denominator = f64::sqrt(from.sqr_magnitude() * to.sqr_magnitude());
        if denominator < Self::K_EPSILON_NORMAL_SQRT {
            0.0
        } else {
            let dot = f64::clamp(Self::dot(from, to), -1.0, 1.0);
            f64::to_degrees(f64::acos(dot))
        }
    }

    /// Returns a copy of vector with its magnitude clamped to max_length.
    pub fn clamp_magnitude(vector: Self, max_length: f64) -> Self {
        let sqr_magnitude = vector.sqr_magnitude();
        if sqr_magnitude > max_length * max_length {
            let mag = f64::sqrt(sqr_magnitude);

            let normalized_x = vector.x / mag;
            let normalized_y = vector.y / mag;
            Self::new(normalized_x * max_length, normalized_y * max_length)
        } else {
            vector
        }
    }

    /// Returns the distance between a and b.
    pub fn distance(a: Self, b: Self) -> f64 {
        let diff_x = a.x - b.x;
        let diff_y = a.y - b.y;
        f64::sqrt((diff_x * diff_x) + (diff_y * diff_y))
    }

    /// Dot product of two vectors.
    pub fn dot(lhs: Self, rhs: Self) -> f64 {
        (lhs.x * rhs.x) + (lhs.y * rhs.y)
    }

    /// Linearly interpolates between vectors a and b by t.
    pub fn lerp(a: Self, b: Self, mut t: f64) -> Self {
        t = f64::clamp(t, 0.0, 1.0);
        Self::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
    }

    /// Linearly interpolates between vectors a and b by t.
    pub fn lerp_unclamped(a: Self, b: Self, t: f64) -> Self {
        Self::new(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t)
    }

    /// Returns a vector that is made from the largest components of two vectors.
    pub fn max(lhs: Self, rhs: Self) -> Self {
        Self::new(f64::max(lhs.x, rhs.x), f64::max(lhs.y, rhs.y))
    }

    /// Returns a vector that is made from the smallest components of two vectors.
    pub fn min(lhs: Self, rhs: Self) -> Self {
        Self::new(f64::min(lhs.x, rhs.x), f64::min(lhs.y, rhs.y))
    }

    /// Moves a point current towards target.
    pub fn move_towards(current: Self, target: Self, max_distance_delta: f64) -> Self {
        let to_vector_x = target.x - current.x;
        let to_vector_y = target.y - current.y;

        let sq_dist = (to_vector_x * to_vector_x) + (to_vector_y * to_vector_y);

        if sq_dist == 0.0
            || (max_distance_delta >= 0.0 && sq_dist <= max_distance_delta * max_distance_delta)
        {
            target
        } else {
            let dist = f64::sqrt(sq_dist);

            Self::new(
                current.x + ((to_vector_x / dist) * max_distance_delta),
                current.y + ((to_vector_y / dist) * max_distance_delta),
            )
        }
    }

    /// Returns the 2D vector perpendicular to this 2D vector. The result is always rotated 90-degrees in a counter-clockwise direction for a 2D coordinate system where the positive Y axis goes up.
    pub fn perpendicular(in_direction: Self) -> Self {
        Self::new(-in_direction.y, in_direction.x)
    }

    /// Reflects a vector off the vector defined by a normal.
    pub fn reflect(in_direction: Self, in_normal: Self) -> Self {
        let factor = -2.0 * Self::dot(in_normal, in_direction);
        Self::new(
            (factor * in_normal.x) + in_direction.x,
            (factor * in_normal.y) + in_direction.y,
        )
    }

    /// Multiplies two vectors component-wise.
    pub fn scale(a: Self, b: Self) -> Self {
        Self::new(a.x * b.x, a.y * b.y)
    }

    /// Gets the signed angle in degrees between from and to.
    pub fn signed_angle(from: Self, to: Self) -> f64 {
        let unsigned_angle = Self::angle(from, to);
        let sign = f64::signum((from.x * to.y) - (from.y * to.x));
        unsigned_angle * sign
    }

    const K_EPSILON: f64 = 0.00001;
    const K_EPSILON_NORMAL_SQRT: f64 = 1e-15;
}

impl From<(f64, f64)> for Vector2 {
    fn from(value: (f64, f64)) -> Self {
        Self {
            x: value.0,
            y: value.1,
        }
    }
}

impl From<Vector2> for (f64, f64) {
    fn from(value: Vector2) -> (f64, f64) {
        (value.x, value.y)
    }
}

impl Sub for Vector2 {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        Self {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl SubAssign for Vector2 {
    fn sub_assign(&mut self, other: Self) {
        *self = Self {
            x: self.x - other.x,
            y: self.y - other.y,
        }
    }
}

impl Mul<f64> for Vector2 {
    type Output = Self;

    fn mul(self, other: f64) -> Self {
        Self {
            x: self.x * other,
            y: self.y * other,
        }
    }
}

impl Mul<Vector2> for f64 {
    type Output = Vector2;

    fn mul(self, other: Vector2) -> Vector2 {
        other * self
    }
}

impl MulAssign<f64> for Vector2 {
    fn mul_assign(&mut self, other: f64) {
        *self = Self {
            x: self.x * other,
            y: self.y * other,
        }
    }
}

impl Div<f64> for Vector2 {
    type Output = Self;

    fn div(self, other: f64) -> Self {
        Self {
            x: self.x / other,
            y: self.y / other,
        }
    }
}

impl DivAssign<f64> for Vector2 {
    fn div_assign(&mut self, other: f64) {
        *self = Self {
            x: self.x / other,
            y: self.y / other,
        }
    }
}

impl Add for Vector2 {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

impl AddAssign for Vector2 {
    fn add_assign(&mut self, other: Self) {
        *self = Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

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

impl Neg for Vector2 {
    type Output = Self;

    fn neg(self) -> Self {
        Self {
            x: -self.x,
            y: -self.y,
        }
    }
}