mesh.lua 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. --- Mesh utilities
  2. -- @module mesh
  3. local modules = (...):gsub('%.[^%.]+$', '') .. "."
  4. local vec3 = require(modules .. "vec3")
  5. local mesh = {}
  6. -- vertices is an arbitrary list of vec3s
  7. function mesh.average(vertices)
  8. local out = vec3()
  9. for _, v in ipairs(vertices) do
  10. out = out + v
  11. end
  12. return out / #vertices
  13. end
  14. -- triangle[1] is a vec3
  15. -- triangle[2] is a vec3
  16. -- triangle[3] is a vec3
  17. function mesh.normal(triangle)
  18. local ba = triangle[2] - triangle[1]
  19. local ca = triangle[3] - triangle[1]
  20. return ba:cross(ca):normalize()
  21. end
  22. -- triangle[1] is a vec3
  23. -- triangle[2] is a vec3
  24. -- triangle[3] is a vec3
  25. function mesh.plane_from_triangle(triangle)
  26. return {
  27. origin = triangle[1],
  28. normal = mesh.normal(triangle)
  29. }
  30. end
  31. -- plane.origin is a vec3
  32. -- plane.normal is a vec3
  33. -- direction is a vec3
  34. function mesh.is_front_facing(plane, direction)
  35. return plane.normal:dot(direction) >= 0
  36. end
  37. -- point is a vec3
  38. -- plane.origin is a vec3
  39. -- plane.normal is a vec3
  40. -- plane.dot is a number
  41. function mesh.signed_distance(point, plane)
  42. return point:dot(plane.normal) - plane.normal:dot(plane.origin)
  43. end
  44. return mesh