Original Post
Hey all, I was wondering if it would be possible for you guys to help me understand a lighting algorithm I found online. The source of this algorithm is : Lighting Algorithm And the algorithm is: (would be greatful if someone could show me how to tag code correctly) On the whole I understand what the function does - for each light in the scene add the diffuse and specular contribution to a pixel. The bits im confused with is the helper functions i dont quite understand this guys pseudocode. Could someone please explain these or maybe provide the c++ equivalent. Also where the pseudocode says lc = light color (rgb) does he mean the ambient? If not what does he mean?? Finally, where does he make use of the lights ambient, diffuse and specular? I only see the material which i'm understanding as being the polygon. Thanks in advance [Edited by - RenderMe on April 13, 2009 10:24:58 AM]
-- some helper functions
zeroclip(X) = [(x when x > 0.0 else 0.0) for x in X]
oneclip(X) = [(x when x < 1.0 else 1.0) for x in X]
unit(x) = x / |x| when |x| != 0.0 else 0.0
-- some pseudo-code to do the lighting
lightfunc(n, v, material, lights, camerapos) : (r,g,b) =
do {
-- let n = surface normal (nx,ny,nz)
-- let v = point in space (x,y,z)
-- let lights = [light0, light1, ... ]
-- let camerapos = (x,y,z)
scolor = material.specularcolor -- (r,g,b)
dcolor = material.diffusecolor -- (r,g,b)
acolor = material.ambientcolor -- (r,g,b)
shiny = material.shininess -- (a scalar, an exponent >= 0)
-- start off the diffuse and specular
-- at pitch black
diffuse = [0.0, 0.0, 0.0]
specular = [0.0, 0.0, 0.0]
-- copy the ambient color (for the eyelight ex/cred
-- code, you can change it here to rely on distance
-- from the camera)
ambient = acolor
for l in lights
do {
-- get the light position and color from the light
-- let lx = light position (x,y,z)
-- let lc = light color (r,g,b)
lx, lc = l
-- first calculate the addition this light makes
-- to the diffuse part
ddiffuse = zeroclip(lc * (n . unit(lx - v))
-- accumulate that
diffuse += ddiffuse
-- calculate the specular exponent
k = zeroclip(n . unit(unit(camerapos - v) + unit(lx - v)))
-- calculate the addition to the specular highlight
-- k^shiny is a scalar, lc is (r,g,b)
dspecular = zeroclip(k^shiny * lc)
-- acumulate that
specular += dspecular
}
-- after working on all the lights, clamp the diffuse value to 1
d = oneclip(diffuse)
-- note that d,dcolor,specular and scolor are all (r,g,b).
-- * here represents component-wise multiplication
rgb = oneclip(ambient + d*dcolor + specular*scolor)
return rgb
}