1
0

sphere.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /*
  2. * Copyright (c), Recep Aslantas.
  3. *
  4. * MIT License (MIT), http://opensource.org/licenses/MIT
  5. * Full license can be found in the LICENSE file
  6. */
  7. #ifndef cglm_sphere_h
  8. #define cglm_sphere_h
  9. #include "common.h"
  10. #include "mat4.h"
  11. /*
  12. Sphere Representation in cglm: [center.x, center.y, center.z, radii]
  13. You could use this representation or you can convert it to vec4 before call
  14. any function
  15. */
  16. /*!
  17. * @brief helper for getting sphere radius
  18. *
  19. * @param[in] s sphere
  20. *
  21. * @return returns radii
  22. */
  23. CGLM_INLINE
  24. float
  25. glm_sphere_radii(vec4 s) {
  26. return s[3];
  27. }
  28. /*!
  29. * @brief apply transform to sphere, it is just wrapper for glm_mat4_mulv3
  30. *
  31. * @param[in] s sphere
  32. * @param[in] m transform matrix
  33. * @param[out] dest transformed sphere
  34. */
  35. CGLM_INLINE
  36. void
  37. glm_sphere_transform(vec4 s, mat4 m, vec4 dest) {
  38. glm_mat4_mulv3(m, s, 1.0f, dest);
  39. dest[3] = s[3];
  40. }
  41. /*!
  42. * @brief merges two spheres and creates a new one
  43. *
  44. * two sphere must be in same space, for instance if one in world space then
  45. * the other must be in world space too, not in local space.
  46. *
  47. * @param[in] s1 sphere 1
  48. * @param[in] s2 sphere 2
  49. * @param[out] dest merged/extended sphere
  50. */
  51. CGLM_INLINE
  52. void
  53. glm_sphere_merge(vec4 s1, vec4 s2, vec4 dest) {
  54. float dist, radii;
  55. dist = glm_vec3_distance(s1, s2);
  56. radii = dist + s1[3] + s2[3];
  57. radii = glm_max(radii, s1[3]);
  58. radii = glm_max(radii, s2[3]);
  59. glm_vec3_center(s1, s2, dest);
  60. dest[3] = radii;
  61. }
  62. /*!
  63. * @brief check if two sphere intersects
  64. *
  65. * @param[in] s1 sphere
  66. * @param[in] s2 other sphere
  67. */
  68. CGLM_INLINE
  69. bool
  70. glm_sphere_sphere(vec4 s1, vec4 s2) {
  71. return glm_vec3_distance2(s1, s2) <= glm_pow2(s1[3] + s2[3]);
  72. }
  73. /*!
  74. * @brief check if sphere intersects with point
  75. *
  76. * @param[in] s sphere
  77. * @param[in] point point
  78. */
  79. CGLM_INLINE
  80. bool
  81. glm_sphere_point(vec4 s, vec3 point) {
  82. float rr;
  83. rr = s[3] * s[3];
  84. return glm_vec3_distance2(point, s) <= rr;
  85. }
  86. #endif /* cglm_sphere_h */