xxxxxxxxxx
67
// game of life shader
//
// An example sketch showing the p5.filterShader library
// https://github.com/BarneyWhiteman/p5.filterShader
let golShader;
let screen;
const cellSize = 5;
let paused = false;
// load in the shader
function preload() {
golShader = loadShader('gol.vert', 'gol.frag');
}
function setup() {
createCanvas(600, 600);
pixelDensity(1);
noSmooth();
screen = createGraphics(width/cellSize, height/cellSize);
screen.pixelDensity(1);
screen.noSmooth();
screen.background(0);
screen.stroke(255);
screen.fill(255);
screen.strokeWeight(1);
}
function draw() {
// Draw a line on the canvas if the mouse is pressed
if(mouseIsPressed) {
const x1 = round(pmouseX/cellSize);
const y1 = round(pmouseY/cellSize);
const x2 = round(mouseX/cellSize);
const y2 = round(mouseY/cellSize);
if(x1 == x2 && y1 == y2) {
screen.point(x1, y1);
} else {
screen.line(x1, y1, x2, y2);
}
}
// Apply the game of life shader
// Note: we didn't clear the canvas or draw a background
// so the output of the last shader is fed into the input
// of the next shader, allowing the simulation to work
if(!paused) {
screen.filterShader(golShader);
}
image(screen, 0, 0, width, height);
}
function keyReleased() {
if(key == " ") {
paused = !paused;
}
}