-
Notifications
You must be signed in to change notification settings - Fork 0
/
bvh.h
87 lines (65 loc) · 2.59 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
//
// Created by W9990 on 2023/12/3.
//
#ifndef RAYTRACING_BVH_H
#define RAYTRACING_BVH_H
#include <algorithm>
#include "constants.h"
#include "object/object.h"
#include "scene.h"
class bvh_node : public object {
public:
bvh_node(const scene& list) : bvh_node(list.objects, 0, list.objects.size()) {}
bvh_node(const std::vector<shared_ptr<object>>& src_objects, size_t start, size_t end) {
auto objects = src_objects; // Create a modifiable array of the source scene 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 intersection(const ray& r, interval ray_t, hit_record& rec) const override {
if (!bbox.hit(r, ray_t))
return false;
bool hit_left = left->intersection(r, ray_t, rec);
bool hit_right = right->intersection(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; }
private:
shared_ptr<object> left;
shared_ptr<object> right;
aabb bbox;
static bool box_compare(
const shared_ptr<object> a, const shared_ptr<object> 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<object> a, const shared_ptr<object> b) {
return box_compare(a, b, 0);
}
static bool box_y_compare (const shared_ptr<object> a, const shared_ptr<object> b) {
return box_compare(a, b, 1);
}
static bool box_z_compare (const shared_ptr<object> a, const shared_ptr<object> b) {
return box_compare(a, b, 2);
}
};
#endif //RAYTRACING_BVH_H