studies/grafik2/Computergrafik-Code6/Aufgabe17/BOX.CPP
⇒
download file
1 #include "box.h"
2
3 Box::Box(const Vector& llf,const Vector& urb) : llf_(llf), urb_(urb) {
4 }
5
6
7 const Vector& Box::getLLF() const { return llf_; }
8
9 void Box::setLLF(const Vector& v) { llf_ = v; }
10
11 const Vector& Box::getURB() const { return urb_; }
12
13 void Box::setURB(const Vector& n) { urb_ = n; }
14
15 inline double max(double x, double y) {
16 return (x<y) ? y : x;
17 }
18 inline double min(double x, double y) {
19 return (x>y) ? y : x;
20 }
21
22 bool Box::intersect(const Ray& ray,Vector& point,Vector& normal, double& distance) const {
23 const static Vector NormalRight(+1,0,0);
24 const static Vector NormalLeft (-1,0,0);
25 const static Vector NormalUp (0,+1,0);
26 const static Vector NormalDown (0,-1,0);
27 const static Vector NormalFront(0,0,+1);
28 const static Vector NormalBack (0,0,-1);
29
30
31 const Vector origin = ray.getOrigin();
32
33 const Vector direction = ray.getDirection();
34
35
36
37 double tnear = -999999999999;
38
39 double tfar = +999999999999;
40
41
42
43
44 const double& ox = origin[0];
45 const double& rx = direction[0];
46
47
48 if (rx == 0)
49 if (ox < llf_[0] || ox > urb_[0])
50 return false;
51
52
53 const double tx1 = (llf_[0] - ox) / rx;
54 const double tx2 = (urb_[0] - ox) / rx;
55
56
57 if (tx2 > tx1 && tx1 > tnear)
58 {
59 tnear = tx1;
60 normal = NormalLeft;
61 }
62 if (tx1 > tx2 && tx2 > tnear)
63 {
64 tnear = tx2;
65 normal = NormalRight;
66 }
67
68
69 tfar = min(tfar, max(tx1, tx2));
70 if (tnear > tfar || tfar < 0)
71 return false;
72
73
74
75
76 const double& oy = origin[1];
77 const double& ry = direction[1];
78
79
80 if (ry == 0)
81 if (oy < llf_[1] || oy > urb_[1])
82 return false;
83
84
85 const double ty1 = (llf_[1] - oy) / ry;
86 const double ty2 = (urb_[1] - oy) / ry;
87
88
89 if (ty2 > ty1 && ty1 > tnear)
90 {
91 tnear = ty1;
92 normal = NormalDown;
93 }
94 if (ty1 > ty2 && ty2 > tnear)
95 {
96 tnear = ty2;
97 normal = NormalUp;
98 }
99
100
101 tfar = min(tfar, max(ty1, ty2));
102 if (tnear > tfar || tfar < 0)
103 return false;
104
105
106
107
108 const double& oz = origin[2];
109 const double& rz = direction[2];
110
111
112 if (rz == 0)
113 if (oz < llf_[2] || oz > urb_[2])
114 return false;
115
116
117 const double tz1 = (llf_[2] - oz) / rz;
118 const double tz2 = (urb_[2] - oz) / rz;
119
120
121 if (tz2 > tz1 && tz1 > tnear)
122 {
123 tnear = tz1;
124 normal = NormalBack;
125 }
126 if (tz1 > tz2 && tz2 > tnear)
127 {
128 tnear = tz2;
129 normal = NormalFront;
130 }
131
132
133 tfar = min(tfar, max(tz1, tz2));
134 if (tnear > tfar || tfar < 0)
135 return false;
136
137
138
139 point = ray.getOrigin() + tnear*ray.getDirection();
140 distance = tnear;
141
142
143 return true;
144 }
145