• Stars
    star
    148
  • Rank 249,983 (Top 5 %)
  • Language
    JavaScript
  • License
    Other
  • Created almost 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Interactive reaction-diffusion simulation with organic patterns and behaviors that emerge from the interactions of two chemicals mixed together.
The text 'Reaction Diffusion Playground' in a wavy font over a black background with small green dots.

Grid of 12 screenshots, 4 columns and 3 rows, with the text Reaction Diffusion Playground overlaid on top.

What is reaction-diffusion?

Reaction-diffusion is a mathematical model describing how two chemicals might react to each other as they diffuse through a medium together. It was proposed by Alan Turing in 1952 as a possible explanation for how the interesting patterns of stripes and spots that are seen on the skin/fur of animals like giraffes and leopards form.

The reaction-diffusion equations really only describes how the concentrations of the chemicals change over time, which means that all of the interesting patterns and behaviors that we see are emergent phenomena.

Here's what the equations look like:

The two reaction-diffusion differential equations with boxes around each part, explained in text bubbles nearby.

Credit to Karl Sims for the equation illustration above.

The most important terms, the ones we'll want to turn into tweakable parameters, are:

  • f - feed rate. Determines how much of chemical A is added to the system in each iteration.
  • k - kill rate. Determines how much of chemical B is removed from the system in each iteration.
  • dA - diffusion rate for chemical A. Determines how much chemical A spreads to neighboring cells each iteration.
  • dB - diffusion rate for chemical B. Determines how much of chemical B spreads to neighboring cells each iteration.

The other terms in the equation are usually kept constant, but might be worth playing around with once you are comfortable with the core parameters:

  • βˆ‡2 - the Laplacian operator. Essentially a single value that represents the chemical concentration of the neighbors to the current cell.
  • AB2 - reaction rate. Note that it is subtracted in the equation for chemical A and added in the equation for chemical B. This is how the chemical reaction converting chemical A into chemical B is modelled.
  • Ξ”t - timestep. Using 1.0 here means it runs at "normal" speed. Smaller values are like slow motion, and larger values make it run faster. Large values can cause the system to collapse.

Learn more about reaction-diffusion in my morphogenesis-resources repo.

How does this project work?

Most reaction-diffusion simulations store values representing the concentrations of the two chemicals (A and B) in a 2D grid format, then applies the reaction-diffusion equations to each cell in the grid. In this simulation, data textures matching the size of the screen (canvas) are used for the 2D grid, and custom shaders are used to apply the reaction-diffusion equations to each pixel (texel) of these textures.

Each pixel/texel of the simulation data texture encodes the A and B concentrations for that location in the R and G channels as a normalized float value ([0.0-1.0]).

In each frame of the simulation, a custom fragment shader (./glsl/simulationFrag.glsl) reads the values of the last frame's data texture as an input and applies the reaction-diffusion equation to every pixel. Data textures are rendered back and forth between two render targets many times per frame with a technique called ping-pong to speed things up.

Once the simulation has been run enough times, another fragment shader (./glsl/displayFrag.glsl) reads the latest data texture and maps the chemical concentration data to color values (configurable in the UI).

Just about every option you see in the UI controls one or more uniforms that get passed to these fragment shaders to influence the reaction-diffusion equations or the way the data texture information is translated into colors.

Using the app

Annotated screenshot of the UI

Equation parameters

Each of the four fundamental parameters of the reaction-diffusion equation (f, k, dA, dB), along with the timestep increment, can be changed using the sliders found at the top of the right panel. Change them gradually to avoid collapsing the system.

Interactive parameter map

Screenshot of interactive parameter mapUse this map to navigate through the parameter space easily and find areas with interesting patterns and behaviors. k values are plotted along the X axis, f values along the Y axis.

Use the crosshairs attached to the mouse position to navigate to a region you're interested in, then click to set the main f and k values to match where you clicked.

This map is inspired by the work of Robert Munafo.

Seed pattern

Choose a pattern to use in the first frame of the simulation to seed the reaction. Each pattern has some additional options you can play with for different effects.

  • Circle - radius.
  • Square - width, height, scale, and rotation.
  • Text - string, size, rotation.
  • Image - upload an image from your computer, fit, scale, rotation.

Also provides buttons to reset the simulation with the selected pattern or clear the canvas completely.

Rendering style

Control how the chemical concentration data is translated into visuals.

Canvas size

Set the width and height of the simulation area.

