How It Works: Raytracing

remixed by ProdigyZeta7
  scripts
  sprites
See inside
Instructions

Arrow keys to rotate the model
Mouse position to aim the ray

See if you can get the ray to hit a sphere and reflect (multiple times). ;)

The green line is the ray
The blue line is the normal

Notes and Credits (added by ProdigyZeta7)

This model demonstrates how a ray intersects with a sphere and then bounces off as a reflected ray. Given a set of objects (spheres), the program determines if and where an intersection occurs with the ray and any one sphere, then re-directs the ray back into the environment as a reflected ray.

Assume the following:
P is the point that starts the ray.
R is the direction of the ray
R' is the direction of the reflected ray
S is the sphere's position
r is the sphere's radius
C is the intersection point
N is the normal at the intersection point C

The ray is defined as Position + (Direction * Time)
Because position and direction are already given, time is what needs to be calculated:
1. V = S - P (find the distance squared between the ray and sphere)
2. d = R * V :: if dot product < 0, stop (if it occurs 'behind' the ray)
3. if d^2 - (V^2 - r^2) < 0, stop
4. C = ±sqrt(d^2 - (V^2 - r^2)) - d
5. C is the "time" it takes to intersect with the sphere, thus
Intersections at P + R*(±sqrt(d^2 - (V^2 - r^2)) - d)
6. To calculate the normal, simply find the scalar value of C - S:
N = (C - S) / ||C - S||
7. Where the closest intersection occurs, that is where the reflected ray is calculated: 1) dot = R * N, 2) R' = R - 2dN

Steps 1-7 are repeated until the closest intersection among the entire set of spheres is found. Depending on where the intersection occurs, a base color and shade are taken from the sphere that was hit. Then, diffuse lighting (how a sphere gets shaded by a light source) and phong lighting (the bright shiny spot where the light is most concentrated) are calculated using the normal.

The full raytracer is here:
http://scratch.mit.edu/projects/12558735

For more information, see:
http://en.wikipedia.org/wiki/Ray_tracing

Shared: 16 Jul 2013 Modified: 2 May 2014
Favorite this project 27
Love this project 59
Total views 1436
View the remix tree  20
  
More projects by ProdigyZeta7