2021-11-16
After seeing the falling sand simulator Sandspiel, along with the accompanying "Making sandspiel" article, I just had to make one of my own! I'm fascinated by how a set of simple rules can result in such complex behaviour.
On this page I describe my own falling-sand toy, written using Rust, Bevy and egui. It's a 2D sandbox that is simulating a simplified form of physics.
Run in browser Download for Windows Source code
The sandbox is programmed in the Rust language. Rust is a safe low-level programming language with nice zero-cost abstractions. It has a steep learning curve, but there's plenty of help available. It comes with a wonderful package manager called Cargo that makes managing dependencies and building applications a breeze.
Bevy is an experimental open-source data driven game-engine written in Rust. It is built around an entity component system (ECS). egui is a simple immediate-mode GUI library for rust, which is very easy to integrate into bevy using the bevy-egui plugin. They all work together quite elegantly.
A falling-sand works like a cellular automaton. The world is divided into cells in a grid. For each cell we define a set of simple rules, based on what's in the neighbouring cells. I'll explain this using a few example "elements" that occupy the cells in a falling-sand game. Each element is governed by its own set of rules.
Sand will fall down if the cell below is empty. It will also slide diagonally down if there is room:
These two simple rules result in a nice sand-like behaviour where piles of sand are formed:
Water is a little more complicated. Water not only falls down and slides diagonally, but it flows horizontally as well. In other words: if one of the horizontally neighbouring cells contains air, move the water there:
This ensures that (eventually) the water will gain an equal level:
Elements in a falling sand game can also interact with each other. One example is fire, which is relatively complex. Fire moves in all directions with a tendency upwards (this is done using a random number generator). Other elements that are burnable (like wood or oil) are turned into fire as well if they are fire's neighbours. Fire burns out over time. Some elements, like wood, turn to ash when they burn. And finally, fire generates some smoke.
This set of rules results in nice pseudo-realistic fire:
The most complete version of a falling sand game that I found is The Powder Toy. It simulates a truckload of elements and also takes into account pressure, velocity, heat and much more. There's a sharing feature with lots of interesting creations to discover.
The code is open source and available on GitHub (MIT License).
Back to top