Skip to main content

three_rs/math/
vector4.rs

1//! Port of `three.js/src/math/Vector4.js`.
2
3use super::math_utils::{clamp, js_max, js_min};
4use super::vector3::js_round;
5use super::{Matrix4, Quaternion};
6
7/// three.js' `Vector4`: an ordered quadruplet `(x, y, z, w)`, used for points
8/// and directions in 4D space, homogeneous coordinates, and quaternion-like
9/// axis/angle packing.
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct Vector4 {
12    /// The x component.
13    pub x: f64,
14    /// The y component.
15    pub y: f64,
16    /// The z component.
17    pub z: f64,
18    /// The w component.
19    pub w: f64,
20}
21
22impl Default for Vector4 {
23    /// `new Vector4()` — `w` defaults to 1, not 0.
24    fn default() -> Self {
25        Self::new(0.0, 0.0, 0.0, 1.0)
26    }
27}
28
29impl Vector4 {
30    /// Constructs a new vector with the given components.
31    pub const fn new(x: f64, y: f64, z: f64, w: f64) -> Self {
32        Self { x, y, z, w }
33    }
34
35    /// `Vector4.width` — the alias `Vector4` exposes for `z`.
36    pub fn width(&self) -> f64 {
37        self.z
38    }
39
40    /// `Vector4.height` — the alias `Vector4` exposes for `w`.
41    pub fn height(&self) -> f64 {
42        self.w
43    }
44
45    /// Sets the vector components.
46    pub fn set(&mut self, x: f64, y: f64, z: f64, w: f64) -> &mut Self {
47        self.x = x;
48        self.y = y;
49        self.z = z;
50        self.w = w;
51        self
52    }
53
54    /// `Vector4.setScalar()`.
55    pub fn set_scalar(&mut self, scalar: f64) -> &mut Self {
56        self.set(scalar, scalar, scalar, scalar)
57    }
58
59    /// Sets the x component.
60    pub fn set_x(&mut self, x: f64) -> &mut Self {
61        self.x = x;
62        self
63    }
64
65    /// Sets the y component.
66    pub fn set_y(&mut self, y: f64) -> &mut Self {
67        self.y = y;
68        self
69    }
70
71    /// Sets the z component.
72    pub fn set_z(&mut self, z: f64) -> &mut Self {
73        self.z = z;
74        self
75    }
76
77    /// Sets the w component.
78    pub fn set_w(&mut self, w: f64) -> &mut Self {
79        self.w = w;
80        self
81    }
82
83    /// `Vector4.setComponent()`; panics where three.js throws.
84    pub fn set_component(&mut self, index: usize, value: f64) -> &mut Self {
85        match index {
86            0 => self.x = value,
87            1 => self.y = value,
88            2 => self.z = value,
89            3 => self.w = value,
90            _ => panic!("THREE.Vector4: index is out of range: {index}"),
91        }
92        self
93    }
94
95    /// `Vector4.getComponent()`.
96    pub fn get_component(&self, index: usize) -> f64 {
97        match index {
98            0 => self.x,
99            1 => self.y,
100            2 => self.z,
101            3 => self.w,
102            _ => panic!("THREE.Vector4: index is out of range: {index}"),
103        }
104    }
105
106    /// `Vector4.copy()`: unlike three.js, which defaults a missing `v.w` to 1
107    /// (it also accepts a `Vector3`), this always copies `v.w` since `v` is
108    /// statically a [`Vector4`].
109    pub fn copy(&mut self, v: &Self) -> &mut Self {
110        self.x = v.x;
111        self.y = v.y;
112        self.z = v.z;
113        self.w = v.w;
114        self
115    }
116
117    /// Adds the given vector to this one.
118    pub fn add(&mut self, v: &Self) -> &mut Self {
119        self.x += v.x;
120        self.y += v.y;
121        self.z += v.z;
122        self.w += v.w;
123        self
124    }
125
126    /// `Vector4.addScalar()`.
127    pub fn add_scalar(&mut self, s: f64) -> &mut Self {
128        self.x += s;
129        self.y += s;
130        self.z += s;
131        self.w += s;
132        self
133    }
134
135    /// Adds `a` and `b`, storing the result in this vector.
136    pub fn add_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
137        self.x = a.x + b.x;
138        self.y = a.y + b.y;
139        self.z = a.z + b.z;
140        self.w = a.w + b.w;
141        self
142    }
143
144    /// `Vector4.addScaledVector()`.
145    pub fn add_scaled_vector(&mut self, v: &Self, s: f64) -> &mut Self {
146        self.x += v.x * s;
147        self.y += v.y * s;
148        self.z += v.z * s;
149        self.w += v.w * s;
150        self
151    }
152
153    /// Subtracts the given vector from this one.
154    pub fn sub(&mut self, v: &Self) -> &mut Self {
155        self.x -= v.x;
156        self.y -= v.y;
157        self.z -= v.z;
158        self.w -= v.w;
159        self
160    }
161
162    /// `Vector4.subScalar()`.
163    pub fn sub_scalar(&mut self, s: f64) -> &mut Self {
164        self.x -= s;
165        self.y -= s;
166        self.z -= s;
167        self.w -= s;
168        self
169    }
170
171    /// Subtracts `b` from `a`, storing the result in this vector.
172    pub fn sub_vectors(&mut self, a: &Self, b: &Self) -> &mut Self {
173        self.x = a.x - b.x;
174        self.y = a.y - b.y;
175        self.z = a.z - b.z;
176        self.w = a.w - b.w;
177        self
178    }
179
180    /// Multiplies this vector by the given vector, component-wise.
181    pub fn multiply(&mut self, v: &Self) -> &mut Self {
182        self.x *= v.x;
183        self.y *= v.y;
184        self.z *= v.z;
185        self.w *= v.w;
186        self
187    }
188
189    /// Multiplies each component of this vector by the given scalar.
190    pub fn multiply_scalar(&mut self, scalar: f64) -> &mut Self {
191        self.x *= scalar;
192        self.y *= scalar;
193        self.z *= scalar;
194        self.w *= scalar;
195        self
196    }
197
198    /// `Vector4.applyMatrix4()`.
199    pub fn apply_matrix4(&mut self, m: &Matrix4) -> &mut Self {
200        let (x, y, z, w) = (self.x, self.y, self.z, self.w);
201        let e = &m.elements;
202
203        self.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
204        self.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
205        self.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
206        self.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
207
208        self
209    }
210
211    /// Divides this vector by the given vector, component-wise.
212    pub fn divide(&mut self, v: &Self) -> &mut Self {
213        self.x /= v.x;
214        self.y /= v.y;
215        self.z /= v.z;
216        self.w /= v.w;
217        self
218    }
219
220    /// `Vector4.divideScalar()`.
221    pub fn divide_scalar(&mut self, scalar: f64) -> &mut Self {
222        self.multiply_scalar(1.0 / scalar)
223    }
224
225    /// `Vector4.setAxisAngleFromQuaternion()`: `xyz` is the axis, `w` the angle.
226    pub fn set_axis_angle_from_quaternion(&mut self, q: &Quaternion) -> &mut Self {
227        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
228        // q is assumed to be normalized
229        self.w = 2.0 * q.w.acos();
230
231        let s = (1.0 - q.w * q.w).sqrt();
232
233        if s < 0.0001 {
234            self.x = 1.0;
235            self.y = 0.0;
236            self.z = 0.0;
237        } else {
238            self.x = q.x / s;
239            self.y = q.y / s;
240            self.z = q.z / s;
241        }
242
243        self
244    }
245
246    /// `Vector4.setAxisAngleFromRotationMatrix()`.
247    pub fn set_axis_angle_from_rotation_matrix(&mut self, m: &Matrix4) -> &mut Self {
248        // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
249        // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
250
251        let epsilon = 0.01; // margin to allow for rounding errors
252        let epsilon2 = 0.1; // margin to distinguish between 0 and 180 degrees
253
254        let te = &m.elements;
255        let (m11, m12, m13) = (te[0], te[4], te[8]);
256        let (m21, m22, m23) = (te[1], te[5], te[9]);
257        let (m31, m32, m33) = (te[2], te[6], te[10]);
258
259        if (m12 - m21).abs() < epsilon && (m13 - m31).abs() < epsilon && (m23 - m32).abs() < epsilon
260        {
261            // singularity found; first check for identity matrix which must have +1 for all terms in leading diagonal
262            if (m12 + m21).abs() < epsilon2
263                && (m13 + m31).abs() < epsilon2
264                && (m23 + m32).abs() < epsilon2
265                && (m11 + m22 + m33 - 3.0).abs() < epsilon2
266            {
267                // this singularity is identity matrix so angle = 0
268                self.set(1.0, 0.0, 0.0, 0.0);
269                return self; // zero angle, arbitrary axis
270            }
271
272            // otherwise this singularity is angle = 180
273            let angle = std::f64::consts::PI;
274
275            let xx = (m11 + 1.0) / 2.0;
276            let yy = (m22 + 1.0) / 2.0;
277            let zz = (m33 + 1.0) / 2.0;
278            let xy = (m12 + m21) / 4.0;
279            let xz = (m13 + m31) / 4.0;
280            let yz = (m23 + m32) / 4.0;
281
282            let (x, y, z);
283
284            // These `0.707106781` literals mirror three.js's `Quaternion.js` verbatim
285            // (an approximation of `FRAC_1_SQRT_2`, not the exact constant); keeping the
286            // same literal keeps this pixel-identical to three.js's output.
287            #[allow(clippy::approx_constant)]
288            if xx > yy && xx > zz {
289                if xx < epsilon {
290                    x = 0.0;
291                    y = 0.707106781;
292                    z = 0.707106781;
293                } else {
294                    x = xx.sqrt();
295                    y = xy / x;
296                    z = xz / x;
297                }
298            } else if yy > zz {
299                if yy < epsilon {
300                    x = 0.707106781;
301                    y = 0.0;
302                    z = 0.707106781;
303                } else {
304                    y = yy.sqrt();
305                    x = xy / y;
306                    z = yz / y;
307                }
308            } else if zz < epsilon {
309                x = 0.707106781;
310                y = 0.707106781;
311                z = 0.0;
312            } else {
313                z = zz.sqrt();
314                x = xz / z;
315                y = yz / z;
316            }
317
318            self.set(x, y, z, angle);
319            return self; // return 180 deg rotation
320        }
321
322        // as we have reached here there are no singularities so we can handle normally
323        let mut s =
324            ((m32 - m23) * (m32 - m23) + (m13 - m31) * (m13 - m31) + (m21 - m12) * (m21 - m12))
325                .sqrt(); // used to normalize
326
327        if s.abs() < 0.001 {
328            s = 1.0;
329        }
330
331        self.x = (m32 - m23) / s;
332        self.y = (m13 - m31) / s;
333        self.z = (m21 - m12) / s;
334        self.w = ((m11 + m22 + m33 - 1.0) / 2.0).acos();
335
336        self
337    }
338
339    /// `Vector4.setFromMatrixPosition()`.
340    pub fn set_from_matrix_position(&mut self, m: &Matrix4) -> &mut Self {
341        let e = &m.elements;
342        self.x = e[12];
343        self.y = e[13];
344        self.z = e[14];
345        self.w = e[15];
346        self
347    }
348
349    /// `Vector4.min()`.
350    pub fn min(&mut self, v: &Self) -> &mut Self {
351        self.x = js_min(self.x, v.x);
352        self.y = js_min(self.y, v.y);
353        self.z = js_min(self.z, v.z);
354        self.w = js_min(self.w, v.w);
355        self
356    }
357
358    /// `Vector4.max()`.
359    pub fn max(&mut self, v: &Self) -> &mut Self {
360        self.x = js_max(self.x, v.x);
361        self.y = js_max(self.y, v.y);
362        self.z = js_max(self.z, v.z);
363        self.w = js_max(self.w, v.w);
364        self
365    }
366
367    /// `Vector4.clamp()`.
368    pub fn clamp(&mut self, min: &Self, max: &Self) -> &mut Self {
369        self.x = clamp(self.x, min.x, max.x);
370        self.y = clamp(self.y, min.y, max.y);
371        self.z = clamp(self.z, min.z, max.z);
372        self.w = clamp(self.w, min.w, max.w);
373        self
374    }
375
376    /// `Vector4.clampScalar()`.
377    pub fn clamp_scalar(&mut self, min_val: f64, max_val: f64) -> &mut Self {
378        self.x = clamp(self.x, min_val, max_val);
379        self.y = clamp(self.y, min_val, max_val);
380        self.z = clamp(self.z, min_val, max_val);
381        self.w = clamp(self.w, min_val, max_val);
382        self
383    }
384
385    /// `Vector4.clampLength()`.
386    pub fn clamp_length(&mut self, min: f64, max: f64) -> &mut Self {
387        let length = self.length();
388        self.divide_scalar(if length == 0.0 { 1.0 } else { length })
389            .multiply_scalar(clamp(length, min, max))
390    }
391
392    /// `Vector4.floor()`.
393    pub fn floor(&mut self) -> &mut Self {
394        self.x = self.x.floor();
395        self.y = self.y.floor();
396        self.z = self.z.floor();
397        self.w = self.w.floor();
398        self
399    }
400
401    /// `Vector4.ceil()`.
402    pub fn ceil(&mut self) -> &mut Self {
403        self.x = self.x.ceil();
404        self.y = self.y.ceil();
405        self.z = self.z.ceil();
406        self.w = self.w.ceil();
407        self
408    }
409
410    /// `Vector4.round()` — `Math.round`, which rounds half *up* (toward
411    /// +Infinity), not half away from zero the way Rust's `f64::round` does.
412    pub fn round(&mut self) -> &mut Self {
413        self.x = js_round(self.x);
414        self.y = js_round(self.y);
415        self.z = js_round(self.z);
416        self.w = js_round(self.w);
417        self
418    }
419
420    /// `Vector4.roundToZero()` — `Math.trunc`.
421    pub fn round_to_zero(&mut self) -> &mut Self {
422        self.x = self.x.trunc();
423        self.y = self.y.trunc();
424        self.z = self.z.trunc();
425        self.w = self.w.trunc();
426        self
427    }
428
429    /// `Vector4.negate()`.
430    pub fn negate(&mut self) -> &mut Self {
431        self.x = -self.x;
432        self.y = -self.y;
433        self.z = -self.z;
434        self.w = -self.w;
435        self
436    }
437
438    /// `Vector4.dot()`.
439    pub fn dot(&self, v: &Self) -> f64 {
440        self.x * v.x + self.y * v.y + self.z * v.z + self.w * v.w
441    }
442
443    /// `Vector4.lengthSq()`.
444    pub fn length_sq(&self) -> f64 {
445        self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w
446    }
447
448    /// `Vector4.length()`: the Euclidean length from `(0, 0, 0, 0)`.
449    pub fn length(&self) -> f64 {
450        (self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w).sqrt()
451    }
452
453    /// `Vector4.manhattanLength()`.
454    pub fn manhattan_length(&self) -> f64 {
455        self.x.abs() + self.y.abs() + self.z.abs() + self.w.abs()
456    }
457
458    /// `Vector4.normalize()`: divides by the length, or by 1 when the length
459    /// is 0.
460    pub fn normalize(&mut self) -> &mut Self {
461        let l = self.length();
462        self.divide_scalar(if l == 0.0 { 1.0 } else { l })
463    }
464
465    /// `Vector4.setLength()`.
466    pub fn set_length(&mut self, length: f64) -> &mut Self {
467        self.normalize().multiply_scalar(length)
468    }
469
470    /// `Vector4.lerp()`.
471    pub fn lerp(&mut self, v: &Self, alpha: f64) -> &mut Self {
472        self.x += (v.x - self.x) * alpha;
473        self.y += (v.y - self.y) * alpha;
474        self.z += (v.z - self.z) * alpha;
475        self.w += (v.w - self.w) * alpha;
476        self
477    }
478
479    /// `Vector4.lerpVectors()`.
480    pub fn lerp_vectors(&mut self, v1: &Self, v2: &Self, alpha: f64) -> &mut Self {
481        self.x = v1.x + (v2.x - v1.x) * alpha;
482        self.y = v1.y + (v2.y - v1.y) * alpha;
483        self.z = v1.z + (v2.z - v1.z) * alpha;
484        self.w = v1.w + (v2.w - v1.w) * alpha;
485        self
486    }
487
488    /// `Vector4.equals()`.
489    pub fn equals(&self, v: &Self) -> bool {
490        v.x == self.x && v.y == self.y && v.z == self.z && v.w == self.w
491    }
492
493    /// `Vector4.fromArray()`.
494    pub fn from_array(&mut self, array: &[f64], offset: usize) -> &mut Self {
495        self.x = array[offset];
496        self.y = array[offset + 1];
497        self.z = array[offset + 2];
498        self.w = array[offset + 3];
499        self
500    }
501
502    /// `Vector4.toArray()`.
503    pub fn to_array(&self) -> [f64; 4] {
504        [self.x, self.y, self.z, self.w]
505    }
506}