MUDA
Loading...
Searching...
No Matches
bounding_volume.h
1#pragma once
2#include <muda/ext/eigen/eigen_core_cxx20.h>
3#include <Eigen/Geometry>
4#include <muda/muda_def.h>
5
6namespace muda::spatial_hash
7{
9{
10 using Vector3 = Eigen::Vector3f;
11
12 public:
13 MUDA_GENERIC BoundingSphere(const Vector3& o, float r)
14 : o(o)
15 , r(r)
16 {
17 }
18 MUDA_GENERIC BoundingSphere() = default;
19
20 Vector3 o = Vector3::Zero();
21 float r = 0.0f;
22 int level = 0;
23};
24
25class AABB
26{
27 using Vector3 = Eigen::Vector3f;
28
29 public:
30 Vector3 max;
31 Vector3 min;
32
33 MUDA_GENERIC AABB(const Vector3& min, const Vector3& max)
34 : min(min)
35 , max(max)
36 {
37 }
38
39 MUDA_GENERIC AABB(const AABB& l, const AABB& r)
40 {
41 max = l.max.cwiseMax(r.max);
42 min = l.min.cwiseMin(r.min);
43 }
44
45 MUDA_GENERIC Vector3 center() const { return (max + min) / 2; }
46
47 MUDA_GENERIC float radius() const { return (max - min).norm() / 2; }
48};
49
50MUDA_INLINE MUDA_GENERIC float squared_distance(const Eigen::Vector3f& p, AABB b)
51{
52 float sq_dist = 0.0f;
53#pragma unroll
54 for(int i = 0; i < 3; i++)
55 {
56 // for each axis count any excess distance outside box extents
57 float v = p[i];
58 if(v < b.min[i])
59 sq_dist += (b.min[i] - v) * (b.min[i] - v);
60 if(v > b.max[i])
61 sq_dist += (v - b.max[i]) * (v - b.max[i]);
62 }
63 return sq_dist;
64}
65
66MUDA_INLINE MUDA_GENERIC float distance(const Eigen::Vector3f& p, AABB b)
67{
68 return ::sqrt(squared_distance(p, b));
69}
70
71MUDA_INLINE MUDA_GENERIC bool intersect(const BoundingSphere& s, const AABB& b)
72{
73 // Compute squared distance between sphere center and AABB
74 // the sqrt(dist) is fine to use as well, but this is faster.
75 float sqDist = squared_distance(s.o, b);
76
77 // Sphere and AABB intersect if the (squared) distance between them is
78 // less than the (squared) sphere radius.
79 return sqDist <= s.r * s.r;
80}
81
82MUDA_INLINE MUDA_GENERIC bool intersect(const BoundingSphere& lhs, const BoundingSphere& rhs)
83{
84 float r = lhs.r + rhs.r;
85 return (lhs.o - rhs.o).squaredNorm() <= r * r;
86}
87
88MUDA_INLINE MUDA_GENERIC bool intersect(const AABB& l, const AABB& r)
89{
90 Eigen::Vector3i c;
91#pragma unroll
92 for(int i = 0; i < 3; ++i)
93 c[i] = l.min[i] <= r.max[i] && l.max[i] >= r.min[i];
94 return c.all();
95}
96} // namespace muda::spatial_hash
Definition bounding_volume.h:26
Definition bounding_volume.h:9