94 lines
2.4 KiB
JavaScript
94 lines
2.4 KiB
JavaScript
import { Universe, Cell } from "rust-wasm";
|
|
import { memory } from "rust-wasm/rust_wasm_bg";
|
|
|
|
const CELL_SIZE = 5; // px
|
|
const GRID_COLOR = "#CCCCCC";
|
|
const COLOURS = ["#FFF", "#FF8", "#FF0", "#F80", "#F00", "#800", "#000"];
|
|
|
|
// Construct the universe, and get its width and height.
|
|
const universe = Universe.new();
|
|
universe.init();
|
|
const width = universe.width();
|
|
const height = universe.height();
|
|
|
|
// Give the canvas room for all of our cells and a 1px border
|
|
// around each of them.
|
|
const infochaos = document.getElementById("chaos");
|
|
const infomax = document.getElementById("max");
|
|
const infoavg = document.getElementById("avg");
|
|
var maxstress = 0;
|
|
var avgstress = 31000;
|
|
const canvas = document.getElementById("game-of-life-canvas");
|
|
canvas.height = (CELL_SIZE + 1) * height + 1;
|
|
canvas.width = (CELL_SIZE + 1) * width + 1;
|
|
|
|
const ctx = canvas.getContext('2d');
|
|
|
|
const renderLoop = () => {
|
|
universe.tick();
|
|
|
|
//drawGrid();
|
|
drawCells();
|
|
|
|
const st = universe.stress();
|
|
if (st > maxstress) maxstress = st;
|
|
avgstress = 0.999 * avgstress + 0.001 * st
|
|
infochaos.innerHTML = st;
|
|
infomax.innerHTML = maxstress;
|
|
infoavg.innerHTML = Math.round(avgstress);
|
|
|
|
// setTimeout(renderLoop, 200);
|
|
requestAnimationFrame(renderLoop);
|
|
};
|
|
|
|
// setTimeout(renderLoop, 1);
|
|
requestAnimationFrame(renderLoop);
|
|
|
|
const drawGrid = () => {
|
|
ctx.beginPath();
|
|
ctx.strokeStyle = GRID_COLOR;
|
|
|
|
// Vertical lines.
|
|
for (let i = 0; i <= width; i++) {
|
|
ctx.moveTo(i * (CELL_SIZE + 1) + 1, 0);
|
|
ctx.lineTo(i * (CELL_SIZE + 1) + 1, (CELL_SIZE + 1) * height + 1);
|
|
}
|
|
|
|
// Horizontal lines.
|
|
for (let j = 0; j <= height; j++) {
|
|
ctx.moveTo(0, j * (CELL_SIZE + 1) + 1);
|
|
ctx.lineTo((CELL_SIZE + 1) * width + 1, j * (CELL_SIZE + 1) + 1);
|
|
}
|
|
|
|
ctx.stroke();
|
|
};
|
|
|
|
const getIndex = (row, column) => {
|
|
return row * width + column;
|
|
};
|
|
|
|
const drawCells = () => {
|
|
const cellsPtr = universe.cells();
|
|
const cells = new Uint8Array(memory.buffer, cellsPtr, width * height);
|
|
|
|
ctx.beginPath();
|
|
|
|
for (let row = 0; row < height; row++) {
|
|
for (let col = 0; col < width; col++) {
|
|
const idx = getIndex(row, col);
|
|
const rat = Math.round(COLOURS.length * cells[idx] / 101);
|
|
const colour = COLOURS[rat];
|
|
|
|
ctx.fillStyle = colour;
|
|
|
|
ctx.fillRect(
|
|
col * (CELL_SIZE + 1) + 1,
|
|
row * (CELL_SIZE + 1) + 1,
|
|
CELL_SIZE,
|
|
CELL_SIZE
|
|
);
|
|
}
|
|
}
|
|
|
|
ctx.stroke();
|
|
};
|