modeling/src/maths/vec3/angle.js

  1. const dot = require('./dot')
  2. /**
  3. * Calculate the angle between two vectors.
  4. *
  5. * @param {vec3} a - first operand
  6. * @param {vec3} b - second operand
  7. * @returns {Number} angle (radians)
  8. * @alias module:modeling/maths/vec3.angle
  9. */
  10. const angle = (a, b) => {
  11. const ax = a[0]
  12. const ay = a[1]
  13. const az = a[2]
  14. const bx = b[0]
  15. const by = b[1]
  16. const bz = b[2]
  17. const mag1 = Math.sqrt(ax * ax + ay * ay + az * az)
  18. const mag2 = Math.sqrt(bx * bx + by * by + bz * bz)
  19. const mag = mag1 * mag2
  20. const cosine = mag && dot(a, b) / mag
  21. return Math.acos(Math.min(Math.max(cosine, -1), 1))
  22. }
  23. module.exports = angle