A few weeks ago, I was looking at a scene in GameHalf and felt it was difficult to parse visually. It seemed to take some mental effort to discern the walls from the floor and such. Part of the problem was that I had used a single texture for the walls and the ground but the other part was that the scene was not lit. The problem was even more apparent when looking at sloping ground. For example, in the scene below it is easy enough to discern the ground height:
But if you switch the texture, it becomes nearly impossible:
Of course, lighting is computationally expensive and Flash tends to resist any sort of computational complexity. However, Flash 10 provides what seems like the perfect solution: shaders. However, although similar to the H/GLSL shaders used for lighting in DirectX and OpenGL, Flash shaders lack some features which make it a bit more challenging to use them to light a 3D scene.
Most importantly, a Flash shader is just a pixel shader. There is no vertex shader and the only per invocation information you get is the (x,y) position of the pixel. So to do Phong shading, you need to calculate and send in the transformation from texture space to local space, the normal of each vertex in the polygon, and the light vector in local space. In the shader, you convert the (x,y) position to a position in local space. Then use a barycentric coordinate calculation to find the right mix of vertices and calculate the normal in local space. After that you are pretty much just a dot product away from a nicely lit scene:
Even for the first texture the scene looks much more realistic:
Of course, this is just ambient and diffuse directed light but from this point adding specular lighting, point lights or even normal maps are pretty simple extensions. However, keep in mind that unlike H/GLSL, this code is getting executed on the cpu, not the gpu (even if you put flash in "gpu" mode), so you can't push it too far if you need the redraw to be reasonably fast. It is, however, much faster than pure Actionscript code.
For more on Flash Shaders, there is a
great post at
kaourantin.net which spells out all the gotchas (of which there are more than a few).