A different kind of computer III: creative coding

· PM-mirror


Most code exists to do a job. It moves money, stores records, answers requests. Creative coding is the other kind: programs whose result is a picture, an animation or a sound, written because the output is interesting to look at or listen to. The program is the brush, and very often the program is also the artwork.

The fantasy consoles from earlier in this series already pointed in this direction. A small machine with 16 colours invites people to draw and make noise with it. Creative coding takes that idea and drops the game around it.

Plotters and the first exhibitions #

People were making art with computers long before screens could show it. In the early 1960s the output device was a pen plotter, a machine that moves a real pen over real paper following instructions from a program. A. Michael Noll started making computer art at Bell Labs in 1962, mixing randomness with order. In February 1965 the Studiengalerie of the Technische Hochschule Stuttgart showed the computer graphics of Georg Nees, one of the first exhibitions of its kind, and Frieder Nake and Noll also showed work that same year.

Vera Molnár, a Hungarian-born artist working in France, began using a computer to create algorithmic drawings in 1968.1 She is considered one of the pioneers of generative art, which is art produced, in whole or in part, by an autonomous system: the artist writes the rules, and the rules make the picture.

One of the best known works from that period is Schotter, by Georg Nees, from 1968.2 It is a grid of squares that starts in perfect order at the top and falls into disorder towards the bottom, as the program adds more and more randomness. It is also a good first exercise.

Order and chaos in twenty lines of Python #

This program draws a grid of 100 squares in the spirit of Schotter. Each row gets more random displacement and rotation than the one above it, and the result is saved as an SVG file, a vector image that any browser can open.

import random
from itertools import product

random.seed(7)
size, cells = 400, 10
step = size / cells
out = ['',
'']

for row, col in product(range(cells), range(cells)):
chaos = row * row / 5
x = col * step + 6 + random.uniform(-chaos, chaos)
y = row * step + 6 + random.uniform(-chaos, chaos)
turn = random.uniform(-chaos, chaos) * 2
out.append(f'<rect x="{x:.0f}" y="{y:.0f}" width="28" height="28" '
f'transform="rotate({turn:.0f} {x + 14:.0f} {y + 14:.0f})"/>')

out.append("")
open("grid.svg", "w").write("\n".join(out))
print(cells * cells, "squares written to grid.svg")

$ python3 grid.py
100 squares written to grid.svg

And this is the file it wrote, shown as it is:

The parts worth understanding:

The usual first mistake in generative art is adding too much randomness. Pure noise is boring to look at. The interesting results come from a strong rule (the grid) with a controlled amount of randomness on top of it.

Processing and p5.js #

For decades this kind of work needed a programmer who also cared about art, or an artist willing to learn a lot of programming. In 2001 Casey Reas and Ben Fry, both from the Aesthetics and Computation Group at the MIT Media Lab, started Processing, a language and editor built to teach programming in a visual context. It is based on Java with the hard parts hidden, and it calls each program a sketch, which says a lot about the intention. In 2012 they founded the Processing Foundation together with Daniel Shiffman, who became the third project lead.

In 2013 Lauren McCarthy created p5.js, which brings the same ideas to JavaScript and runs in any browser. Its site describes it as "a friendly tool for learning to code and make art", and there is a web editor where you can write and run sketches without installing anything.

A p5.js sketch has the same structure as the fantasy consoles from the previous part of this series: setup() runs once, and draw() runs again on every frame.

function setup() {
createCanvas(400, 400);
noFill();
stroke(20, 20, 20, 120);
}

function draw() {
background(250, 247, 240);
for (let i = 0; i < 30; i++) {
let wobble = sin(frameCount * 0.03 + i * 0.25) * 60;
circle(200 + wobble, 200, 40 + i * 10);
}
}

Paste it into the web editor and press play. You will see thirty circles of growing size whose centres slide left and right, each one a little behind the previous one, so the rings fold into each other like a tunnel. This is one frame of it:3

Thirty thin grey circles of growing size on a light background. Their centres slide sideways by different amounts, so the rings bunch together on the left and spread apart on the right, like a tunnel seen at an angle.

