Menu

Maximal Sand

Maximal Sand is an Art program I wrote that simulates falling sand. It is written in C++ and compiled to WebAssembly using Emscripten.

The simulator is written to be multithreaded. But for older browsers that don't support WebAssembly multithreading, the simulator has a single-threaded version that is loaded automatically.

The Simulation is divided into 16x16 chunks, and each chunk can have three states: Clean, Dirty, and Empty.

  • Empty chunk: A chunk with no sand. Skipped each frame.
  • Clean chunk: Has sand, but none is moving. Copied to the next frame each frame.
  • Dirty chunk: Has falling sand. Processed by the simulation.

When sand moves, the chunks it moves to and from are marked as dirty. If a chunk is processed and no sand moves, the chunk is marked as clean. If no sand is detected, the chunk is marked as empty.

To avoid race conditions, threads write to chunks in a checkerboard pattern. This ensures that when a chunk is processing, none of the chunks immediately surrounding it are. This prevents the need for atomics in the simulator's frame buffer.

To handle windows such as the palette window, the simulator includes a full window manager. Windows use a grid layout to scale according to the screen size.

The main window is the background window. It contains the sand simulation and the buttons at the top. You can play the simulator by clicking the button below.