# Example of a simple Ray Tracing Computation to compute primary ray and test intersection with a sphere

Assume:

VRP = [0 0 -10]

Window = -12 (Xleft), 12 (Xright), 9 (Ytop), -9 (Ybottom).

Notice the 4:3 ratio. The final image is to be computed at a size of 256 x 192 pixels (also a 4:3 ratio). There is one sphere located at [Xc Yc Zc] = [0 0 10] with a radius, Sr = 5.

Then: dx per pixel = 24/256 = 0.09375, dy per pixel = 18/192 = 0.09375

The center of the top left pixel (0, 0) is at Xleft + 0.5 * dx and Ytop - 0.5 * dy = (-11.9531, 8.9531). As you go across a scan-line add dx to find the next X value. As you go down the scan lines, add dy to find the Y values.

Let us form a ray through a pixel slightly to the left and above of center of the image. Choose pixel (120, 90). In world coordinates this will be:

```
Xleft + 0.5 * dx + 120 * dx = -0.7031 = Xp
Ytop + 0.5 * dy + 90 * dy = 0.5156 = Yp
Zp = 0 since image plane is at Z = 0

Form the Ray: Ro + t * Rd  Ro = VRP = [ Xo Yo Zo] = [0 0 -10]
Rd = [Xp - Xo, Yp - Yo, Zp - Zo] = [-0.7031  0.5156  10]  Length = 10.0379
After normalizing: [Xd Yd Zd] = [-0.0700  0.0514 0.9962]  ```

Testing for sphere intersection (putting the ray equation into the sphere equation) we get

```
(X0 + Xd*t - Xc)^2 + (Y0 + Yd*t - Yc^)2 + (Z0 + Zd*t - Zc)^2 = Sr^2
or  A*t^2 + B*t + C = 0

A = Xd^2 + Yd^2 + Zd^2 = 1

B = 2*(Xd*(X0 - Xc) + Yd*(Y0 - Yc) + Zd*(Z0 - Zc))
= 2*(-.07*(0 - 0) + .5156*(0 - 0 ) + .9962*( -10 - 10) )
= -39.85

C = (X0 - Xc)^2 + (Y0 - Yc)^2 + (Z0 - Zc)^2 - Sr^2
= 0 + 0  + 400 - 25 = 375
```

Then discriminant (B^2 - 4*C) = (1587.93 - 1500) = 87.93 which is > 0, so there is an intersection

t0 is for (-) and t1 is for (+)

t0, t1 = (-/+ B + (B^2 - 4*C)^1/2)/2

t0 = (-(-39.85) - sqrt(87.93))/2 = 15.246

Then t0 = 15.246 which is > 0.0 and is greater than the primary ray distance to the screen (length = 10.0379) so we are through. Be sure to test the primary ray intersections against the length to the screen for near plane clipping.

The Intersection point is:

Ri = [xi, yi, zi] = [x0 + xd * ti, y0 + yd * ti, z0 + Zd *ti] = [-1.067 0.783 5.18]

The unit N at surface
SN = [(x i - xc)/Sr, (yi - yc)/Sr, (zi - zc)/Sr] = [-0.2134 0.1566 -0.964]

Ray Tracing Design Page