const WASM_FILE = "./main.wasm"; const W = 640; const H = 360; let mem_in, mem_out; let mem_bg_img; let instance = null; let memoryStates = new WeakMap(); // basic system calls from the wasm module function syscall(instance, n, args) { switch (n) { default: // console.log("Syscall " + n + " NYI."); break; case /* brk */ 45: return 0; case /* writev */ 146: return instance.exports.writev_c(args[0], args[1], args[2]); case /* mmap2 */ 192: debugger; const memory = instance.exports.memory; let memoryState = memoryStates.get(instance); const requested = args[1]; if (!memoryState) { memoryState = { object: memory, currentPosition: memory.buffer.byteLength, }; memoryStates.set(instance, memoryState); } let cur = memoryState.currentPosition; if (cur + requested > memory.buffer.byteLength) { const need = Math.ceil( (cur + requested - memory.buffer.byteLength) / 65536 ); memory.grow(need); } memoryState.currentPosition += requested; return cur; } } const initWASM = () => fetch(WASM_FILE) .then((response) => response.arrayBuffer()) .then((bytes) => WebAssembly.instantiate(bytes, { env: { __syscall0: function __syscall0(n) { return syscall(instance, n, []); }, __syscall1: function __syscall1(n, a) { return syscall(instance, n, [a]); }, __syscall2: function __syscall2(n, a, b) { return syscall(instance, n, [a, b]); }, __syscall3: function __syscall3(n, a, b, c) { return syscall(instance, n, [a, b, c]); }, __syscall4: function __syscall4(n, a, b, c, d) { return syscall(instance, n, [a, b, c, d]); }, __syscall5: function __syscall5(n, a, b, c, d, e) { return syscall(instance, n, [a, b, c, d, e]); }, __syscall6: function __syscall6(n, a, b, c, d, e, f) { return syscall(instance, n, [a, b, c, d, e, f]); } } }) ) .then((results) => { instance = results.instance; // instruct the module to allocate the shared buffers const in_p = instance.exports.init_in(W, H); const out_p = instance.exports.init_out(); const bg_p = instance.exports.init_bg_img(); // create byte type view buffers mem_in = new Uint8Array( instance.exports.memory.buffer, in_p, W * H * 1.5 ); mem_out = new Uint8Array( instance.exports.memory.buffer, out_p, W * H * 4 ); mem_bg_img = new Uint8Array( instance.exports.memory.buffer, bg_p, W * H * 4 ); }) .catch(console.error);