Skip to main content

three_rs/math/
vector2.rs

1//! Port of `three.js/src/math/Vector2.js`.
2
3use super::math_utils::{clamp, js_max, js_min};
4use super::vector3::js_round;
5use super::Matrix3;
6
7/// three.js' `Vector2`: an ordered pair of numbers, used for 2D points,
8/// directions, and any other pair of related values.
9#[derive(Clone, Copy, Debug, Default, PartialEq)]
10pub struct Vector2 {
11    /// The x component.
12    pub x: f64,
13    /// The y component.
14    pub y: f64,
15}
16
17impl Vector2 {
18    /// Constructs a new vector with the given components.
19    pub const fn new(x: f64, y: f64) -> Self {
20        Self { x, y }
21    }
22
23    /// The zero vector.
24    pub const ZERO: Self = Self::new(0.0, 0.0);
25
26    /// `Vector2.width` — the alias `Vector2` exposes for `x`.
27    pub fn width(&self) -> f64 {
28        self.x
29    }
30
31    /// `Vector2.height` — the alias `Vector2` exposes for `y`.
32    pub fn height(&self) -> f64 {
33        self.y
34    }
35
36    /// Sets the vector's components.
37    pub fn set(&mut self, x: f64, y: f64) -> &mut Self {
38        self.x = x;
39        self.y = y;
40        self
41    }
42
43    /// `Vector2.setScalar()`: sets both components to `scalar`.
44    pub fn set_scalar(&mut self, scalar: f64) -> &mut Self {
45        self.set(scalar, scalar)
46    }
47
48    /// `Vector2.setX()`.
49    pub fn set_x(&mut self, x: f64) -> &mut Self {
50        self.x = x;
51        self
52    }
53
54    /// `Vector2.setY()`.
55    pub fn set_y(&mut self, y: f64) -> &mut Self {
56        self.y = y;
57        self
58    }
59
60    /// `Vector2.setComponent()`: sets `x` (index 0) or `y` (index 1). Panics
61    /// where three.js throws.
62    pub fn set_component(&mut self, index: usize, value: f64) -> &mut Self {
63        match index {
64            0 => self.x = value,
65            1 => self.y = value,
66            _ => panic!("THREE.Vector2: index is out of range: {index}"),
67        }
68        self
69    }
70
71    /// `Vector2.getComponent()`: `x` (index 0) or `y` (index 1). Panics where
72    /// three.js throws.
73    pub fn get_component(&self, index: usize) -> f64 {
74        match index {
75            0 => self.x,
76            1 => self.y,
77            _ => panic!("THREE.Vector2: index is out of range: {index}"),
78        }
79    }
80
81    /// Copies the components of `v` into this vector.
82    pub fn copy(&mut self, v: &Self) -> &mut Self {
83        self.x = v.x;
84        self.y = v.y;
85        self
86    }
87
88    /// Adds `v` to this vector.
89    pub fn add(&mut self, v: &Self) -> &mut Self {
90        self.x += v.x;
91        self.y += v.y;
92        self
93    }
94
95    /// `Vector2.addScalar()`: adds `s` to both components.
96    pub fn add_scalar(&mut self, s: f64) -> &mut Self {
97        self.x += s;
98        self.y += s;
99        self
100    }
101
102    /// `Vector2.addVectors()`: sets this vector to `a + b`.
103    pub fn add_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
104        self.x = a.x + b.x;
105        self.y = a.y + b.y;
106        self
107    }
108
109    /// `Vector2.addScaledVector()`: adds `v * s` to this vector.
110    pub fn add_scaled_vector(&mut self, v: &Self, s: f64) -> &mut Self {
111        self.x += v.x * s;
112        self.y += v.y * s;
113        self
114    }
115
116    /// Subtracts `v` from this vector.
117    pub fn sub(&mut self, v: &Self) -> &mut Self {
118        self.x -= v.x;
119        self.y -= v.y;
120        self
121    }
122
123    /// `Vector2.subScalar()`: subtracts `s` from both components.
124    pub fn sub_scalar(&mut self, s: f64) -> &mut Self {
125        self.x -= s;
126        self.y -= s;
127        self
128    }
129
130    /// `Vector2.subVectors()`: sets this vector to `a - b`.
131    pub fn sub_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
132        self.x = a.x - b.x;
133        self.y = a.y - b.y;
134        self
135    }
136
137    /// Multiplies this vector by `v`, component-wise.
138    pub fn multiply(&mut self, v: &Self) -> &mut Self {
139        self.x *= v.x;
140        self.y *= v.y;
141        self
142    }
143
144    /// `Vector2.multiplyScalar()`.
145    pub fn multiply_scalar(&mut self, scalar: f64) -> &mut Self {
146        self.x *= scalar;
147        self.y *= scalar;
148        self
149    }
150
151    /// Divides this vector by `v`, component-wise.
152    pub fn divide(&mut self, v: &Self) -> &mut Self {
153        self.x /= v.x;
154        self.y /= v.y;
155        self
156    }
157
158    /// `Vector2.divideScalar()`.
159    pub fn divide_scalar(&mut self, scalar: f64) -> &mut Self {
160        self.multiply_scalar(1.0 / scalar)
161    }
162
163    /// `Vector2.applyMatrix3()`.
164    pub fn apply_matrix3(&mut self, m: &Matrix3) -> &mut Self {
165        let (x, y) = (self.x, self.y);
166        let e = &m.elements;
167
168        self.x = e[0] * x + e[3] * y + e[6];
169        self.y = e[1] * x + e[4] * y + e[7];
170
171        self
172    }
173
174    /// Replaces each component with the smaller of itself and the matching
175    /// component of `v`.
176    pub fn min(&mut self, v: &Self) -> &mut Self {
177        self.x = js_min(self.x, v.x);
178        self.y = js_min(self.y, v.y);
179        self
180    }
181
182    /// Replaces each component with the larger of itself and the matching
183    /// component of `v`.
184    pub fn max(&mut self, v: &Self) -> &mut Self {
185        self.x = js_max(self.x, v.x);
186        self.y = js_max(self.y, v.y);
187        self
188    }
189
190    /// Clamps each component between the matching components of `min` and
191    /// `max`.
192    pub fn clamp(&mut self, min: &Self, max: &Self) -> &mut Self {
193        self.x = clamp(self.x, min.x, max.x);
194        self.y = clamp(self.y, min.y, max.y);
195        self
196    }
197
198    /// `Vector2.clampScalar()`: clamps each component between `min_val` and
199    /// `max_val`.
200    pub fn clamp_scalar(&mut self, min_val: f64, max_val: f64) -> &mut Self {
201        self.x = clamp(self.x, min_val, max_val);
202        self.y = clamp(self.y, min_val, max_val);
203        self
204    }
205
206    /// `Vector2.clampLength()`: clamps this vector's length between `min` and
207    /// `max`, preserving its direction.
208    pub fn clamp_length(&mut self, min: f64, max: f64) -> &mut Self {
209        let length = self.length();
210        self.divide_scalar(if length == 0.0 { 1.0 } else { length })
211            .multiply_scalar(clamp(length, min, max))
212    }
213
214    /// Rounds each component down to the nearest integer.
215    pub fn floor(&mut self) -> &mut Self {
216        self.x = self.x.floor();
217        self.y = self.y.floor();
218        self
219    }
220
221    /// Rounds each component up to the nearest integer.
222    pub fn ceil(&mut self) -> &mut Self {
223        self.x = self.x.ceil();
224        self.y = self.y.ceil();
225        self
226    }
227
228    /// `Vector2.round()` — `Math.round`, which rounds half *up* (toward
229    /// +Infinity), not half away from zero the way Rust's `f64::round` does.
230    pub fn round(&mut self) -> &mut Self {
231        self.x = js_round(self.x);
232        self.y = js_round(self.y);
233        self
234    }
235
236    /// `Vector2.roundToZero()` — `Math.trunc`.
237    pub fn round_to_zero(&mut self) -> &mut Self {
238        self.x = self.x.trunc();
239        self.y = self.y.trunc();
240        self
241    }
242
243    /// Negates both components.
244    pub fn negate(&mut self) -> &mut Self {
245        self.x = -self.x;
246        self.y = -self.y;
247        self
248    }
249
250    /// The dot product of this vector and `v`.
251    pub fn dot(&self, v: &Self) -> f64 {
252        self.x * v.x + self.y * v.y
253    }
254
255    /// `Vector2.cross()` — the z component of the 3D cross product.
256    pub fn cross(&self, v: &Self) -> f64 {
257        self.x * v.y - self.y * v.x
258    }
259
260    /// `Vector2.lengthSq()`: the squared Euclidean length, cheaper than
261    /// [`Vector2::length`] when only comparing lengths.
262    pub fn length_sq(&self) -> f64 {
263        self.x * self.x + self.y * self.y
264    }
265
266    /// The Euclidean length (distance from `(0, 0)` to `(x, y)`).
267    pub fn length(&self) -> f64 {
268        (self.x * self.x + self.y * self.y).sqrt()
269    }
270
271    /// `Vector2.manhattanLength()`.
272    pub fn manhattan_length(&self) -> f64 {
273        self.x.abs() + self.y.abs()
274    }
275
276    /// Scales this vector to unit length, or to `(0, 0)` if its length is 0.
277    pub fn normalize(&mut self) -> &mut Self {
278        let l = self.length();
279        self.divide_scalar(if l == 0.0 { 1.0 } else { l })
280    }
281
282    /// `Vector2.angle()` — in the range `[0, 2pi)`, measured counter-clockwise
283    /// from the positive x axis.
284    pub fn angle(&self) -> f64 {
285        (-self.y).atan2(-self.x) + std::f64::consts::PI
286    }
287
288    /// `Vector2.angleTo()`: the angle in radians between this vector and `v`.
289    pub fn angle_to(&self, v: &Self) -> f64 {
290        let denominator = (self.length_sq() * v.length_sq()).sqrt();
291
292        if denominator == 0.0 {
293            return std::f64::consts::PI / 2.0;
294        }
295
296        let theta = self.dot(v) / denominator;
297
298        clamp(theta, -1.0, 1.0).acos()
299    }
300
301    /// The distance from this vector to `v`.
302    pub fn distance_to(&self, v: &Self) -> f64 {
303        self.distance_to_squared(v).sqrt()
304    }
305
306    /// `Vector2.distanceToSquared()`: cheaper than [`Vector2::distance_to`]
307    /// when only comparing distances.
308    pub fn distance_to_squared(&self, v: &Self) -> f64 {
309        let (dx, dy) = (self.x - v.x, self.y - v.y);
310        dx * dx + dy * dy
311    }
312
313    /// `Vector2.manhattanDistanceTo()`.
314    pub fn manhattan_distance_to(&self, v: &Self) -> f64 {
315        (self.x - v.x).abs() + (self.y - v.y).abs()
316    }
317
318    /// `Vector2.setLength()`: rescales this vector to the given length,
319    /// preserving its direction.
320    pub fn set_length(&mut self, length: f64) -> &mut Self {
321        self.normalize().multiply_scalar(length)
322    }
323
324    /// Linearly interpolates from this vector toward `v`, where `alpha` is
325    /// the distance along the line (`0` stays at this vector, `1` reaches
326    /// `v`).
327    pub fn lerp(&mut self, v: &Self, alpha: f64) -> &mut Self {
328        self.x += (v.x - self.x) * alpha;
329        self.y += (v.y - self.y) * alpha;
330        self
331    }
332
333    /// `Vector2.lerpVectors()`: sets this vector to the linear interpolation
334    /// from `v1` to `v2` at `alpha`.
335    pub fn lerp_vectors(&mut self, v1: &Self, v2: &Self, alpha: f64) -> &mut Self {
336        self.x = v1.x + (v2.x - v1.x) * alpha;
337        self.y = v1.y + (v2.y - v1.y) * alpha;
338        self
339    }
340
341    /// Whether this vector's components equal `v`'s.
342    pub fn equals(&self, v: &Self) -> bool {
343        v.x == self.x && v.y == self.y
344    }
345
346    /// `Vector2.fromArray()`: reads `x` from `array[offset]` and `y` from
347    /// `array[offset + 1]`.
348    pub fn from_array(&mut self, array: &[f64], offset: usize) -> &mut Self {
349        self.x = array[offset];
350        self.y = array[offset + 1];
351        self
352    }
353
354    /// `Vector2.toArray()`: `[x, y]`.
355    pub fn to_array(&self) -> [f64; 2] {
356        [self.x, self.y]
357    }
358
359    /// `Vector2.rotateAround()`.
360    pub fn rotate_around(&mut self, center: &Self, angle: f64) -> &mut Self {
361        let (c, s) = (angle.cos(), angle.sin());
362
363        let x = self.x - center.x;
364        let y = self.y - center.y;
365
366        self.x = x * c - y * s + center.x;
367        self.y = x * s + y * c + center.y;
368
369        self
370    }
371}