Skip to content

Update game-of-life example #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions game-of-life/asconfig.json
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
{
"options": {
"runtime": "stub",
"use": "Math=JSMath",
"importMemory": true,
"sourceMap": true,
"measure": true
},
"targets": {
"options": {
"runtime": "stub",
"sourceMap": true,
"measure": true
},
"debug": {
"outFile": "build/untouched.wasm",
"textFile": "build/untouched.wat",
"use": "Math=JSMath",
"importMemory": true,
"outFile": "build/debug.wasm",
"textFile": "build/debug.wat",
"debug": true
},
"release": {
"outFile": "build/optimized.wasm",
"textFile": "build/optimized.wat",
"use": "Math=JSMath",
"importMemory": true,
"outFile": "build/release.wasm",
"textFile": "build/release.wat",
"optimizeLevel": 3,
"converge": false,
"shrinkLevel": 0,
"noAssert": false
"noAssert": true
}
}
}
3 changes: 3 additions & 0 deletions game-of-life/assembly/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,21 @@ import { BGR_ALIVE, BGR_DEAD, BIT_ROT } from "./config";
var width: i32, height: i32, offset: i32;

/** Gets an input pixel in the range [0, s]. */
// @ts-ignore: decorator
@inline
function get(x: u32, y: u32): u32 {
return load<u32>((y * width + x) << 2);
}

/** Sets an output pixel in the range [s, 2*s]. */
// @ts-ignore: decorator
@inline
function set(x: u32, y: u32, v: u32): void {
store<u32>((offset + y * width + x) << 2, v);
}

