-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (63 loc) · 1.77 KB
/
Copy pathindex.js
File metadata and controls
75 lines (63 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
const WIDTH = 100, HEIGHT = 100, SIZE = WIDTH * HEIGHT;
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = WIDTH;
canvas.height = HEIGHT;
start();
const Controls = {
None: 'Controls.None',
Up: 'Controls.Up',
Right: 'Controls.Right',
Left: 'Controls.Left'
}
let control = Controls.None;
document.addEventListener('keydown', event => {
switch (event.key) {
case "ArrowLeft":
control = Controls.Left;
break;
case "ArrowRight":
control = Controls.Right;
break;
case "ArrowUp":
control = Controls.Up;
break;
case "ArrowDown":
control = Controls.Down;
break;
default:
control = Controls.None;
break;
}
});
document.addEventListener('keyup', event => {
control = Controls.None;
});
async function loadWasm() {
const wasm = await WebAssembly
.instantiateStreaming(fetch('../build/optimized.wasm'), {
Date,
env: {
abort: (_msg, _file, line, column) => console.error(`Abort at ${line}:${column}`),
seed: Date.now
}});
return wasm.instance.exports;
}
async function start() {
const wasm = await loadWasm();
wasm.start();
console.log(wasm)
const mem = new Uint32Array(wasm.memory.buffer); // 32bit => 8bit color * 4 (RGBA)
const imageData = ctx.createImageData(WIDTH, HEIGHT);
const argb = new Uint32Array(imageData.data.buffer);
const updateCall = () => {
update(wasm, mem, imageData, argb);
window.requestAnimationFrame(updateCall);
}
window.requestAnimationFrame(updateCall);
}
function update(wasm, mem, imageData, argb) {
wasm.update(wasm[control]);
argb.set(mem.subarray(0, SIZE)); // copy output to image buffer
ctx.putImageData(imageData, 0, 0); // apply image buffer
}