xxxxxxxxxx
128
// Let's make things faster
// What if:
// the grain of sand get pour from the top and fall down?
// there is a force affecting the grain of sand?
let img;
let slider;
let sandpiles;
let nextpiles;
let defaultColor = [30, 30, 30];
let colors = [
[255, 255, 255],
[30, 30, 30],
[90, 90, 90],
[170, 170, 170]
];
function preload() {
img = loadImage('image3.jpg');
}
function setup() {
createCanvas(800, 800); // make a big canvas
pixelDensity(1.0);
image(img, 0, 0, width, height);
sandpiles = new Array(width).fill().map(i => new Array(height).fill(0));
nextpiles = new Array(width).fill().map(i => new Array(height).fill(0));
slider = createSlider(0, 255, 255);
slider.position(10, 10);
slider.style('width', '80px');
//sandpiles[width / 2][height / 2] = 1000000000;
//sandpiles[width / 4][height / 4] = 1000000000; // add more sand
}
function topple() {
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
nextpiles[x][y] = sandpiles[x][y];
}
}
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
let num = sandpiles[x][y];
if (num >= 4) {
nextpiles[x][y] -= 4;
if (x + 1 < width) nextpiles[x + 1][y]++;
if (x - 1 >= 0) nextpiles[x - 1][y]++;
if (y + 1 < height) nextpiles[x][y + 1]++;
if (y - 1 >= 0) nextpiles[x][y - 1]++;
}
}
}
let tmp = sandpiles;
sandpiles = nextpiles;
nextpiles = tmp;
}
function render() {
loadPixels();
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
let num = sandpiles[x][y];
let col = defaultColor;
if (num == 0) {
col = colors[0];
} else if (num == 1) {
col = colors[1];
} else if (num == 2) {
col = colors[2];
} else if (num == 3) {
col = colors[3];
}
let pix = (x + y * width) * 4;
pixels[pix] = col[0];
pixels[pix + 1] = col[1];
pixels[pix + 2] = col[2];
}
}
updatePixels();
}
function draw() {
let sliderVal = slider.value();
image(img, 0, 0);
loadPixels();
const d = pixelDensity();
for (let x = 0; x < width; x++) {
for (let y = 0; y < height; y++) {
const i = 4 * d * (y * d * width + x);
const [r, g, b] = [pixels[i], pixels[i + 1], pixels[i + 2]]; // get colors
if (r >= sliderVal && b >= sliderVal && g >= sliderVal) { // if r g b all less than 80 then color will appear black
sandpiles[x][y] = 1000;
}
}
}
noTint();
image(img, 0, 0, width, height);
tint(255, 230);
render();
//image(img, 0, 0,width,height);
blend(img, 0, 0, width, height, 0, 0, width, height, DIFFERENCE);
// make things move faster
for (let i = 0; i < 50; i++) {
topple();
}
}
// function mousePressed() {
// sandpiles[mouseX][mouseY] = 1000;
// }