This will be split over 2 posts, the second covering the GPU version of this effect.
So, it all started with a page I found while looking up ray casting, and on there was also an algorithm for rendering old school fire, and I thought it would be easy for me to port the code to C#, so I did :D, then I thought I would put it into a shader, after all, XNA supports another 2 platforms you know :D
So, here is my class to render my 2D fire on the CPU.
So, basically how does it work?
There is a texture that stores the “temperature” for each pixel on the screen (the fire map, second image on the right in the picture above), now the class enables you to set the resolution of this texture, so if you are running this on the little known third platform that XNA supports, the Windows Phone :D then you may want to reduce this resolution, the final image will be up scaled as you will soon see.
As well as the fire map there is another texture that is used to render the fire to the screen, we take each pixel and use it’s value to extract a value from a third palette texture (the palette, picture on the top right of the image above)
So, we now have a fire map, a palette and a final render, but how is the fire animated? Well, on each update, we randomly set the bottom line of the fire map, each pixel on the bottom row having random value between min and max flame, then we descend through the texture from the top left corner and calculate it’s new values based on four pixels below it. The new value being the sum of the four pixels averaged. The average is then modified by how much oxygen we have, this simply makes the flames brighter.
Here you can see I created 2 constructors for the class, both create the palette texture and initialize the Random object, and one ca be used to control the resolution.
As you can see, this will result in an image that gives you a fade from red to bright yellow, you can set this for what ever color you like, or don’t use it and load a pre made texture from the content pipeline.
In the LoadContent method we can now populate the palette texture
As you can see I am also setting up the fire texture, the fire map array (fmap) and the palette texture.
Again, in here you can change this calculation to get you lots of different effects, with a blur palette and with alterations in here I managed to get a kind of shimmering water effect :D
And so we finally render our flames to the screen.
As ever, this si my stab at it, please feel free to comment and let me know what you think of it. Ill post the source code all in one go after the next post.