xxxxxxxxxx
71
// Bumpmap with the help of ChatGPT, but changed and optimized, removing function()s. Could be more easily ported to oldschool platforms :). I think I know how it works now.
let img;
let lightPosX, lightPosY, lightPosZ;
let ynorm, xnorm, znorm;
function preload() {
// Load a grayscale image to use as a height map
img = loadImage("images/bumpmap2023.png");
}
function setup() {
createCanvas(img.width, img.height);
img.loadPixels();
// initial light settings
lightPosX = width / 2;
lightPosY = height / 2;
lightPosZ = 30; // brightness
pixelDensity(1); // needed in some browsers
}
function draw() {
background(0);
loadPixels();
let moveX = (sin(frameCount * 0.05) * img.width) / 2;
let moveY = (cos(frameCount * 0.01) * img.width) / 3;
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
let idx = (x + y * img.width) * 4;
// Here's where the bumpmap magic happens
let left = img.pixels[(x - 1 + y * img.width) * 4] / 255;
let right = img.pixels[(x + 1 + y * img.width) * 4] / 255;
let up = img.pixels[(x + (y - 1) * img.width) * 4] / 255;
let down = img.pixels[(x + (y + 1) * img.width) * 4] / 255;
let dx = right - left;
let dy = down - up;
let norX = -dx;
let norY = -dy;
let norZ = 1; // size of lightsource
// There's where the magic happened
let lightDirX = lightPosX - (x + moveX);
let lightDirY = lightPosY - (y + moveY);
let lightDirZ = lightPosZ;
let lightnorm = Math.sqrt(
lightDirX * lightDirX + lightDirY * lightDirY + lightDirZ * lightDirZ
);
if (lightnorm > 0) { // avoid division by zero
xnorm = lightDirX / lightnorm;
ynorm = lightDirY / lightnorm;
znorm = lightDirZ / lightnorm;
}
let intensity = xnorm * norX + ynorm * norY + znorm * norZ; //kalkylerar dot-produkt.. schnajz
// Shade pixel based on intensity
let c = intensity * 255;
pixels[idx] = c;
pixels[idx + 1] = c;
pixels[idx + 2] = c;
// pixels[idx + 3] = 255; // Alpha
}
}
updatePixels();
}