The trick is in i * 0.25. Every circle uses the same sin() wave, but each one is shifted a little in time, so they move together without moving the same way. The 120 in stroke() is transparency, which makes the lines darker where they overlap. Small numbers like these are where most of the work in creative coding happens: you change one, run it, look, and change it again.

Shaders: one formula for every pixel #

The sketches above draw shapes one at a time. A shader works the other way around. It is a small program that the graphics card runs for every pixel of the screen at the same time, and its only job is to answer one question: given the position of this pixel, what colour should it be?

That sounds limiting, but whole landscapes, clouds and planets are drawn this way. Shadertoy, created by Inigo Quilez and Pol Jeremias, is the place where people share these programs, and every one of them can be opened, read and edited in the browser.

The idea is easy to try in Python, with NumPy doing for the whole image at once what a shader does per pixel:

import numpy as np
from PIL import Image

w, h = 320, 200
y, x = np.mgrid[0:h, 0:w] / h
d = np.hypot(x - 0.8, y - 0.5)
v = np.sin(d * 40) * 0.5 + 0.5
rgb = np.stack([v * 255, v * 120 + 40, 90 - v * 60], axis=-1)
Image.fromarray(rgb.astype("uint8")).save("rings.png")
print(f"{w * h} pixels, one formula")

$ python3 rings.py
64000 pixels, one formula

Concentric rings in orange and dark blue, centred in the middle of a wide image, fading smoothly from one colour to the other.

d is the distance from each pixel to the point (0.8, 0.5), which is the centre of the image. Passing that distance through sin() turns it into a wave that goes up and down as you move away from the centre, and those waves are the rings. The last line before saving maps the wave to two colours, orange at the top of the wave and dark blue at the bottom.

The same picture written as a shader for Shadertoy looks like this:

void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 p = fragCoord / iResolution.y;
float v = sin(length(p - vec2(0.8, 0.5)) * 40.0) * 0.5 + 0.5;
fragColor = vec4(v, (v * 120.0 + 40.0) / 255.0, (90.0 - v * 60.0) / 255.0, 1.0);
}

Rendered in a browser through WebGL, it produces practically the same image as the Python version.4 Shaders work with colours from 0 to 1 instead of 0 to 255, which is why the divisions by 255 appear. Change the 40.0 to make the rings thinner or thicker, or add iTime inside the sin() on Shadertoy and the rings start to move.

Live coding: code as a performance #

Creative code usually gets written first and shown later. Live coding turns that around: the programmer writes and changes the code in front of an audience, and the music or the visuals change as they type. The screen with the code is often projected so people can watch it being written. TOPLAP, an informal organization for live coding communities, was founded in February 2004, and the events where people dance to live coded music are called algoraves.

A few tools to know:

In Sonic Pi, a drum that keeps playing while you edit the rest of the code is three lines:

live_loop :drums do
sample :bd_haus
sleep 0.5
end

live_loop repeats forever, sample plays a sound that comes with Sonic Pi, and sleep waits half a beat. Change 0.5 to 0.25 and run it again, and the drum doubles its speed without stopping.

Where to start #

The easiest path is to pick one tool and copy something small. The p5.js web editor and Strudel need nothing installed. If you prefer to stay in Python, the grid and the rings above need only NumPy and Pillow, and the Pyxel engine from the previous part of this series works for animation too.

Some habits that help:

If you want a deadline, Genuary happens every January: one prompt per day for "code that makes beautiful things", in any language, and following the prompts is optional. It is a good excuse to make thirty-one small things instead of planning one big one.

Sources #

  1. Vera Molnár died in Paris on 7 December 2023, at 99. She worked with algorithms for more than half a century.

  2. Schotter is German for gravel. Nees made it with a Siemens System 2002 computer. Turning the image upside down reverses the direction, from chaos to order.

  3. The frame was rendered with p5.js 1.11.3 in a browser without a screen, by running the sketch above unchanged and saving the canvas.

  4. Comparing both images pixel by pixel, the largest difference was 19 out of 255 in a single channel, which comes from where each system samples the centre of a pixel. One detail: shaders count rows from the bottom and images from the top, but these rings are symmetric, so the result is the same.