Line data Source code
1 : #pragma once
2 : #include <math3d/math3d.hpp>
3 : namespace rbc
4 : {
5 : // -------------------------------------------------------------------------
6 : // AABB - Axis-Aligned Bounding Box
7 : // Stored as min/max corners in world space.
8 : // Fattenned by a small margin during broad phase for temporal coherence.
9 : // -------------------------------------------------------------------------
10 : struct AABB
11 : {
12 : m3d::vec3 min;
13 : m3d::vec3 max;
14 :
15 160 : AABB() : min(m3d::vec3(std::numeric_limits<m3d::scalar>::infinity())),
16 160 : max(m3d::vec3(-std::numeric_limits<m3d::scalar>::infinity())) {}
17 :
18 2659 : AABB(const m3d::vec3 &min, const m3d::vec3 &max) : min(min), max(max) {}
19 :
20 : bool operator==(const AABB &other) const
21 : {
22 : return min == other.min && max == other.max;
23 : }
24 :
25 : bool operator!=(const AABB &other) const
26 : {
27 : return !(*this == other);
28 : }
29 : };
30 :
31 : // -------------------------------------------------------------------------
32 : // Basic AABB operations
33 : // -------------------------------------------------------------------------
34 529 : inline bool aabb_overlap(const AABB &a, const AABB &b)
35 : {
36 : // Separating axis test on all 3 axes
37 529 : return (a.min.x <= b.max.x && a.max.x >= b.min.x) &&
38 1486 : (a.min.y <= b.max.y && a.max.y >= b.min.y) &&
39 957 : (a.min.z <= b.max.z && a.max.z >= b.min.z);
40 : }
41 :
42 : inline AABB aabb_union(const AABB &a, const AABB &b)
43 : {
44 : return {
45 : m3d::vec3(m3d::min(a.min.x, b.min.x),
46 : m3d::min(a.min.y, b.min.y),
47 : m3d::min(a.min.z, b.min.z)),
48 : m3d::vec3(m3d::max(a.max.x, b.max.x),
49 : m3d::max(a.max.y, b.max.y),
50 : m3d::max(a.max.z, b.max.z))};
51 : }
52 :
53 : // Expand the AABB by a uniform margin on all sides.
54 : // Used to "fatten" AABBs for temporal coherence (avoids rebuilding the
55 : // sorted list every frame for objects that barely moved).
56 200 : inline AABB aabb_expand(const AABB &a, m3d::scalar margin)
57 : {
58 200 : const m3d::vec3 m(margin, margin, margin);
59 200 : return {a.min - m, a.max + m};
60 : }
61 :
62 : inline m3d::vec3 aabb_center(const AABB &a)
63 : {
64 : return (a.min + a.max) * 0.5;
65 : }
66 :
67 : inline m3d::vec3 aabb_half_extents(const AABB &a)
68 : {
69 : return (a.max - a.min) * 0.5;
70 : }
71 :
72 : // Surface area — used by BVH cost heuristics if you ever switch to one.
73 : inline m3d::scalar aabb_surface_area(const AABB &a)
74 : {
75 : const m3d::vec3 d = a.max - a.min;
76 : return 2.0 * (d.x * d.y + d.y * d.z + d.z * d.x);
77 : }
78 :
79 : } // namespace rbc
|