Ray Casting
visibility of surfaces by tracing imaginary rays of light from eye to objects in the scene

Non computer image:  light hits eye
Computer image:  for each pixel, what is seen: trace ray from eye into world

Pin hole camera

Ray-Casting:  Inverse Mapping approach
  go thru all primitives at each pixel
  sample first
  analytic processing afterwards
  requires display list (list of objects)

Graphics Pipeline Review  (raster graphics
	Primitives are processed one at a time
	all analytical processing early on
	sampling occurs late
	minimal state required (immediate mode rendering)
	Processing is forward-mapping

Problems with Ray Casting
	no advantage of screen space coherence
	Costly visibility computation
	Works only for solids
	forces per pixel illumination evaluations
	Not suited for immediate mode rendering

Turner Whitted 1980
recursive ray casting -> ray tracing
See Slide

makes use of actual physics and mathematics of light
-> photorealistic images
Simulation of classical ray optics

scene:
camera
lights
objects

Ray:
thin straight line used to model a beam of light
origin + time*direction    t =[0,inf)

p(t) = e + t (s - e) 
where e=eye_pt, s = surface (hit) pt, t = time
"advance from e along the vector (s-e) a fractional distance t to find the pt p"

p(0)=e p(1)=s
positive t, if t_1 < t_2, p(t_1) closer than p(t_2)
 t< 0, p is behind e

Typs of rays:
eye/pixel rays
illumination/shadow rays
reflection rays
transmission/transparency rays

Eye Rays:
effectively determine visible surfaces
Perspective view:  eye thru pixel
Orthogonal:  parallel rays thru pixel in direction of projection
Stop at nearest intersection with surface

basic algorithm (See slide):

for each pixel
   for each object
    test ray from eye in direction of pixel (perspective projection)
    if hits, record hit; record object;
   end

   get pixel color for closest hit (light it)
end

what is a hit
	Keep track of smallest t so far
	ray-object intersection (parametric math)

Ray-Object intersection
ray = e + t*d
intersect with any object, t > 0

Ray-Sphere Intersection
ray = p(t) = e + t d
implicit srf = f(p) = 0

intersection at   f(p(t)) = 0
		f(e + t*d) = 0

Sphere with center c = (c_x, c_y, c_z) and radius R
	(x - c_x)^2 + (y - c_y)^2 + (z - c_z)^2 - R^2 = 0
	= (p - c) . (p - c) - R^2 = 0

any pt p that satisfies this equation is on the sphere
plug in pts on ray p(t)=e+t*d

(e + t*d - c )  .  (e + t*d - c) - R^2 = 0
(d . d) t^2  + 2d . (e - c) t + (e-c) . (e-c) - R^2 = 0
	(ERROR in shirley book)

unknown is t  & eq takes form 
	A*t^2 + B*t + C = 0 

t = (-B +/- sqrt(B^2 - 4AC) ) / (2A)

term under sqrt is B^2 - 4AC
this is the discriminant and should be checked (is enough to check when doing bounding volumes) 
	if negative, there are no solutions
	if 0, ray grazes sphere at one pt
	else two solutions (in  & out of sphere)
Sphere Normal:  n = 2(p-c)  
	Unit Normal = (p - c)/R

Ray-Triangle Intersection
Use Barycentric Coordinates
See handout

Surface Model

I = sum of local illumination (attenuated illumination rays)
     + attenuated reflection ray
     + attenuated transmission ray

illuminate rays attenated by transmission coeffiecients of light occluders
reflection rays attenuated by specular coeffiecient
Transmission ray attenuated by transmission coefficent

c = c_r * c_a  + Si( c_r c_l max(0,n.l) + 
                                  c_l c_p (h . n)^p  )

c_r = diffuse reflected color of surface
c_a = ambient color from world (sky light)
c_l = light color
c_p = highlight color = usually set to light color
  h = half vector =  normalize(normalize(L) + normalize(-d))
  p = phong exponent
  e = eye point
  d = direction vector
  L = l = light
  n = surface normal
  Si = Shadow [0,1] (0 is in shadow, 1 if not)

good for coding:  

c_a + c_l <= (1,1,1) (may want to clamp)

c_p = 1 - M  where M is max component of c_r to keep color below one for light source and no ambient term

Adding Shadows
    From surface point towards light source
	 Intervening surfaces may block or attenuate direct illumination

Recursion to get multiple bounces
	Reflection
	   angle of reflection = angle of incidence
 	   on plane with incident and surface normal
        From hit point towards reflection direction
        Contribute illumination from closest surface intersection
        Assume perfect (sharp specular reflection)
        Attenduated by specular coeffiecient

    Add Reflection with recursive call
	c = c + c_s * trace((p+s*r), epsilon, inf)
	where r = d - 2 * (d . n) n

	(see slide on reflection ray)

Transmission
        Gather light transmitted thru current surface
	Attenuated by transmission coefficient
	Incident ray refraced according to index of refraction & Snell's law
     
 Refraction  (see slide on Refraction)
	Snell's law
	n_i sin theta_i  = n_r  sin theta_r
	  i = material of incidence 
	  r = material of refraction

	Indices:  air = 1.00003   water = 1.33   glass = 1.5

Add Refraction:  transparent material that refract or filter light
	diamonds, glass, water, air, etc

ray travels from one medium with refractive index n
into one with refractive index n_t, some of light is transmitted and it bends

See book pg 162-163 on derivation, but we get an equation for t with respect to the two refractive indices and normal of surface and view direction:
 t = (n (d - n(d.n)))/n_t  - n*sqrt (1  - (n^2(1-(d.n)^2)/(n_t)^2)

works regardless of which n or n_t is larger

if number under sqrt is negative, then no refacted ray and all energy is reflected = total internal reflection = glass

I = I_a + k_d *  Sum_over_lights {  (N . L)  + k_s S  + k_t  T  }

See nxt slide

Trace (ray)
	For each object in scene
		intersect (ray, object)
	If no intersections
		return background_color
	Current color = c_a * c_r  (ambient (sky)* diffuse reflected color of object);
	For each light
		for each object in scene
			intersect(shadowRay, object)
		Accumulate local illumination
	Trace (ReflectionRay)
	Trace (TransmissionRay)
	Accumulate global illumination
	Return illumination

(See nxt slide)
Sampling issues
pixel
reflection 
transmission
frame time
eye point
	->  Aliasing
		 = high frequency signal masquerading as lower frequency
	wagon wheel illusion

Jaggies

Solutions

supersampling:  multiple rays thru each pixel  (regular grid 3x3 or 4x4
  avg resulting intensities  = box filter

Adaptive supersampling
	sample at corners & center
	add more samples if gradient (change over pixel) is larger than a threshold
	Add samples only in necessary regions
	more efficient (may not be enough)

jittering
	random perturbations to sampling positions of uniform or adaptive grid
	removes regularity
	converts aliasing to noise... more tolerable

Speed:
1024x1024 is 1million pixels

performance = early rejection
Bounding Volumes
Spatial Subdivision
Light or Shadow Buffers