/** Sets an output pixel in the range [s, 2*s] while fading it out. */
// @ts-ignore: decorator
@inline
function rot(x: u32, y: u32, v: u32): void {
var alpha = max<i32>((v >> 24) - BIT_ROT, 0);
Expand Down
2 changes: 1 addition & 1 deletion game-of-life/build/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
*
!.gitignore
!optimized.wasm
!release.wasm
Binary file not shown.
95 changes: 52 additions & 43 deletions game-of-life/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,19 +31,19 @@ <h1>
const BIT_ROT = 10;

// Set up the canvas with a 2D rendering context
var cnv = document.getElementsByTagName("canvas")[0];
var ctx = cnv.getContext("2d");
var bcr = cnv.getBoundingClientRect();
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
var bcr = canvas.getBoundingClientRect();

// Compute the size of the universe (here: 2px per cell)
var width = bcr.width >>> 1;
var height = bcr.height >>> 1;
var size = width * height;
var byteSize = (size + size) << 2; // input & output (here: 4b per cell)
var width = bcr.width >>> 1;
var height = bcr.height >>> 1;
var size = width * height;
var byteSize = (2 * size) << 2; // input & output (here: 4b per cell)

cnv.width = width;
cnv.height = height;
cnv.style = `
canvas.width = width;
canvas.height = height;
canvas.style = `
image-rendering: optimizeSpeed;
image-rendering: -moz-crisp-edges;
image-rendering: -webkit-optimize-contrast;
Expand All @@ -56,21 +56,23 @@ <h1>
ctx.imageSmoothingEnabled = false;

// Compute the size of and instantiate the module's memory
var memory = new WebAssembly.Memory({ initial: ((byteSize + 0xffff) & ~0xffff) >>> 16 });
var memory = new WebAssembly.Memory({
initial: ((byteSize + 0xffff) & ~0xffff) >>> 16
});

// Fetch and instantiate the module
fetch("build/optimized.wasm")
fetch("build/release.wasm")
.then(response => response.arrayBuffer())
.then(buffer => WebAssembly.instantiate(buffer, {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't you use WebAssembly.instantiateStreaming()?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instantiateStreaming doesn't support on Safari yet. Or support only in the latest WebKit. So for simplicity better to use non-streamed version

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In that case, the interference example also uses instantiateStreaming(). Shouldn't that be changed then?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I think it's worth it

env: {
memory,
abort: function() {},
abort() {},
"Math.random": Math.random
},
config: {
BGR_ALIVE : rgb2bgr(RGB_ALIVE) | 1, // little endian, LSB must be set
BGR_DEAD : rgb2bgr(RGB_DEAD) & ~1, // little endian, LSB must not be set
BIT_ROT
BIT_ROT,
BGR_ALIVE: rgb2bgr(RGB_ALIVE) | 1, // little endian, LSB must be set
BGR_DEAD: rgb2bgr(RGB_DEAD) & ~1, // little endian, LSB must not be set
},
}))
.then(module => {
Expand All @@ -84,45 +86,52 @@ <h1>
// Update about 30 times a second
(function update() {
setTimeout(update, 1000 / 30);
mem.copyWithin(0, size, size + size); // copy output to input
exports.step(); // perform the next step
mem.copyWithin(0, size, 2 * size); // copy output to input
exports.step(); // perform the next step
})();

// Keep rendering the output at [size, 2*size]
var imageData = ctx.createImageData(width, height);
var argb = new Uint32Array(imageData.data.buffer);

(function render() {
requestAnimationFrame(render);
argb.set(mem.subarray(size, size + size)); // copy output to image buffer
ctx.putImageData(imageData, 0, 0); // apply image buffer
argb.set(mem.subarray(size, 2 * size)); // copy output to image buffer
ctx.putImageData(imageData, 0, 0); // apply image buffer
})();

// When clicked or dragged, fill the current row and column with random live cells
var down = false;
[ [cnv, "mousedown"],
[cnv, "touchstart"]
].forEach(eh => eh[0].addEventListener(eh[1], e => down = true));
[ [document, "mouseup"],
[document, "touchend"]
].forEach(eh => eh[0].addEventListener(eh[1], e => down = false));
[ [cnv, "mousemove"],
[cnv, "touchmove"],
[cnv, "mousedown"]
].forEach(eh => eh[0].addEventListener(eh[1], e => {
if (!down) return;
var loc;
if (e.touches) {
if (e.touches.length > 1) return;
loc = e.touches[0];
} else {
loc = e;
}
var bcr = cnv.getBoundingClientRect();
exports.fill((loc.clientX - bcr.left) >>> 1, (loc.clientY - bcr.top) >>> 1, 0.5);
}));
let down = false;
for (const ty of ["mousedown", "touchstart"]) {
canvas.addEventListener(ty, e => down = true);
}
for (const ty of ["mouseup", "touchend"]) {
document.addEventListener(ty, e => down = false);
}
for (const ty of ["mousemove", "touchmove", "mousedown"]) {
canvas.addEventListener(ty, e => {
if (!down) return;
const touches = e.touches;
let loc;
if (touches) {
if (touches.length > 1) return;
loc = touches[0];
} else {
loc = e;
}
const rect = canvas.getBoundingClientRect();
exports.fill(
(loc.clientX - rect.left) >>> 1,
(loc.clientY - rect.top) >>> 1,
0.5
);
});
}

// :-(
if (navigator.userAgent.indexOf(" Edge/") >= 0) document.getElementById("edge").style.display = "block";
if (navigator.userAgent.includes(" Edge/")) {
document.getElementById("edge").style.display = "block";
}
}).catch(err => {
alert("Failed to load WASM: " + err.message + " (ad blocker, maybe?)");
console.log(err.stack);
Expand Down
6 changes: 3 additions & 3 deletions game-of-life/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
"license": "Apache-2.0",
"private": true,
"scripts": {
"asbuild:untouched": "asc assembly/index.ts --target debug",
"asbuild:optimized": "asc assembly/index.ts --target release",
"asbuild": "npm run asbuild:untouched && npm run asbuild:optimized",
"asbuild:debug": "asc assembly/index.ts --target debug",
"asbuild:release": "asc assembly/index.ts --target release",
"asbuild": "npm run asbuild:debug && npm run asbuild:release",
"start": "npx serve"
},
"devDependencies": {
Expand Down