Simulating Fluids in Flash
A thread in the FGL forums got me interested in the simulation of fluids. Of course this topic has seen quite extensive coverage in academic papers but getting it to work in the limitted environment of Flash provides some intersting challenges. Interesting enough for me to give it a try over my christmas break.
I loosely followed a paper Particle-based Viscoelastic Fluid Simulation to implement a sandbox application that simulates and renders a small blob of fluid and allows you to tinker with various parameters. Click the image below and give it a try!
The fluid is represented as a set of ~400 particles that interact with their neighbours and such seem to form a coherent entity.
For rendering I use an oldschool approach: Each particle is represented as a metaball. For a given pixel the force function of every metaball is evaluated, summed up and the final sum is compared with a threshold value to decide whether the pixel is inside or outside of the fluid.
To be able to do that in realtime I precalculate the values that a forcefunction yields for pixels within a relevant range of the particles center as a Bitmap.
These tiny images (about 40×40 pixels) are rendered at the position of the particle with additive blendmode.
Now I can decide with a single lookup in the resulting Bitmap if a pixel belongs to the surface or not. That evaluation step is done by a pixel bender shader and instead of just working with a boolean state (inside or outside) I sample a gradient based on the accumulated force value.
This approach allows me to achieve a variety of styles in the visual appearance of the simulated fluid by just using different gradients.
This technique would unfold it’s real potential if you could use hardware acceleration to accumulate the field functions because that’s a bottle neck in the current implementation.
Not sure if that stuff has any practical relevance, anyway. But the SWF is only 32kb big so people that are into demos (32k, 64k) could maybe make something fancy out of it. Here’s the source code released under the MIT license.