Created
June 25, 2018 11:53
-
-
Save 19h/9e24ab2393abd92eb9a8835e20122dc8 to your computer and use it in GitHub Desktop.
Vector Distance using WebAssembly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log(loadWebAssembly().exports['f64.distance'](1, 2, 3, 4)); | |
function loadWebAssembly(opts) { | |
var imp = opts && opts.imports | |
var wasm = toUint8Array('AGFzbQEAAAABDgJgAX8Bf2AEf39/fwF8AwMCAAEHGQIGc3F1YXJlAAAMZjY0LmRpc3RhbmNlAAEKKQIIACAAIABsDwseAQJ/IAAgAmshBCABIANrIQUgBBAAIAUQAGq3nw8L') | |
var ready = null | |
var mod = { | |
buffer: wasm, | |
memory: null, | |
exports: null, | |
realloc: realloc, | |
onload: onload | |
} | |
onload(function() {}) | |
return mod | |
function realloc(size) { | |
mod.exports.memory.grow(Math.max(0, Math.ceil(Math.abs(size - mod.memory.length) / 65536))) | |
mod.memory = new Uint8Array(mod.exports.memory.buffer) | |
} | |
function onload(cb) { | |
if (mod.exports) return cb() | |
if (ready) { | |
ready.then(cb.bind(null, null)).catch(cb) | |
return | |
} | |
try { | |
if (opts && opts.async) throw new Error('async') | |
setup({ | |
instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp) | |
}) | |
} catch (err) { | |
ready = WebAssembly.instantiate(wasm, imp).then(setup) | |
} | |
onload(cb) | |
} | |
function setup(w) { | |
mod.exports = w.instance.exports | |
mod.memory = mod.exports.memory && mod.exports.memory.buffer && new Uint8Array(mod.exports.memory.buffer) | |
} | |
} | |
function toUint8Array(s) { | |
if (typeof atob === 'function') return new Uint8Array(atob(s).split('').map(charCodeAt)) | |
return (require('buf' + 'fer').Buffer).from(s, 'base64') | |
} | |
function charCodeAt(c) { | |
return c.charCodeAt(0) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(module | |
(func $square | |
(export "square") | |
(param $x i32) | |
(result i32) | |
(return (i32.mul (get_local $x) | |
(get_local $x)) | |
) | |
) | |
(func $f64.distance | |
(export "f64.distance") | |
(param $x1 i32) (param $y1 i32) | |
(param $x2 i32) (param $y2 i32) | |
(result f64) | |
(local $x.dist i32) | |
(local $y.dist i32) | |
(set_local $x.dist (i32.sub (get_local $x1) | |
(get_local $x2))) | |
(set_local $y.dist (i32.sub (get_local $y1) | |
(get_local $y2))) | |
(return (f64.sqrt ( f64.convert_s/i32( | |
i32.add (call $square (get_local $x.dist)) | |
(call $square (get_local $y.dist)))))) | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment