Skip to content

Koch snowflake with matrices

As the quip goes: when I wrote this code, only I and God knew what how it works. Now only God knows.

Looking at it today, it seems like like the code takes the list of points forming a Koch Snowflake, and passes them through a series of transformation matrices to get a new list of points. Can one do that? Who knows! Does it work? Apparently! Why do the points themselves have 6 coordinates? Maybe they are triangles! Ask them yourself! hmph

...At least the deep dark blue is nice 😁

A Koch snowflake against a deep blue background.

function setup() {
  let c = createCanvas(windowWidth, windowHeight);
  pixelDensity(1)
  let sq3 = sqrt(3)
  // Here be dragons
  const transforms = [
    [1 / 3, 0, 0, 1 / 3, 0, 0],
    [0.5 / 3, sq3 / 2 / 3, -sq3 / 2 / 3, 0.5 / 3, 1, 0],
    [0.5 / 3, -sq3 / 2 / 3, sq3 / 2 / 3, 0.5 / 3, 1.5, sq3 / 2],
    [1 / 3, 0, 0, 1 / 3, 2, 0],
  ]
  let initial = [
    [0.5 / 3, sq3 / 2 / 3, -sq3 / 2 / 3, 0.5 / 3, -0.5, -sq3 / 6],
    [0.5 / 3, -sq3 / 2 / 3, sq3 / 2 / 3, 0.5 / 3, 0, sq3 / 3],
    [-1 / 3, 0, 0, -1 / 3, 0.5, -sq3 / 6],
  ]
  function trmul(a, b) {
    // More dragons
    return [
      a[0] * b[0] + a[1] * b[2], a[0] * b[1] + a[1] * b[3],
      a[2] * b[0] + a[3] * b[2], a[2] * b[1] + a[3] * b[3],
      a[4] * b[0] + a[5] * b[2] + b[4], a[4] * b[1] + a[5] * b[3] + b[5],
    ]
  }
  let newT = initial
  for (let i = 0; i < 5; i ++) {
    newT = newT.flatMap(x => transforms.map(t => trmul(t, x)))
  }
  background(45, 40, 90)
  stroke(255)
  fill(220)
  translate(width / 2, height / 2)
  for (let i = 0; i < 20; i ++) {
    resetMatrix()
    background(45, 40, 90, 70)
    translate(width / 2, height / 2)
    translate(0, 2 * (19 - i))
    beginShape()
    let r = min(width, height) * 0.8
    for (let t of newT) {
      vertex(t[4] * r, t[5] * r)
    }
    endShape(CLOSE)
  }
}
var windowResized = setup

(Originally seen at https://editor.p5js.org/bojidar-bg/sketches/YcWhVuDBL)

Experiments tagged p5 (52/85)

Experiments on this site (52/85)