Question: double Sphere::Intersect ( Vector source, Vector d ) { / / Compute the intersection of a ray with a TRANSFORMED sphere / / You can

double Sphere::Intersect(Vector source, Vector d)
{
// Compute the intersection of a ray with a TRANSFORMED sphere
// You can assume that for a transformed object the vectors 'scaling' and 'translation" are defined.
// where (scaling.x,scaling.y,scaling.z) are the scale factors in x,y, and z direction
// and (translation.x,translation.y,translation.z) is the translation vector
// STEP 1: Transform the ray, compute the transformed ray start point and direction
Vector s =(source - translation).Scale(1/ scaling.x,1/ scaling.y,1/ scaling.z);
Vector dir = d.Scale(1/ scaling.x,1/ scaling.y,1/ scaling.z);
// STEP 2: Compute intersection of the transformed ray with the sphere
// A, B, and C are the parameters of the quadratic equation for finding the
// ray intersection parameter t (see "Ray Tracing" lecture notes)
float A = dir.Dot(dir);
float B =2* dir.Dot(s - center);
float C =(s - center).Dot(s - center)- radius * radius;
float t =-1.0; // the parameter t for the closest intersection point or ray with the sphere. If no intersection t=-1.0
// BEGIN SOLUTION RAY-SPHERE INTERSECTION
//================================================================
//== Delete the line "t=-1.0;" and insert your solution instead ==
//== NOTE 1: If there is no ray-shere intersection set t=-1.0==
//== NOTE 2: Use C notation so that the code runs in Coderunner ==
//== NOTE 3: You might want to use the sqrt() function ==
//================================================================
float discriminant = B * B -4* A * C;
if (discriminant <0){
t =-1.0;
}
else {
float t1=(-B - sqrt(discriminant))/(2* A);
float t2=(-B + sqrt(discriminant))/(2* A);
if (t1<0 && t2<0){
t =-1.0;
}
else if (t1>=0 && t2>=0){
t = fmin(t1, t2);
}
else {
t = fmax(t1, t2);
}
}
// END SOLUTION RAY-SPHERE INTERSECTION
return t;
}
Vector Sphere::Normal(Vector p)
{
// STEP 3: Calculate the correct normal for the transformed sphere
// replace the existing code below and use the values 'scaling' and 'translation" to compute the normal of the transformed sphere
Vector n =(p - center).Scale(1/ scaling.x,1/ scaling.y,1/ scaling.z).Normalize();
return n;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!