You can also maximize the canvas to fit the entire viewport.

Global actions

Buttons to pause/play or export an image of the current state of the simulation area.

Style map

Upload an image from your computer to vary the f, k, dA, and dB values based on the brightness value of each pixel. The secondary values you choose here will become endstops in an interpolation calculation with the primary values (on the right UI pane). In other words, the four equation parameters will be interpolated to be between the original parameter values (on the right pane) and these secondary parameter values (left pane) using the brightness value of each pixel.

In addition to the reaction-diffusion equation parameters, you can also adjust the uniform scale, rotation, and X/Y offset of the image for different effects.

Your image will automatically be scaled to fit the entire canvas, so it may be stretched. Resize your image to match the width and height of the canvas (or at least its aspect ratio) to minimize distortion.

Bias

Normally diffusion occurs evenly in all directions due to the default radially symmetrical Laplacian stencil. Using this X/Y pad you can "weight" this stencil to cause diffusion to favor one particular direction.

Keyboard controls

  • Space = pause/play.
  • r = reset using the currently-selected seed pattern.
  • s = save an image of the current canvas content.
  • u = show/hide the UI.

Mouse controls

Click and drag anywhere on the canvas to increase the concentration of the B chemical around the mouse position.

Use your mouse wheel to change the diameter of the area affected by clicking / dragging. The size of the brush is indicated with a circle that follows the mouse.

MIDI controls

If you have an Akai LPD8 Wireless or a Novation Launch Control XL, mappings are provided for the various pads and knobs. See ./js/midi.js for details.

Technical notes

Setting up and running locally

  1. Run npm install to get all packages.
  2. Run npm run serve to start up Webpack and launch the application in a live-reloading browser window.

Technologies used

  • ThreeJS for WebGL conveniences like running custom shaders and managing uniforms.
  • GLSL shaders for running the reaction-diffusion equation for every pixel of the screen and rendering.
  • Vanilla ES6 JavaScript.
  • MIDI support using WebMidi.js.
  • Webpack build system with live-reloading dev server.
  • Github Pages to serve the files.

Architecture and file structure

JavaScript

The most important file is entry.js - that's where the environment, UI, and the simulation itself are set up, and where the main update loop is. It sets up a ThreeJS environment with an orthographic camera and a scene containing a plane mesh that is oriented perpendicular to the camera so that it appears 2D.

In the ./js folder are a bunch of modules split into files (all referenced in one way or another through entry.js):

  • export.js - helper functions for downloading the canvas content as an image file.
  • firstFrame.js - helper functions for seeding the first frame of the simulation with interesting patterns.
  • keyboard.js - global keyboard commands.
  • map.js - handles the modal dialog containing the interactive parameter map picker.
  • materials.js - ThreeJS materials that associate uniforms with custom shaders. These get attached to the render targets and plane mesh to run and render the simulation.
  • midi.js - mappings for MIDI controllers (Akai LPD8 Wireless and Novation Launch Control XL).
  • mouse.js - mouse controls.
  • parameterMetadata.js - limits and initial values for each of the parameters controlled by the UI.
  • parameterPresets.js - presets for the main equation parameters (f, k, dA, dB).
  • parameterValues.js - variables controlled by the UI.
  • renderTargets.js - invisible buffers that allow us run the simulation multiple times per frame while only rendering data to the screen once.
  • stats.js - FPS and iteration counters.
  • ui.js - UI built with Tweakpane.
    • ui/left-pane.js - left side of the UI, with style map and bias controls.
    • ui/right-pane.js - right side of the UI, with equation parameters, seeding, and rendering options.
  • uniforms.js - variables that are passed into shaders.

GLSL

In the ./glsl folder are:

  • displayFrag.glsl - turns chemical concentration data textures into colorful pixels for the screen using a variety of techniques.
  • displayVert.glsl - passes vertex data onto the displayFrag.glsl shader with no modifications.
  • passthroughFrag.glsl - takes a passed texture and renders it as-is to the render targets to create a first frame of data for the simulation to work with.
  • passthroughVert.glsl - passes vertex data onto the displayFrag.glsl shader with no modifications.
  • simulationFrag.glsl - takes a passed texture of encoded chemical concentration data and applies the reaction-diffusion equation to each pixel, spitting out a new texture of data to be rendered to the screen or fed into another simulation pass.
  • simulationVert.glsl - passes vertex data along with precomputed texel neighbor coordinates so that they can be automatically interpolated for use in the frag shader.

