Sphere Properties:
1. Sphere Radius
2. Sphere Center
Using these tow properties we can construct a sphere:
(x-xc)^2+ (y-yc)^2 + (z-zc)^2 = r^2
Here (xc, yc, zc) are coordinate of sphere center
r is sphere radius
In Parametric form we can write the equation of sphere as:
(p-c).(p-c) = r^2
here p is point on sphere and c is center of sphere
Ray Equation in parametric form:
p(t) = e + t d
e = camera position
d = ray direction which we constructed in Image plane setup i.e. (s-e) s is pixel center coordinate
t = unknown
Replacing ray equation in sphere equation:
(e+td-c).(e+td-c) - R^2 = 0
Expanding the equation :
(d.d) t + 2d.(e-c)t + (e-c).(e-c) - R^2 = 0
Its a quadratic equation in t which gives us two roots which signifies two intersection point on sphere.
We can rewrite the equation as:
at^2 + bt +c = 0
a = d.d
b = 2d.(e-c)
c = (e-c).(e-c) - R^2
First we need to check whether ray is intersection with the sphere or not:
determinant = sqrt (b^2 - 4ac)
b2 – 4ac < 0 ⇒ No intersection b2 – 4ac > 0 ⇒ Two solutions (enter and exit) b2 – 4ac = 0 ⇒ One solution (ray grazes sphere)
If the ray intersects the sphere we need to find the smallest root:
t = (-b + d) / 2a and (-b - d) / 2a
Algorithm: For each pixel { construct a ray from eye (camera )through the pixel center of image plane min_t = ∞ For each object { if (t = intersection(ray, object)) { if (t < min_t) { closestObject = object min_t = t } } } } Code for Ray Sphere Intersection:
rayStart is camera position rayDirection is direction of the ray i.e. (s-e) float Sphere::intersection(SbVec3f rayStart, SbVec3f rayDirection) { d = rayDirection; float t1 = -1; float t2 = -1; float discriminent; float t = -1; //temporary == e-c temporary = rayStart; temporary -=center; float b = 2*(d.dot(temporary)); float a = d.dot(d); float c = temporary.dot(temporary) - (radius * radius); float disc; disc = b*b - 4*a*c; if(disc < 0){ return -1; } else{ discriminent = sqrt(disc); t1 = (-b+discriminent)/(2*a); t2 = (-b-discriminent)/(2*a); if(t10) t = t1; } else{ if(t2>0) t = t2; } } return t; }
To find the intersection point on sphere we can replace the returned value of t from the above method into ray equation, which in turn give us the intersection point on closest sphere.
Once we had found the intersection point on the sphere, we need to render the color of the sphere onto the pixel on image plane. I will tell you how to render the color of sphere or any other object in my next post i.e. Render Color
No comments:
Post a Comment