all files / src/ quaternion.js

18.64% Statements 11/59
43.75% Branches 7/16
50% Functions 2/4
18.64% Lines 11/59
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                                                                                                                                                                             
class Quaternion {
  constructor (x, y, z, w) {
    this.x = x || 0;
    this.y = y || 0;
    this.z = z || 0;
    this.w = (w !== undefined) ? w : 1;
  }
 
  setFromAxisAngle (axis, angle) {
    let halfAngle = angle / 2,
      s = Math.sin(halfAngle);
 
    this.x = axis.x * s;
    this.y = axis.y * s;
    this.z = axis.z * s;
    this.w = Math.cos(halfAngle);
 
    return this;
  }
 
  multiplyQuaternions (a, b) {
    let qax = a.x,
      qay = a.y,
      qaz = a.z,
      qaw = a.w;
    let qbx = b.x,
      qby = b.y,
      qbz = b.z,
      qbw = b.w;
 
    this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
    this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
    this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
    this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
 
    return this;
  }
 
  setFromRotationMatrix (m) {
    let te = m.elements,
 
      m11 = te[0],
      m12 = te[4],
      m13 = te[8],
      m21 = te[1],
      m22 = te[5],
      m23 = te[9],
      m31 = te[2],
      m32 = te[6],
      m33 = te[10],
 
      trace = m11 + m22 + m33,
      s;
 
    if (trace > 0) {
 
      s = 0.5 / Math.sqrt(trace + 1.0);
 
      this.w = 0.25 / s;
      this.x = (m32 - m23) * s;
      this.y = (m13 - m31) * s;
      this.z = (m21 - m12) * s;
 
    } else if (m11 > m22 && m11 > m33) {
 
      s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
 
      this.w = (m32 - m23) / s;
      this.x = 0.25 * s;
      this.y = (m12 + m21) / s;
      this.z = (m13 + m31) / s;
 
    } else if (m22 > m33) {
 
      s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
 
      this.w = (m13 - m31) / s;
      this.x = (m12 + m21) / s;
      this.y = 0.25 * s;
      this.z = (m23 + m32) / s;
 
    } else {
 
      s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
 
      this.w = (m21 - m12) / s;
      this.x = (m13 + m31) / s;
      this.y = (m23 + m32) / s;
      this.z = 0.25 * s;
 
    }
 
    return this;
  }
}
 
export default Quaternion;