-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbvh.h
88 lines (69 loc) · 2.76 KB
/
bvh.h
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
#ifndef BVH_H
#define BVH_H
#include "util.h"
#include "hittable.h"
#include "hittable_list.h"
#include "aabb.h"
#include <algorithm>
class bvh_node : public hittable {
private:
aabb bbox;
shared_ptr<hittable> left;
shared_ptr<hittable> right;
static bool box_compare(
const shared_ptr<hittable> a, const shared_ptr<hittable> b, int axis_index
) {
return a->bounding_box().axis(axis_index).min < b->bounding_box().axis(axis_index).min;
}
static bool box_x_compare (const shared_ptr<hittable> a, const shared_ptr<hittable> b) {
return box_compare(a, b, 0);
}
static bool box_y_compare (const shared_ptr<hittable> a, const shared_ptr<hittable> b) {
return box_compare(a, b, 1);
}
static bool box_z_compare (const shared_ptr<hittable> a, const shared_ptr<hittable> b) {
return box_compare(a, b, 2);
}
public:
bvh_node(const hittable_list& list): bvh_node(list.objects, 0, list.objects.size()) {}
bvh_node(const std::vector<shared_ptr<hittable>>& src_objects, size_t start, size_t end) {
auto objects = src_objects;
int axis = random_int(0,2);
auto comparator = (axis == 0) ? box_x_compare :
(axis == 1) ? box_y_compare :
box_z_compare;
size_t object_span = end - start;
if (object_span == 1) {
left = right = objects[start];
} else if (object_span == 2) {
if (comparator(objects[start], objects[start+1])) {
left = objects[start];
right = objects[start + 1];
}
else {
left = objects[start+1];
right = objects[start];
}
} else {
std::sort(objects.begin() + start, objects.begin() + end, comparator);
auto mid = start + object_span/2;
left = make_shared<bvh_node>(objects, start, mid);
right = make_shared<bvh_node>(objects, mid, end);
}
bbox = aabb(left->bounding_box(), right->bounding_box());
}
bool hit(const ray& r, interval ray_t, hit_record& rec) const override {
auto boxx = bbox;
auto isHit = boxx.hit(r, ray_t);
if (!isHit) {
return false;
}
bool hit_left = left->hit(r, ray_t, rec);
bool hit_right = right->hit(r, interval(ray_t.min, hit_left ? rec.t : ray_t.max), rec);
return hit_left || hit_right;
}
aabb bounding_box() const override {
return bbox;
}
};
#endif