I've been taking a 3D programming class for a while now ,and our first assignment was ray tracing. TO cut it short, Im done with all of the assignment, I only need to be able to find the normal of the OBB, So I can shade it, and since Ive never worked with an OBB before, Im having trouble doing so. Here is my Ray tracing code for the OBB:
void TOBB::test(Ray& ray, HitData& hit)
{
float tMin = -INFINITY;
float tMax = +INFINITY;
Vec p = Bcenter - ray.o; // Bcenter is the center of the OBB. Ray.o is the origin of the ray.
Vec arr[3] = { Bu,Bv,Bw }; // Direction/base vectors. (1,0,0), (0,1,0), (0,0,1)
for (auto& i : arr)
{
float e = i.Dot(p);
float f = i.Dot(ray.d);
float q = -e - halfBu; // The distance between the center and each side. 100.
float w = -e + halfBu;
if (abs(f) > 1e-20f)
{
float t1 = ((e + halfBu) / f);
float t2 = ((e - halfBu) / f);
if (t1 > t2) { std::swap(t1, t2); }
if (t1 > tMin) { tMin = t1; }
if (t2 < tMax) { tMax = t2; }
if (tMin > tMax) { return; }
if (tMax < 0) { return; }
}
elseif (q > 0 || w < 0) { return; }
}
if (tMin > 0)
{
if (hit.t == -1)
{
hit.t = tMin;
hit.lastShape = this;
}
elseif (tMin < hit.t)
{
hit.t = tMin;
hit.lastShape = this;
}
}
elseif (tMax <= 0)
{
if (hit.t == -1)
{
hit.t = tMax;
hit.lastShape = this;
}
elseif (tMax < hit.t)
{
hit.t = tMax;
hit.lastShape = this;
}
}
}
I got this tip from the profesor but I didnt quite understand how to implement it.
lets say you have a hit point H, and you don't know in which face is.
You can compute one point S for each of the six faces using: center +- (vector*halfDist)
What would be dot (H-S , NormalFace) if H and S belong to the same face ?
Any vector in a plane is perpendicular to the normal to that plane. If you are given NormalFace, the vector to some face i, and Si is a point on that face, then dot(H-Si, NormalFace) is 0 if the point is in the plane, and it is not 0, otherwise.
You have 6 normal faces. The 3 provided base vectors, and their inverse, meaning: * -1.
So if you have a basevector Bu = (1,0,0), you would have another vector that is (-1,0,0).
Using these 6 normal faces, you can get a point on each side of the OBB using this formula.
center + (normalFace * theHalfDistance )
Now you have 6 normal faces. And 6 points on each side.
Now you use dot(H-S, NormalFace), if H and S is on the same side, you would get a float that is not exactly 0, but very close to 0.
Here is why: if H and S are two points on a side, H-S would be a vector between them, that is on the side. normalFace would be the normal vector sticking out of the OBB. The angle between these 2 vectors would then be 90 degrees and the dot product would be very close to 0.