modeling/src/maths/plane/fromPoints.js

  1. const vec3 = require('../vec3')
  2. /**
  3. * Create a plane from the given points.
  4. *
  5. * @param {plane} out - receiving plane
  6. * @param {Array} vertices - points on the plane
  7. * @returns {plane} out
  8. * @alias module:modeling/maths/plane.fromPoints
  9. */
  10. const fromPoints = (out, ...vertices) => {
  11. const len = vertices.length
  12. // Calculate normal vector for a single vertex
  13. // Inline to avoid allocations
  14. const ba = vec3.create()
  15. const ca = vec3.create()
  16. const vertexNormal = (index) => {
  17. const a = vertices[index]
  18. const b = vertices[(index + 1) % len]
  19. const c = vertices[(index + 2) % len]
  20. vec3.subtract(ba, b, a) // ba = b - a
  21. vec3.subtract(ca, c, a) // ca = c - a
  22. vec3.cross(ba, ba, ca) // ba = ba x ca
  23. vec3.normalize(ba, ba)
  24. return ba
  25. }
  26. out[0] = 0
  27. out[1] = 0
  28. out[2] = 0
  29. if (len === 3) {
  30. // optimization for triangles, which are always coplanar
  31. vec3.copy(out, vertexNormal(0))
  32. } else {
  33. // sum of vertex normals
  34. vertices.forEach((v, i) => {
  35. vec3.add(out, out, vertexNormal(i))
  36. })
  37. // renormalize normal vector
  38. vec3.normalize(out, out)
  39. }
  40. out[3] = vec3.dot(out, vertices[0])
  41. return out
  42. }
  43. module.exports = fromPoints