Z-buffers!
Here we're going back to the mesh objects that you already created, but we'll be using the PixApplet method for setting the color at each pixel that you have been using for Ray Tracing.
The Z-buffer algorithm is a way to get from triangles to shaded pixels.
You use the Z buffer algorithm to figure out which thing is in front at every pixel when you are creating fully shaded versions of your mesh objects, such as when you use the Phong surface shading algorithm.
You will want to have a list of Materials, where each Material object gives the data that you need to simulate a particular kind of surface using the Phong algorithm (eg: DiffuseColor, SpecularColor, etc.).
You will also want to have a list of Light source objects, just as you did when you were doing ray tracing.
The algorithm starts with an empty zBuffer, indexed by pixels [X,Y], and initially set to zero for each pixel. You also need an image FrameBuffer filled with background color. This frameBuffer can be the pix[] array you currently use for ray tracing.
The general flow of things is:
(X_BL, Y_BOTTOM) (X_BR, Y_BOTTOM)
You can see the process repesented here: First a polygon is split into triangles, and the eacn triangle is split into scan-line aligned trapezoids:
Each vertex of one of these scan-line aligned trapezoids will have both color and perspective z, or (r,g,b,pz).
If pz > zBuffer[X,Y] then replace the values at that pixel:
zBuffer[X,Y] ← pz
frameBuffer[X,Y] ← (r,g,b)
A note about linear interpolation:
In order to interpolate values from the triangle to the trapezoid, then from the trapezoid to the horizontal span for each scan-line, then from the span down individual pixels, you'll need to use linear interpolation.
Generally speaking, linear interpolation involves the following two steps:
value = a + t * (b - a)
In order to compute t, you just need your extreme values and the intermediate value where you want the results. For example, to compute the value of t to interpolate from scan-line Y_TOP and Y_BOTTOM to a single scan-line Y:
t = (double)(Y - Y_TOP) / (Y_BOTTOM - Y_TOP)Similarly, to compute the value of t to interpolate from pixels X_lEFT and X_RIGHT to values at a single pixel X:
t = (double)(X - X_LEFT) / (X_RIGHT - X_LEFT)