|
5 | 5 | fetch("game-of-life.optimized.wast").then(response => response.text()).then(text => { |
6 | 6 |
|
7 | 7 | // Convert it to binary format |
8 | | - var buffer = Binaryen.parseText(text).emitBinary(); |
| 8 | + var binary = Binaryen.parseText(text).emitBinary(); |
9 | 9 |
|
10 | 10 | // Instantiate the module |
11 | | - return WebAssembly.instantiate(buffer, {}); |
12 | | - |
13 | | -}).then(result => { |
14 | | - var module = result.instance; |
| 11 | + var module = new WebAssembly.Module(binary); |
| 12 | + var instance = new WebAssembly.Instance(module, { /* no imports */ }); |
15 | 13 |
|
16 | 14 | // Set up the canvas with a 2D rendering context |
17 | 15 | var cnv = document.getElementById("canvas"); |
|
22 | 20 | S = s + s; // total memory required to store input and output |
23 | 21 |
|
24 | 22 | // Grow the (exported) memory if it's size isn't sufficient |
25 | | - var memory = module.exports.memory; |
| 23 | + var memory = instance.exports.memory; |
26 | 24 | if (memory.buffer.byteLength < S) |
27 | 25 | memory.grow(Math.ceil((S - memory.buffer.byteLength) / 65536)); |
28 | 26 |
|
| 27 | + // Initialize with width and height |
| 28 | + instance.exports.init(w, h); |
| 29 | + |
29 | 30 | // Fill input at [0, s-1] with random cells |
30 | 31 | var mem = new Uint8Array(memory.buffer); |
31 | 32 | for (var y = 0; y < h; ++y) |
32 | 33 | for (var x = 0; x < w; ++x) |
33 | 34 | mem[y * w + x] = Math.random() > 0.1 ? 0 : 1; |
34 | 35 |
|
35 | | - // Initialize with width and height |
36 | | - module.exports.init(w, h); |
37 | | - |
38 | 36 | // Update about 30 times a second |
39 | | - function update() { |
| 37 | + (function update() { |
40 | 38 | setTimeout(update, 33); |
41 | | - module.exports.step(); |
| 39 | + instance.exports.step(); |
42 | 40 | mem.set(mem.subarray(s, S), 0); // copy output -> input |
43 | | - } |
| 41 | + })(); |
44 | 42 |
|
45 | 43 | // Keep rendering the output at [s, 2*s-1] |
46 | | - function render() { |
| 44 | + (function render() { |
47 | 45 | requestAnimationFrame(render); |
48 | 46 | ctx.clearRect(0, 0, w, h); |
49 | 47 | ctx.fillStyle = "#333"; |
50 | 48 | for (var y = 0; y < h; ++y) |
51 | 49 | for (var x = 0; x < w; ++x) |
52 | 50 | if (mem[s + y * w + x]) |
53 | 51 | ctx.fillRect(x, y, 1, 1); |
54 | | - } |
55 | | - |
56 | | - update(); |
57 | | - render(); |
| 52 | + })(); |
58 | 53 |
|
59 | 54 | }).catch(err => { |
60 | 55 | throw err; |
|
0 commit comments