File size: 1,859 Bytes
ec3121c
 
 
5f32ba4
4e1da8c
 
 
 
 
 
 
 
 
 
 
 
3b7903d
4e1da8c
 
 
 
 
 
ec3121c
cc654e9
 
 
 
ec3121c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e1da8c
5f32ba4
 
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
import { Matrix3 } from "./Matrix3";
import type { Vector3 } from "./Vector3";

class Quaternion {
    x: number;
    y: number;
    z: number;
    w: number;

    constructor(x: number = 0, y: number = 0, z: number = 0, w: number = 1) {
        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;
    }

    set(x: number, y: number, z: number, w: number): Quaternion {
        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;

        return this;
    }    

    flat(): number[] {
        return [this.x, this.y, this.z, this.w];
    }

    clone(): Quaternion {
        return new Quaternion(this.x, this.y, this.z, this.w);
    }

    toRotationMatrix(): Matrix3 {
        const xx = this.x * this.x;
        const xy = this.x * this.y;
        const xz = this.x * this.z;
        const xw = this.x * this.w;
        const yy = this.y * this.y;
        const yz = this.y * this.z;
        const yw = this.y * this.w;
        const zz = this.z * this.z;
        const zw = this.z * this.w;

        const m = new Matrix3();
        // prettier-ignore
        m.set(
            1 - 2 * (yy + zz), 2 * (xy - zw), 2 * (xz + yw),
            2 * (xy + zw), 1 - 2 * (xx + zz), 2 * (yz - xw),
            2 * (xz - yw), 2 * (yz + xw), 1 - 2 * (xx + yy)
        )

        return m;
    }

    static FromEuler(m: Vector3) {
        const cy = Math.cos(m.y / 2);
        const sy = Math.sin(m.y / 2);
        const cp = Math.cos(m.x / 2);
        const sp = Math.sin(m.x / 2);
        const cr = Math.cos(m.z / 2);
        const sr = Math.sin(m.z / 2);

        const w = cy * cp * cr + sy * sp * sr;
        const x = cy * cp * sr - sy * sp * cr;
        const y = sy * cp * sr + cy * sp * cr;
        const z = sy * cp * cr - cy * sp * sr;

        return new Quaternion(x, y, z, w);
    }
}

export { Quaternion };