References

Fundamentals

These papers, articles, and videos helped me understand how the reaction-diffusion algorithm works.

Code

These articles, repos, and project pages helped me figure out how to build my implementation.

Creative

These projects inspired me to explore some of the creative possibilities of reaction-diffusion.

More Repositories

1

morphogenesis-resources

Resources on the topic of digital morphogenesis (creating form with code). Includes links to major articles, code repos, creative projects, books, software, and more.
1,997
star
2

2d-differential-growth-experiments

Visual experiments exploring differential growth as a 2D morphogenesis tool.
JavaScript
229
star
3

2d-space-colonization-experiments

Visual experiments exploring space colonization as a 2D morphogenesis tool.
JavaScript
188
star
4

SuperformulaSVG-for-web

A generative line art web app using the 2D superformula, with support for SVG and raster exporting.
JavaScript
69
star
5

SurfaceMapperGUI

A simple projection mapping interface using Processing's SurfaceMapper and ControlP5 libraries.
HTML
64
star
6

2d-diffusion-limited-aggregation-experiments

Visual experiments exploring diffusion-limited aggregation (DLA) as a 2D morphogenesis tool.
JavaScript
59
star
7

SuperformulaSVG

2D superformula line-art generator built in Processing, with SVG export for use in digital fabrication workflows.
Processing
51
star
8

2d-voronoi-experiments

Visual experiments exploring 2D voronoi diagrams for simple diatom/radiolaria patterns.
JavaScript
28
star
9

Genmitsu-PROVerXL-4030-Enclosure

Parts lists and CAD files for a DIY aluminum extrusion enclosure with a slide-out drawer and a table for the 4030 CNC router.
20
star
10

cellular-automata-explorer

(WIP) An interactive web app for exploring cellular automata.
JavaScript
18
star
11

tc-maker-4x4-router

Restoration and documentation of custom-built 4x4' CNC router at Twin Cities Maker hackerspace (aka the Hack Factory) in Minneapolis, MN.
C
15
star
12

Jar-of-Fireflies

Mason jar with interactive LEDs that mimic fireflies on a warm summer night, realized with an Arduino-enabled ATTiny85, multiple power options and a sensor interface.
C++
14
star
13

dashboard-for-everybody

Demo project of a real-time data dashboard showing effective design and dev techniques for making complex interfaces accessible for people with disabilities
HTML
13
star
14

openSipPuff

Simple, low-cost "sip and puff" USB interface for expressive interactions, enabling breath-based control of keypresses, mouse actions and much more using USB HID.
C++
11
star
15

unity-space-colonization

Unity implementation of the space colonization algorithm to generate organic branching structures.
C#
11
star
16

revealjs-subtitles

A Reveal.js plugin to add real-time subtitles to presentations
JavaScript
7
star
17

wall-plotter

Interactive wall plotter platform
5
star
18

superformulabot

A generative art Twitter bot using the 2D superformula. Tweets new drawings every couple hours, and responds to @mentions with custom drawings.
JavaScript
4
star
19

dla-sandbox-for-unity

Unity project exploring 3D diffusion-limited aggregation (DLA) with high-res photogrammetry scans
C#
3
star
20

flat-pack-corner-table

Design files and documentation for a custom-designed flat-pack, no-fastener corner table.
3
star
21

How-to-Build-Almost-Anything-Fall-2015

Courseware and student content from "How to Build Almost Anything" course at Metropolitan Community College's FabLab in Omaha, NE
3
star
22

jasonwebb.io-theme

WordPress theme for personal portfolio website
PHP
2
star
23

BacKey-for-MaKey-MaKey

BacKey for MaKey MaKey
2
star
24

Augmented-Reality-Pong

Table-top augmented reality pong using IR markers and projectors
C++
2
star
25

minecraft-interface

Arduino firmware for real-life Minecraft interface
Arduino
2
star
26

PaintingSpinner

Arduino-based hardware platform for interactively spinning a painting using a DC motor.
Arduino
1
star
27

making-the-web-work-for-everyone-talk

Talk on web accessibility for developers (2019)
JavaScript
1
star
28

Lumiboard

Open-source, Bluetooth-enabled, ambient-aware LED controller platform
Arduino
1
star
29

OMEGA-2

Interactive spaceship-themed control panels for OMEGA-2 Burning Man artcar
Eagle
1
star
30

jasonwebb

1
star