-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaabb.c
More file actions
119 lines (97 loc) · 2.5 KB
/
aabb.c
File metadata and controls
119 lines (97 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "aabb.h"
#include "util.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
//
// Returns a pointer to a newly created AABB.
//
AABB *aabb_create(vec3 min, vec3 max) {
AABB *box = (AABB *)malloc(sizeof(AABB));
assert(box != NULL);
box->min = min;
box->max = max;
return box;
}
//
// Initializes a bounding box w/o dyanmically allocating any memory.
//
AABB aabb_init(vec3 min, vec3 max) {
AABB box;
box.min = min;
box.max = max;
return box;
}
//
// Deletes an AABB.
//
void aabb_delete(AABB **box) {
if (*box) {
free(*box);
*box = NULL;
}
return;
}
//
// Returns true if a ray hit an AABB, false otherwise.
//
bool aabb_hit(AABB aabb, ray r, double t_min, double t_max) {
// Comptue t-intervals along the x-axis
double invD = 1.0 / r.dir.x;
double t0 = (aabb.min.x - r.orig.x) * invD;
double t1 = (aabb.max.x - r.orig.x) * invD;
if (invD < 0.0) {
swap_double(&t0, &t1);
}
t_min = t0 > t_min ? t0 : t_min;
t_max = t1 < t_max ? t1 : t_max;
if (t_max <= t_min) {
return false;
}
// Comptue t-intervals along the y-axis
invD = 1.0 / r.dir.y;
t0 = (aabb.min.y - r.orig.y) * invD;
t1 = (aabb.max.y - r.orig.y) * invD;
if (invD < 0.0) {
swap_double(&t0, &t1);
}
t_min = t0 > t_min ? t0 : t_min;
t_max = t1 < t_max ? t1 : t_max;
if (t_max <= t_min) {
return false;
}
// Comptue t-intervals along the z-axis
invD = 1.0 / r.dir.z;
t0 = (aabb.min.z - r.orig.z) * invD;
t1 = (aabb.max.z - r.orig.z) * invD;
if (invD < 0.0) {
swap_double(&t0, &t1);
}
t_min = t0 > t_min ? t0 : t_min;
t_max = t1 < t_max ? t1 : t_max;
if (t_max <= t_min) {
return false;
}
return true;
}
//
// Computes the bounding box of two boxes.
//
AABB surrounding_box(AABB box0, AABB box1) {
vec3 small = v3_init(fmin(box0.min.x, box1.min.x), fmin(box0.min.y, box1.min.y),
fmin(box0.min.z, box1.min.z));
vec3 big = v3_init(fmax(box0.max.x, box1.max.x), fmax(box0.max.y, box1.max.y),
fmax(box0.max.z, box1.max.z));
AABB surrounding_box = {small, big};
return surrounding_box;
}
//
// Prints the lower and upper bound of the given AABB.
//
void aabb_print(AABB box) {
printf("Bounding box -> ");
printf("Min: (%f, %f, %f), Max: (%f, %f, %f)\n", box.min.x, box.min.y, box.min.z,
box.max.x, box.max.y, box.max.z);
return;
}