Fluid simulation is a great example of simulating natural phenomena using a feedback system. It approximates complex phenomena represented by equations that are very challenging to solve by breaking them down into multiple relatively simple steps of approximations, resulting in intricate and elegant motion.



On this page, we will build a fluid simulation step by step. The demo above is written with GLSL shaders to ensure high performance. However, for learning purposes, we will create a miniature simulation using p5.js.


Explaining fluid simulation can involve a lot of math and physics, but I will try to keep it at a high level and intuitive as much as possible. For more detailed explanation, I highly recommend reading Jamie Wong's article, "Fluid Simulation (with WebGL demo)”, which provides a more precise yet friendly breakdown of the topic.

流体シミュレーションを説明するにはかなりの数学と物理が必要ですが、ここではできるだけ直感的に説明しようと思います。より詳しく知りたい方は、Jamie Wongの記事「Fluid Simulation (with WebGL demo)」がとても正確かつ親切なのでオススメです。

Moving colors(paints)


First, we will define the space as a grid of cells. We want to smoothly move paints, or different colors, around in this space. To do this, we will use two maps, specifically two 2D arrays, to capture the information for each cell. The color map stores the color values of each cell, while the velocity map stores a vector that represents the velocity, i.e. the information about the speed and direction of the water flow in each cell.


To move the colors, we will add the opposite vector of the velocity to the position of each cell and sample the color from that point. The idea is that the color at the sampled point will move to the position of the cell in the next frame. Typically, the sampling point is located in the middle of four cells, so we will interpolate the colors between these cells. Also, for this implementation, we assume that the top edge and the bottom edge, as well as the left edge and the right edge, are connected. This means that the sampling position will wrap around to the opposite side of the canvas if it goes out of bounds.