3d shading engine AS2 help? :)


I’m currently making a 3d engine, it is rendered using backface culling, which works very nicely. I’ve started trying to shade the faces. I don’t really know how to go about it. I figure in my 3d world i will have a light source (x, y, z). Now each face using the backface culling will either be visible or not. Say a face is visible, the angle between the light source and the face can be worked out by dot product. say triangle ABC is a face in 3d space.

xnormal = (B.y-A.y)*(C.z-A.z)-(B.z-A.z)*(C.y-A.y)
ynormal = (B.z-A.z)*(C.x-A.x)-(B.x-A.x)*(C.z-A.z)
znormal = (B.x-A.x)*(C.y-A.y)-(B.y-A.y)*(C.x-A.x)

so you have the normal vector (xnormal, ynormal, znormal)

then you have the vector of the source of light which is:

((xsource - facex), (ysource - facey), (zsource- facez))

using dot product to find the angle:

A = Cos ((|normal vector|*|light vector|) /(xnormal*(xsource - facex) + ynormal*(ysource - facey) + znormal*(zsource - facez))

so once you have an angle which should theoretically return something between 0 and 2pi (I hope :)) I was kind of wanting to know how to render depending on the angle to the source, obviously small angle means bright render, and large angle means dim, and also taking into account distance probably times a constant…

My problem is that I render using hex values. Is there a way of changing this brightness dynamically depending on the angle and distance, say I had a face with beginFill(0xFF0000) …face… endFill(); how would I change the brightness. Would this be doable with integers instead of hex?

Sorry about rambling, sometimes it helps me to write things down to work them out.

Any tips about the shading would be great, thanks! :slight_smile: