Path Tracer
hittable_list.hpp
1 #pragma once
2 #include <common.hpp>
3 #include <hittable/hittable.hpp>
4 #include <camera/ray.hpp>
5 #include <utils.hpp>
6 #include <math3d/vec3.hpp>
7 using namespace ptracey;
8 
9 namespace ptracey {
10 
11 class hittable_list : public hittable {
12 public:
13  hittable_list() {}
14  hittable_list(shared_ptr<hittable> object) {
15  add(object);
16  }
17  hittable_list(std::vector<shared_ptr<hittable>> objs) {
18  objects.clear();
19  for (const auto &obj : objs)
20  add(obj);
21  }
22 
23  void clear() { objects.clear(); }
24  void add(shared_ptr<hittable> object) {
25  objects.push_back(object);
26  }
27 
28  virtual bool hit(const ray &r, Real t_min, Real t_max,
29  hit_record &rec) const override;
30 
31  virtual bool
32  bounding_box(Real time0, Real time1,
33  aabb &output_box) const override;
34  virtual Real pdf_value(const vec3 &o,
35  const vec3 &v) const override;
36  virtual vec3 random(const vec3 &o) const override;
37 
38 public:
39  std::vector<shared_ptr<hittable>> objects;
40 };
41 bool hittable_list::hit(const ray &r, Real t_min,
42  Real t_max, hit_record &rec) const {
43  hit_record temp_rec;
44  auto hit_anything = false;
45  auto closest_so_far = t_max;
46 
47  for (const auto &object : objects) {
48  if (object->hit(r, t_min, closest_so_far, temp_rec)) {
49  hit_anything = true;
50  closest_so_far = temp_rec.t;
51  rec = temp_rec;
52  }
53  }
54 
55  return hit_anything;
56 }
57 bool hittable_list::bounding_box(Real time0, Real time1,
58  aabb &output_box) const {
59  if (objects.empty())
60  return false;
61 
62  aabb temp_box;
63  bool first_box = true;
64 
65  for (const auto &object : objects) {
66  if (!object->bounding_box(time0, time1, temp_box))
67  return false;
68  output_box =
69  first_box ? temp_box
70  : surrounding_box(output_box, temp_box);
71  first_box = false;
72  }
73 
74  return true;
75 }
76 Real hittable_list::pdf_value(const point3 &o,
77  const vec3 &v) const {
78  auto weight = 1.0 / objects.size();
79  auto sum = 0.0;
80 
81  for (const auto &object : objects)
82  sum += weight * object->pdf_value(o, v);
83 
84  return sum;
85 }
86 vec3 hittable_list::random(const vec3 &o) const {
87  auto int_size = static_cast<int>(objects.size());
88  return objects[random_int(0, int_size - 1)]->random(o);
89 }
90 }
ptracey::ray
Definition: ray.hpp:8
ptracey::hit_record
Definition: hittable.hpp:11
ptracey::hittable
Definition: hittable.hpp:35
ptracey::vec3
Definition: vec3.hpp:7
ptracey::hittable_list
Definition: hittable_list.hpp:11
ptracey::aabb
Definition: aabb.hpp:12