UNPKG

pathkit-asmjs

Version:

A asm.js version of Skia's PathOps toolkit

1,322 lines (1,142 loc) 6.65 MB
var PathKitInit = (function() { var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; return ( function(PathKitInit) { PathKitInit = PathKitInit || {}; // Copyright 2010 The Emscripten Authors. All rights reserved. // Emscripten is available under two separate licenses, the MIT license and the // University of Illinois/NCSA Open Source License. Both these licenses can be // found in the LICENSE file. // The Module object: Our interface to the outside world. We import // and export values on it. There are various ways Module can be used: // 1. Not defined. We create it here // 2. A function parameter, function(Module) { ..generated code.. } // 3. pre-run appended it, var Module = {}; ..generated code.. // 4. External script tag defines var Module. // We need to check if Module already exists (e.g. case 3 above). // Substitution will be replaced with actual code on later stage of the build, // this way Closure Compiler will not mangle it (e.g. case 4. above). // Note that if you want to run closure, and also to use Module // after the generated code, you will need to define var Module = {}; // before the code. Then that object will be used in the code, and you // can continue to use Module afterwards as well. var Module = typeof PathKitInit !== 'undefined' ? PathKitInit : {}; // --pre-jses are emitted after the Module integration code, so that they can // refer to Module (if they choose; they can also define Module) // Adds any extra JS functions/helpers we want to the PathKit Library. // Wrapped in a function to avoid leaking global variables. (function(PathKit){ // Caching the Float32Arrays can save having to reallocate them // over and over again. var Float32ArrayCache = {}; // Takes a 2D array of commands and puts them into the WASM heap // as a 1D array. This allows them to referenced from the C++ code. // Returns a 2 element array, with the first item being essentially a // pointer to the array and the second item being the length of // the new 1D array. // // Example usage: // let cmds = [ // [PathKit.MOVE_VERB, 0, 10], // [PathKit.LINE_VERB, 30, 40], // [PathKit.QUAD_VERB, 20, 50, 45, 60], // ]; // // // The following uses ES6 syntactic sugar "Array Destructuring". // // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring // let [ptr, len] = PathKit.loadCmdsTypedArray(cmds); // let path = PathKit.FromCmds(ptr, len); // // If arguments at index 1... in each cmd row are strings, they will be // parsed as hex, and then converted to floats using SkBits2FloatUnsigned PathKit.loadCmdsTypedArray = function(arr) { var len = 0; for (var r = 0; r < arr.length; r++) { len += arr[r].length; } var ta; if (Float32ArrayCache[len]) { ta = Float32ArrayCache[len]; } else { ta = new Float32Array(len); Float32ArrayCache[len] = ta; } // Flatten into a 1d array var i = 0; for (var r = 0; r < arr.length; r++) { for (var c = 0; c < arr[r].length; c++) { var item = arr[r][c]; if (typeof item === 'string') { // Converts hex to an int, which can be passed to SkBits2FloatUnsigned item = PathKit.SkBits2FloatUnsigned(parseInt(item)); } ta[i] = item; i++; } } var ptr = PathKit._malloc(ta.length * ta.BYTES_PER_ELEMENT); PathKit.HEAPF32.set(ta, ptr / ta.BYTES_PER_ELEMENT); return [ptr, len]; } // Experimentation has shown that using TypedArrays to pass arrays from // JS to C++ is faster than passing the JS Arrays across. // See above for example of cmds. PathKit.FromCmds = function(cmds) { var ptrLen = PathKit.loadCmdsTypedArray(cmds); var path = PathKit._FromCmds(ptrLen[0], ptrLen[1]); // TODO(kjlubick): cache this memory blob somehow. PathKit._free(ptrLen[0]); return path; } /** * A common pattern is to call this function in sequence with the same * params. We can just remember the last one to speed things up. * Caching in this way is about a 10-15x speed up. * See externs.js for this definition * @type {CubicMap} */ var cachedMap; var _cpx1, _cpy1, _cpx2, _cpy2; PathKit.cubicYFromX = function(cpx1, cpy1, cpx2, cpy2, X) { if (!cachedMap || _cpx1 !== cpx1 || _cpy1 !== cpy1 || _cpx2 !== cpx2 || _cpy2 !== cpy2) { if (cachedMap) { // Delete previous cached map to avoid memory leaks. cachedMap.delete() } cachedMap = new PathKit._SkCubicMap([cpx1, cpy1], [cpx2, cpy2]); _cpx1 = cpx1, _cpy1 = cpy1, _cpx2 = cpx2, _cpy2 = cpy2; } return cachedMap.computeYFromX(X); } PathKit.cubicPtFromT = function(cpx1, cpy1, cpx2, cpy2, T) { if (!cachedMap || _cpx1 !== cpx1 || _cpy1 !== cpy1 || _cpx2 !== cpx2 || _cpy2 !== cpy2) { if (cachedMap) { // Delete previous cached map to avoid memory leaks. cachedMap.delete() } cachedMap = new PathKit._SkCubicMap([cpx1, cpy1], [cpx2, cpy2]); _cpx1 = cpx1, _cpy1 = cpy1, _cpx2 = cpx2, _cpy2 = cpy2; } return cachedMap.computePtFromT(T); } }(Module)); // When this file is loaded in, the high level object is "Module"; // Adds JS functions to allow for chaining w/o leaking by re-using 'this' path. (function(PathKit){ // PathKit.onRuntimeInitialized is called after the WASM library has loaded. // when onRuntimeInitialized is called, PathKit.SkPath is defined with many // functions on it (see pathkit_wasm_bindings.cpp@EMSCRIPTEN_BINDINGS) PathKit.onRuntimeInitialized = function() { // All calls to 'this' need to go in externs.js so closure doesn't minify them away. PathKit.SkPath.prototype.addPath = function() { // Takes 1, 2, 7 or 10 args, where the first arg is always the path. // The options for the remaining args are: // - an SVGMatrix // - the 6 parameters of an SVG Matrix // - the 9 parameters of a full Matrix var path = arguments[0]; if (arguments.length === 1) { // Add path, unchanged. Use identity matrix this._addPath(path, 1, 0, 0, 0, 1, 0, 0, 0, 1); } else if (arguments.length === 2) { // Takes SVGMatrix, which has its args in a counter-intuitive order // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform#Transform_functions /** * @type {SVGMatrix} */ var sm = arguments[1]; this._addPath(path, sm.a, sm.c, sm.e, sm.b, sm.d, sm.f, 0, 0, 1); } else if (arguments.length === 7) { // User provided the 6 params for an SVGMatrix directly. var a = arguments; this._addPath(path, a[1], a[3], a[5], a[2], a[4], a[6], 0 , 0 , 1 ); } else if (arguments.length === 10) { // User provided the 9 params of a (full) matrix directly. // These are in the same order as what Skia expects. var a = arguments; this._addPath(path, a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9]); } else { console.err('addPath expected to take 1, 2, 7, or 10 args. Got ' + arguments.length); return null; } return this; }; // ccw (counter clock wise) is optional and defaults to false. PathKit.SkPath.prototype.arc = function(x, y, radius, startAngle, endAngle, ccw) { this._arc(x, y, radius, startAngle, endAngle, !!ccw); return this; }; PathKit.SkPath.prototype.arcTo = function(x1, y1, x2, y2, radius) { this._arcTo(x1, y1, x2, y2, radius); return this; }; PathKit.SkPath.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y); return this; }; PathKit.SkPath.prototype.close = function() { this._close(); return this; }; // Reminder, we have some duplicate definitions because we want to be a // superset of Path2D and also work like the original SkPath C++ object. PathKit.SkPath.prototype.closePath = function() { this._close(); return this; }; PathKit.SkPath.prototype.conicTo = function(x1, y1, x2, y2, w) { this._conicTo(x1, y1, x2, y2, w); return this; }; PathKit.SkPath.prototype.cubicTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { this._cubicTo(cp1x, cp1y, cp2x, cp2y, x, y); return this; }; PathKit.SkPath.prototype.dash = function(on, off, phase) { if (this._dash(on, off, phase)) { return this; } return null; }; // ccw (counter clock wise) is optional and defaults to false. PathKit.SkPath.prototype.ellipse = function(x, y, radiusX, radiusY, rotation, startAngle, endAngle, ccw) { this._ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, !!ccw); return this; }; PathKit.SkPath.prototype.lineTo = function(x, y) { this._lineTo(x, y); return this; }; PathKit.SkPath.prototype.moveTo = function(x, y) { this._moveTo(x, y); return this; }; PathKit.SkPath.prototype.op = function(otherPath, op) { if (this._op(otherPath, op)) { return this; } return null; }; PathKit.SkPath.prototype.quadraticCurveTo = function(cpx, cpy, x, y) { this._quadTo(cpx, cpy, x, y); return this; }; PathKit.SkPath.prototype.quadTo = function(cpx, cpy, x, y) { this._quadTo(cpx, cpy, x, y); return this; }; PathKit.SkPath.prototype.rect = function(x, y, w, h) { this._rect(x, y, w, h); return this; }; PathKit.SkPath.prototype.simplify = function() { if (this._simplify()) { return this; } return null; }; PathKit.SkPath.prototype.stroke = function(opts) { // Fill out any missing values with the default values. /** * See externs.js for this definition * @type {StrokeOpts} */ opts = opts || {}; opts.width = opts.width || 1; opts.miter_limit = opts.miter_limit || 4; opts.cap = opts.cap || PathKit.StrokeCap.BUTT; opts.join = opts.join || PathKit.StrokeJoin.MITER; if (this._stroke(opts)) { return this; } return null; }; PathKit.SkPath.prototype.transform = function() { // Takes 1 or 9 args if (arguments.length === 1) { // argument 1 should be a 9 element array (which is transformed on the C++ side // to a SimpleMatrix) this._transform(arguments[0]); } else if (arguments.length === 9) { // these arguments are the 9 members of the matrix var a = arguments; this._transform(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]); } else { console.err('transform expected to take 1 or 9 arguments. Got ' + arguments.length); return null; } return this; }; // isComplement is optional, defaults to false PathKit.SkPath.prototype.trim = function(startT, stopT, isComplement) { if (this._trim(startT, stopT, !!isComplement)) { return this; } return null; }; }; }(Module)); // When this file is loaded in, the high level object is "Module"; // Sometimes an existing Module object exists with properties // meant to overwrite the default module functionality. Here // we collect those properties and reapply _after_ we configure // the current environment's defaults to avoid having to be so // defensive during initialization. var moduleOverrides = {}; var key; for (key in Module) { if (Module.hasOwnProperty(key)) { moduleOverrides[key] = Module[key]; } } Module['arguments'] = []; Module['thisProgram'] = './this.program'; Module['quit'] = function(status, toThrow) { throw toThrow; }; Module['preRun'] = []; Module['postRun'] = []; // Determine the runtime environment we are in. You can customize this by // setting the ENVIRONMENT setting at compile time (see settings.js). var ENVIRONMENT_IS_WEB = false; var ENVIRONMENT_IS_WORKER = false; var ENVIRONMENT_IS_NODE = false; var ENVIRONMENT_IS_SHELL = false; ENVIRONMENT_IS_WEB = typeof window === 'object'; ENVIRONMENT_IS_WORKER = typeof importScripts === 'function'; ENVIRONMENT_IS_NODE = typeof process === 'object' && typeof require === 'function' && !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_WORKER; ENVIRONMENT_IS_SHELL = !ENVIRONMENT_IS_WEB && !ENVIRONMENT_IS_NODE && !ENVIRONMENT_IS_WORKER; if (Module['ENVIRONMENT']) { throw new Error('Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -s ENVIRONMENT=web or -s ENVIRONMENT=node)'); } // Three configurations we can be running in: // 1) We could be the application main() thread running in the main JS UI thread. (ENVIRONMENT_IS_WORKER == false and ENVIRONMENT_IS_PTHREAD == false) // 2) We could be the application main() thread proxied to worker. (with Emscripten -s PROXY_TO_WORKER=1) (ENVIRONMENT_IS_WORKER == true, ENVIRONMENT_IS_PTHREAD == false) // 3) We could be an application pthread running in a worker. (ENVIRONMENT_IS_WORKER == true and ENVIRONMENT_IS_PTHREAD == true) // `/` should be present at the end if `scriptDirectory` is not empty var scriptDirectory = ''; function locateFile(path) { if (Module['locateFile']) { return Module['locateFile'](path, scriptDirectory); } else { return scriptDirectory + path; } } if (ENVIRONMENT_IS_NODE) { scriptDirectory = __dirname + '/'; // Expose functionality in the same simple way that the shells work // Note that we pollute the global namespace here, otherwise we break in node var nodeFS; var nodePath; Module['read'] = function shell_read(filename, binary) { var ret; if (!nodeFS) nodeFS = require('fs'); if (!nodePath) nodePath = require('path'); filename = nodePath['normalize'](filename); ret = nodeFS['readFileSync'](filename); return binary ? ret : ret.toString(); }; Module['readBinary'] = function readBinary(filename) { var ret = Module['read'](filename, true); if (!ret.buffer) { ret = new Uint8Array(ret); } assert(ret.buffer); return ret; }; if (process['argv'].length > 1) { Module['thisProgram'] = process['argv'][1].replace(/\\/g, '/'); } Module['arguments'] = process['argv'].slice(2); // MODULARIZE will export the module in the proper place outside, we don't need to export here process['on']('uncaughtException', function(ex) { // suppress ExitStatus exceptions from showing an error if (!(ex instanceof ExitStatus)) { throw ex; } }); // Currently node will swallow unhandled rejections, but this behavior is // deprecated, and in the future it will exit with error status. process['on']('unhandledRejection', abort); Module['quit'] = function(status) { process['exit'](status); }; Module['inspect'] = function () { return '[Emscripten Module object]'; }; } else if (ENVIRONMENT_IS_SHELL) { if (typeof read != 'undefined') { Module['read'] = function shell_read(f) { return read(f); }; } Module['readBinary'] = function readBinary(f) { var data; if (typeof readbuffer === 'function') { return new Uint8Array(readbuffer(f)); } data = read(f, 'binary'); assert(typeof data === 'object'); return data; }; if (typeof scriptArgs != 'undefined') { Module['arguments'] = scriptArgs; } else if (typeof arguments != 'undefined') { Module['arguments'] = arguments; } if (typeof quit === 'function') { Module['quit'] = function(status) { quit(status); } } } else if (ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) { if (ENVIRONMENT_IS_WORKER) { // Check worker, not web, since window could be polyfilled scriptDirectory = self.location.href; } else if (document.currentScript) { // web scriptDirectory = document.currentScript.src; } // When MODULARIZE (and not _INSTANCE), this JS may be executed later, after document.currentScript // is gone, so we saved it, and we use it here instead of any other info. if (_scriptDir) { scriptDirectory = _scriptDir; } // blob urls look like blob:http://site.com/etc/etc and we cannot infer anything from them. // otherwise, slice off the final part of the url to find the script directory. // if scriptDirectory does not contain a slash, lastIndexOf will return -1, // and scriptDirectory will correctly be replaced with an empty string. if (scriptDirectory.indexOf('blob:') !== 0) { scriptDirectory = scriptDirectory.substr(0, scriptDirectory.lastIndexOf('/')+1); } else { scriptDirectory = ''; } Module['read'] = function shell_read(url) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.send(null); return xhr.responseText; }; if (ENVIRONMENT_IS_WORKER) { Module['readBinary'] = function readBinary(url) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, false); xhr.responseType = 'arraybuffer'; xhr.send(null); return new Uint8Array(xhr.response); }; } Module['readAsync'] = function readAsync(url, onload, onerror) { var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'arraybuffer'; xhr.onload = function xhr_onload() { if (xhr.status == 200 || (xhr.status == 0 && xhr.response)) { // file URLs can return 0 onload(xhr.response); return; } onerror(); }; xhr.onerror = onerror; xhr.send(null); }; Module['setWindowTitle'] = function(title) { document.title = title }; } else { throw new Error('environment detection error'); } // Set up the out() and err() hooks, which are how we can print to stdout or // stderr, respectively. // If the user provided Module.print or printErr, use that. Otherwise, // console.log is checked first, as 'print' on the web will open a print dialogue // printErr is preferable to console.warn (works better in shells) // bind(console) is necessary to fix IE/Edge closed dev tools panel behavior. var out = Module['print'] || (typeof console !== 'undefined' ? console.log.bind(console) : (typeof print !== 'undefined' ? print : null)); var err = Module['printErr'] || (typeof printErr !== 'undefined' ? printErr : ((typeof console !== 'undefined' && console.warn.bind(console)) || out)); // Merge back in the overrides for (key in moduleOverrides) { if (moduleOverrides.hasOwnProperty(key)) { Module[key] = moduleOverrides[key]; } } // Free the object hierarchy contained in the overrides, this lets the GC // reclaim data used e.g. in memoryInitializerRequest, which is a large typed array. moduleOverrides = undefined; // perform assertions in shell.js after we set up out() and err(), as otherwise if an assertion fails it cannot print the message assert(typeof Module['memoryInitializerPrefixURL'] === 'undefined', 'Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['pthreadMainPrefixURL'] === 'undefined', 'Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['cdInitializerPrefixURL'] === 'undefined', 'Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead'); assert(typeof Module['filePackagePrefixURL'] === 'undefined', 'Module.filePackagePrefixURL option was removed, use Module.locateFile instead'); // Copyright 2017 The Emscripten Authors. All rights reserved. // Emscripten is available under two separate licenses, the MIT license and the // University of Illinois/NCSA Open Source License. Both these licenses can be // found in the LICENSE file. // {{PREAMBLE_ADDITIONS}} var STACK_ALIGN = 16; // stack management, and other functionality that is provided by the compiled code, // should not be used before it is ready stackSave = stackRestore = stackAlloc = function() { abort('cannot use the stack before compiled code is ready to run, and has provided stack access'); }; function staticAlloc(size) { abort('staticAlloc is no longer available at runtime; instead, perform static allocations at compile time (using makeStaticAlloc)'); } function dynamicAlloc(size) { assert(DYNAMICTOP_PTR); var ret = HEAP32[DYNAMICTOP_PTR>>2]; var end = (ret + size + 15) & -16; if (end <= _emscripten_get_heap_size()) { HEAP32[DYNAMICTOP_PTR>>2] = end; } else { var success = _emscripten_resize_heap(end); if (!success) return 0; } return ret; } function alignMemory(size, factor) { if (!factor) factor = STACK_ALIGN; // stack alignment (16-byte) by default return Math.ceil(size / factor) * factor; } function getNativeTypeSize(type) { switch (type) { case 'i1': case 'i8': return 1; case 'i16': return 2; case 'i32': return 4; case 'i64': return 8; case 'float': return 4; case 'double': return 8; default: { if (type[type.length-1] === '*') { return 4; // A pointer } else if (type[0] === 'i') { var bits = parseInt(type.substr(1)); assert(bits % 8 === 0, 'getNativeTypeSize invalid bits ' + bits + ', type ' + type); return bits / 8; } else { return 0; } } } } function warnOnce(text) { if (!warnOnce.shown) warnOnce.shown = {}; if (!warnOnce.shown[text]) { warnOnce.shown[text] = 1; err(text); } } var asm2wasmImports = { // special asm2wasm imports "f64-rem": function(x, y) { return x % y; }, "debugger": function() { debugger; } }; var jsCallStartIndex = 1; var functionPointers = new Array(0); // 'sig' parameter is currently only used for LLVM backend under certain // circumstance: RESERVED_FUNCTION_POINTERS=1, EMULATED_FUNCTION_POINTERS=0. function addFunction(func, sig) { var base = 0; for (var i = base; i < base + 0; i++) { if (!functionPointers[i]) { functionPointers[i] = func; return jsCallStartIndex + i; } } throw 'Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.'; } function removeFunction(index) { functionPointers[index-jsCallStartIndex] = null; } var funcWrappers = {}; function getFuncWrapper(func, sig) { if (!func) return; // on null pointer, return undefined assert(sig); if (!funcWrappers[sig]) { funcWrappers[sig] = {}; } var sigCache = funcWrappers[sig]; if (!sigCache[func]) { // optimize away arguments usage in common cases if (sig.length === 1) { sigCache[func] = function dynCall_wrapper() { return dynCall(sig, func); }; } else if (sig.length === 2) { sigCache[func] = function dynCall_wrapper(arg) { return dynCall(sig, func, [arg]); }; } else { // general case sigCache[func] = function dynCall_wrapper() { return dynCall(sig, func, Array.prototype.slice.call(arguments)); }; } } return sigCache[func]; } function makeBigInt(low, high, unsigned) { return unsigned ? ((+((low>>>0)))+((+((high>>>0)))*4294967296.0)) : ((+((low>>>0)))+((+((high|0)))*4294967296.0)); } function dynCall(sig, ptr, args) { if (args && args.length) { assert(args.length == sig.length-1); assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\''); return Module['dynCall_' + sig].apply(null, [ptr].concat(args)); } else { assert(sig.length == 1); assert(('dynCall_' + sig) in Module, 'bad function pointer type - no table for sig \'' + sig + '\''); return Module['dynCall_' + sig].call(null, ptr); } } var tempRet0 = 0; var setTempRet0 = function(value) { tempRet0 = value; } var getTempRet0 = function() { return tempRet0; } function getCompilerSetting(name) { throw 'You must build with -s RETAIN_COMPILER_SETTINGS=1 for getCompilerSetting or emscripten_get_compiler_setting to work'; } var Runtime = { // helpful errors getTempRet0: function() { abort('getTempRet0() is now a top-level function, after removing the Runtime object. Remove "Runtime."') }, staticAlloc: function() { abort('staticAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') }, stackAlloc: function() { abort('stackAlloc() is now a top-level function, after removing the Runtime object. Remove "Runtime."') }, }; // The address globals begin at. Very low in memory, for code size and optimization opportunities. // Above 0 is static memory, starting with globals. // Then the stack. // Then 'dynamic' memory for sbrk. var GLOBAL_BASE = 8; // === Preamble library stuff === // Documentation for the public APIs defined in this file must be updated in: // site/source/docs/api_reference/preamble.js.rst // A prebuilt local version of the documentation is available at: // site/build/text/docs/api_reference/preamble.js.txt // You can also build docs locally as HTML or other formats in site/ // An online HTML version (which may be of a different version of Emscripten) // is up at http://kripken.github.io/emscripten-site/docs/api_reference/preamble.js.html /** @type {function(number, string, boolean=)} */ function getValue(ptr, type, noSafe) { type = type || 'i8'; if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit if (noSafe) { switch(type) { case 'i1': return HEAP8[((ptr)>>0)]; case 'i8': return HEAP8[((ptr)>>0)]; case 'i16': return HEAP16[((ptr)>>1)]; case 'i32': return HEAP32[((ptr)>>2)]; case 'i64': return HEAP32[((ptr)>>2)]; case 'float': return HEAPF32[((ptr)>>2)]; case 'double': return HEAPF64[((ptr)>>3)]; default: abort('invalid type for getValue: ' + type); } } else { switch(type) { case 'i1': return ((SAFE_HEAP_LOAD(((ptr)|0), 1, 0))|0); case 'i8': return ((SAFE_HEAP_LOAD(((ptr)|0), 1, 0))|0); case 'i16': return ((SAFE_HEAP_LOAD(((ptr)|0), 2, 0))|0); case 'i32': return ((SAFE_HEAP_LOAD(((ptr)|0), 4, 0))|0); case 'i64': return ((SAFE_HEAP_LOAD(((ptr)|0), 8, 0))|0); case 'float': return (+(SAFE_HEAP_LOAD_D(((ptr)|0), 4, 0))); case 'double': return (+(SAFE_HEAP_LOAD_D(((ptr)|0), 8, 0))); default: abort('invalid type for getValue: ' + type); } } return null; } function getSafeHeapType(bytes, isFloat) { switch (bytes) { case 1: return 'i8'; case 2: return 'i16'; case 4: return isFloat ? 'float' : 'i32'; case 8: return 'double'; default: assert(0); } } function SAFE_HEAP_STORE(dest, value, bytes, isFloat) { if (dest <= 0) abort('segmentation fault storing ' + bytes + ' bytes to address ' + dest); if (dest % bytes !== 0) abort('alignment error storing to address ' + dest + ', which was expected to be aligned to a multiple of ' + bytes); if (dest + bytes > HEAP32[DYNAMICTOP_PTR>>2]) abort('segmentation fault, exceeded the top of the available dynamic heap when storing ' + bytes + ' bytes to address ' + dest + '. DYNAMICTOP=' + HEAP32[DYNAMICTOP_PTR>>2]); assert(DYNAMICTOP_PTR); assert(HEAP32[DYNAMICTOP_PTR>>2] <= TOTAL_MEMORY); setValue(dest, value, getSafeHeapType(bytes, isFloat), 1); } function SAFE_HEAP_STORE_D(dest, value, bytes) { SAFE_HEAP_STORE(dest, value, bytes, true); } function SAFE_HEAP_LOAD(dest, bytes, unsigned, isFloat) { if (dest <= 0) abort('segmentation fault loading ' + bytes + ' bytes from address ' + dest); if (dest % bytes !== 0) abort('alignment error loading from address ' + dest + ', which was expected to be aligned to a multiple of ' + bytes); if (dest + bytes > HEAP32[DYNAMICTOP_PTR>>2]) abort('segmentation fault, exceeded the top of the available dynamic heap when loading ' + bytes + ' bytes from address ' + dest + '. DYNAMICTOP=' + HEAP32[DYNAMICTOP_PTR>>2]); assert(DYNAMICTOP_PTR); assert(HEAP32[DYNAMICTOP_PTR>>2] <= TOTAL_MEMORY); var type = getSafeHeapType(bytes, isFloat); var ret = getValue(dest, type, 1); if (unsigned) ret = unSign(ret, parseInt(type.substr(1)), 1); return ret; } function SAFE_HEAP_LOAD_D(dest, bytes, unsigned) { return SAFE_HEAP_LOAD(dest, bytes, unsigned, true); } function SAFE_FT_MASK(value, mask) { var ret = value & mask; if (ret !== value) { abort('Function table mask error: function pointer is ' + value + ' which is masked by ' + mask + ', the likely cause of this is that the function pointer is being called by the wrong type.'); } return ret; } function segfault() { abort('segmentation fault'); } function alignfault() { abort('alignment fault'); } function ftfault() { abort('Function table mask error'); } // Wasm globals var wasmMemory; // Potentially used for direct table calls. var wasmTable; //======================================== // Runtime essentials //======================================== // whether we are quitting the application. no code should run after this. // set in exit() and abort() var ABORT = false; // set by exit() and abort(). Passed to 'onExit' handler. // NOTE: This is also used as the process return code code in shell environments // but only when noExitRuntime is false. var EXITSTATUS = 0; /** @type {function(*, string=)} */ function assert(condition, text) { if (!condition) { abort('Assertion failed: ' + text); } } // Returns the C function with a specified identifier (for C++, you need to do manual name mangling) function getCFunc(ident) { var func = Module['_' + ident]; // closure exported function assert(func, 'Cannot call unknown function ' + ident + ', make sure it is exported'); return func; } // C calling interface. function ccall(ident, returnType, argTypes, args, opts) { // For fast lookup of conversion functions var toC = { 'string': function(str) { var ret = 0; if (str !== null && str !== undefined && str !== 0) { // null string // at most 4 bytes per UTF-8 code point, +1 for the trailing '\0' var len = (str.length << 2) + 1; ret = stackAlloc(len); stringToUTF8(str, ret, len); } return ret; }, 'array': function(arr) { var ret = stackAlloc(arr.length); writeArrayToMemory(arr, ret); return ret; } }; function convertReturnValue(ret) { if (returnType === 'string') return UTF8ToString(ret); if (returnType === 'boolean') return Boolean(ret); return ret; } var func = getCFunc(ident); var cArgs = []; var stack = 0; assert(returnType !== 'array', 'Return type should not be "array".'); if (args) { for (var i = 0; i < args.length; i++) { var converter = toC[argTypes[i]]; if (converter) { if (stack === 0) stack = stackSave(); cArgs[i] = converter(args[i]); } else { cArgs[i] = args[i]; } } } var ret = func.apply(null, cArgs); ret = convertReturnValue(ret); if (stack !== 0) stackRestore(stack); return ret; } function cwrap(ident, returnType, argTypes, opts) { return function() { return ccall(ident, returnType, argTypes, arguments, opts); } } /** @type {function(number, number, string, boolean=)} */ function setValue(ptr, value, type, noSafe) { type = type || 'i8'; if (type.charAt(type.length-1) === '*') type = 'i32'; // pointers are 32-bit if (noSafe) { switch(type) { case 'i1': HEAP8[((ptr)>>0)]=value; break; case 'i8': HEAP8[((ptr)>>0)]=value; break; case 'i16': HEAP16[((ptr)>>1)]=value; break; case 'i32': HEAP32[((ptr)>>2)]=value; break; case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= (+1) ? (tempDouble > (+0) ? ((Math_min((+(Math_floor((tempDouble)/(+4294967296)))), (+4294967295)))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/(+4294967296))))))>>>0) : 0)],HEAP32[((ptr)>>2)]=tempI64[0],HEAP32[(((ptr)+(4))>>2)]=tempI64[1]); break; case 'float': HEAPF32[((ptr)>>2)]=value; break; case 'double': HEAPF64[((ptr)>>3)]=value; break; default: abort('invalid type for setValue: ' + type); } } else { switch(type) { case 'i1': SAFE_HEAP_STORE(((ptr)|0), ((value)|0), 1); break; case 'i8': SAFE_HEAP_STORE(((ptr)|0), ((value)|0), 1); break; case 'i16': SAFE_HEAP_STORE(((ptr)|0), ((value)|0), 2); break; case 'i32': SAFE_HEAP_STORE(((ptr)|0), ((value)|0), 4); break; case 'i64': (tempI64 = [value>>>0,(tempDouble=value,(+(Math_abs(tempDouble))) >= (+1) ? (tempDouble > (+0) ? ((Math_min((+(Math_floor((tempDouble)/(+4294967296)))), (+4294967295)))|0)>>>0 : (~~((+(Math_ceil((tempDouble - +(((~~(tempDouble)))>>>0))/(+4294967296))))))>>>0) : 0)],SAFE_HEAP_STORE(((ptr)|0), ((tempI64[0])|0), 4),SAFE_HEAP_STORE((((ptr)+(4))|0), ((tempI64[1])|0), 4)); break; case 'float': SAFE_HEAP_STORE_D(((ptr)|0), (+(value)), 4); break; case 'double': SAFE_HEAP_STORE_D(((ptr)|0), (+(value)), 8); break; default: abort('invalid type for setValue: ' + type); } } } var ALLOC_NORMAL = 0; // Tries to use _malloc() var ALLOC_STACK = 1; // Lives for the duration of the current function call var ALLOC_DYNAMIC = 2; // Cannot be freed except through sbrk var ALLOC_NONE = 3; // Do not allocate // allocate(): This is for internal use. You can use it yourself as well, but the interface // is a little tricky (see docs right below). The reason is that it is optimized // for multiple syntaxes to save space in generated code. So you should // normally not use allocate(), and instead allocate memory using _malloc(), // initialize it with setValue(), and so forth. // @slab: An array of data, or a number. If a number, then the size of the block to allocate, // in *bytes* (note that this is sometimes confusing: the next parameter does not // affect this!) // @types: Either an array of types, one for each byte (or 0 if no type at that position), // or a single type which is used for the entire block. This only matters if there // is initial data - if @slab is a number, then this does not matter at all and is // ignored. // @allocator: How to allocate memory, see ALLOC_* /** @type {function((TypedArray|Array<number>|number), string, number, number=)} */ function allocate(slab, types, allocator, ptr) { var zeroinit, size; if (typeof slab === 'number') { zeroinit = true; size = slab; } else { zeroinit = false; size = slab.length; } var singleType = typeof types === 'string' ? types : null; var ret; if (allocator == ALLOC_NONE) { ret = ptr; } else { ret = [_malloc, stackAlloc, dynamicAlloc][allocator](Math.max(size, singleType ? 1 : types.length)); } if (zeroinit) { var stop; ptr = ret; assert((ret & 3) == 0); stop = ret + (size & ~3); for (; ptr < stop; ptr += 4) { HEAP32[((ptr)>>2)]=0; } stop = ret + size; while (ptr < stop) { HEAP8[((ptr++)>>0)]=0; } return ret; } if (singleType === 'i8') { if (slab.subarray || slab.slice) { HEAPU8.set(/** @type {!Uint8Array} */ (slab), ret); } else { HEAPU8.set(new Uint8Array(slab), ret); } return ret; } var i = 0, type, typeSize, previousType; while (i < size) { var curr = slab[i]; type = singleType || types[i]; if (type === 0) { i++; continue; } assert(type, 'Must know what type to store in allocate!'); if (type == 'i64') type = 'i32'; // special case: we have one i32 here, and one i32 later setValue(ret+i, curr, type); // no need to look up size unless type changes, so cache it if (previousType !== type) { typeSize = getNativeTypeSize(type); previousType = type; } i += typeSize; } return ret; } // Allocate memory during any stage of startup - static memory early on, dynamic memory later, malloc when ready function getMemory(size) { if (!runtimeInitialized) return dynamicAlloc(size); return _malloc(size); } /** @type {function(number, number=)} */ function Pointer_stringify(ptr, length) { abort("this function has been removed - you should use UTF8ToString(ptr, maxBytesToRead) instead!"); } // Given a pointer 'ptr' to a null-terminated ASCII-encoded string in the emscripten HEAP, returns // a copy of that string as a Javascript String object. function AsciiToString(ptr) { var str = ''; while (1) { var ch = ((SAFE_HEAP_LOAD(((ptr++)|0), 1, 0))|0); if (!ch) return str; str += String.fromCharCode(ch); } } // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', // null-terminated and encoded in ASCII form. The copy will require at most str.length+1 bytes of space in the HEAP. function stringToAscii(str, outPtr) { return writeAsciiToMemory(str, outPtr, false); } // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the given array that contains uint8 values, returns // a copy of that string as a Javascript String object. var UTF8Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf8') : undefined; /** * @param {number} idx * @param {number=} maxBytesToRead * @return {string} */ function UTF8ArrayToString(u8Array, idx, maxBytesToRead) { var endIdx = idx + maxBytesToRead; var endPtr = idx; // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. // (As a tiny code save trick, compare endPtr against endIdx using a negation, so that undefined means Infinity) while (u8Array[endPtr] && !(endPtr >= endIdx)) ++endPtr; if (endPtr - idx > 16 && u8Array.subarray && UTF8Decoder) { return UTF8Decoder.decode(u8Array.subarray(idx, endPtr)); } else { var str = ''; // If building with TextDecoder, we have already computed the string length above, so test loop end condition against that while (idx < endPtr) { // For UTF8 byte structure, see: // http://en.wikipedia.org/wiki/UTF-8#Description // https://www.ietf.org/rfc/rfc2279.txt // https://tools.ietf.org/html/rfc3629 var u0 = u8Array[idx++]; if (!(u0 & 0x80)) { str += String.fromCharCode(u0); continue; } var u1 = u8Array[idx++] & 63; if ((u0 & 0xE0) == 0xC0) { str += String.fromCharCode(((u0 & 31) << 6) | u1); continue; } var u2 = u8Array[idx++] & 63; if ((u0 & 0xF0) == 0xE0) { u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; } else { if ((u0 & 0xF8) != 0xF0) warnOnce('Invalid UTF-8 leading byte 0x' + u0.toString(16) + ' encountered when deserializing a UTF-8 string on the asm.js/wasm heap to a JS string!'); u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (u8Array[idx++] & 63); } if (u0 < 0x10000) { str += String.fromCharCode(u0); } else { var ch = u0 - 0x10000; str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); } } } return str; } // Given a pointer 'ptr' to a null-terminated UTF8-encoded string in the emscripten HEAP, returns a // copy of that string as a Javascript String object. // maxBytesToRead: an optional length that specifies the maximum number of bytes to read. You can omit // this parameter to scan the string until the first \0 byte. If maxBytesToRead is // passed, and the string at [ptr, ptr+maxBytesToReadr[ contains a null byte in the // middle, then the string will cut short at that byte index (i.e. maxBytesToRead will // not produce a string of exact length [ptr, ptr+maxBytesToRead[) // N.B. mixing frequent uses of UTF8ToString() with and without maxBytesToRead may // throw JS JIT optimizations off, so it is worth to consider consistently using one // style or the other. /** * @param {number} ptr * @param {number=} maxBytesToRead * @return {string} */ function UTF8ToString(ptr, maxBytesToRead) { return ptr ? UTF8ArrayToString(HEAPU8, ptr, maxBytesToRead) : ''; } // Copies the given Javascript String object 'str' to the given byte array at address 'outIdx', // encoded in UTF8 form and null-terminated. The copy will require at most str.length*4+1 bytes of space in the HEAP. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. // Parameters: // str: the Javascript string to copy. // outU8Array: the array to copy to. Each index in this array is assumed to be one 8-byte element. // outIdx: The starting offset in the array to begin the copying. // maxBytesToWrite: The maximum number of bytes this function can write to the array. // This count should include the null terminator, // i.e. if maxBytesToWrite=1, only the null terminator will be written and nothing else. // maxBytesToWrite=0 does not write any bytes to the output, not even the null terminator. // Returns the number of bytes written, EXCLUDING the null terminator. function stringToUTF8Array(str, outU8Array, outIdx, maxBytesToWrite) { if (!(maxBytesToWrite > 0)) // Parameter maxBytesToWrite is not optional. Negative values, 0, null, undefined and false each don't write out any bytes. return 0; var startIdx = outIdx; var endIdx = outIdx + maxBytesToWrite - 1; // -1 for string null terminator. for (var i = 0; i < str.length; ++i) { // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8. // See http://unicode.org/faq/utf_bom.html#utf16-3 // For UTF8 byte structure, see http://en.wikipedia.org/wiki/UTF-8#Description and https://www.ietf.org/rfc/rfc2279.txt and https://tools.ietf.org/html/rfc3629 var u = str.charCodeAt(i); // possibly a lead surrogate if (u >= 0xD800 && u <= 0xDFFF) { var u1 = str.charCodeAt(++i); u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); } if (u <= 0x7F) { if (outIdx >= endIdx) break; outU8Array[outIdx++] = u; } else if (u <= 0x7FF) { if (outIdx + 1 >= endIdx) break; outU8Array[outIdx++] = 0xC0 | (u >> 6); outU8Array[outIdx++] = 0x80 | (u & 63); } else if (u <= 0xFFFF) { if (outIdx + 2 >= endIdx) break; outU8Array[outIdx++] = 0xE0 | (u >> 12); outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63); outU8Array[outIdx++] = 0x80 | (u & 63); } else { if (outIdx + 3 >= endIdx) break; if (u >= 0x200000) warnOnce('Invalid Unicode code point 0x' + u.toString(16) + ' encountered when serializing a JS string to an UTF-8 string on the asm.js/wasm heap! (Valid unicode code points should be in range 0-0x1FFFFF).'); outU8Array[outIdx++] = 0xF0 | (u >> 18); outU8Array[outIdx++] = 0x80 | ((u >> 12) & 63); outU8Array[outIdx++] = 0x80 | ((u >> 6) & 63); outU8Array[outIdx++] = 0x80 | (u & 63); } } // Null-terminate the pointer to the buffer. outU8Array[outIdx] = 0; return outIdx - startIdx; } // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', // null-terminated and encoded in UTF8 form. The copy will require at most str.length*4+1 bytes of space in the HEAP. // Use the function lengthBytesUTF8 to compute the exact number of bytes (excluding null terminator) that this function will write. // Returns the number of bytes written, EXCLUDING the null terminator. function stringToUTF8(str, outPtr, maxBytesToWrite) { assert(typeof maxBytesToWrite == 'number', 'stringToUTF8(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); return stringToUTF8Array(str, HEAPU8,outPtr, maxBytesToWrite); } // Returns the number of bytes the given Javascript string takes if encoded as a UTF8 byte array, EXCLUDING the null terminator byte. function lengthBytesUTF8(str) { var len = 0; for (var i = 0; i < str.length; ++i) { // Gotcha: charCodeAt returns a 16-bit word that is a UTF-16 encoded code unit, not a Unicode code point of the character! So decode UTF16->UTF32->UTF8. // See http://unicode.org/faq/utf_bom.html#utf16-3 var u = str.charCodeAt(i); // possibly a lead surrogate if (u >= 0xD800 && u <= 0xDFFF) u = 0x10000 + ((u & 0x3FF) << 10) | (str.charCodeAt(++i) & 0x3FF); if (u <= 0x7F) ++len; else if (u <= 0x7FF) len += 2; else if (u <= 0xFFFF) len += 3; else len += 4; } return len; } // Given a pointer 'ptr' to a null-terminated UTF16LE-encoded string in the emscripten HEAP, returns // a copy of that string as a Javascript String object. var UTF16Decoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-16le') : undefined; function UTF16ToString(ptr) { assert(ptr % 2 == 0, 'Pointer passed to UTF16ToString must be aligned to two bytes!'); var endPtr = ptr; // TextDecoder needs to know the byte length in advance, it doesn't stop on null terminator by itself. // Also, use the length info to avoid running tiny strings through TextDecoder, since .subarray() allocates garbage. var idx = endPtr >> 1; while (HEAP16[idx]) ++idx; endPtr = idx << 1; if (endPtr - ptr > 32 && UTF16Decoder) { return UTF16Decoder.decode(HEAPU8.subarray(ptr, endPtr)); } else { var i = 0; var str = ''; while (1) { var codeUnit = ((SAFE_HEAP_LOAD((((ptr)+(i*2))|0), 2, 0))|0); if (codeUnit == 0) return str; ++i; // fromCharCode constructs a character from a UTF-16 code unit, so we can pass the UTF16 string right through. str += String.fromCharCode(codeUnit); } } } // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', // null-terminated and encoded in UTF16 form. The copy will require at most str.length*4+2 bytes of space in the HEAP. // Use the function lengthBytesUTF16() to compute the exact number of bytes (excluding null terminator) that this function will write. // Parameters: // str: the Javascript string to copy. // outPtr: Byte address in Emscripten HEAP where to write the string to. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null // terminator, i.e. if maxBytesToWrite=2, only the null terminator will be written and nothing else. // maxBytesToWrite<2 does not write any bytes to the output, not even the null terminator. // Returns the number of bytes written, EXCLUDING the null terminator. function stringToUTF16(str, outPtr, maxBytesToWrite) { assert(outPtr % 2 == 0, 'Pointer passed to stringToUTF16 must be aligned to two bytes!'); assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. if (maxBytesToWrite === undefined) { maxBytesToWrite = 0x7FFFFFFF; } if (maxBytesToWrite < 2) return 0; maxBytesToWrite -= 2; // Null terminator. var startPtr = outPtr; var numCharsToWrite = (maxBytesToWrite < str.length*2) ? (maxBytesToWrite / 2) : str.length; for (var i = 0; i < numCharsToWrite; ++i) { // charCodeAt returns a UTF-16 encoded code unit, so it can be directly written to the HEAP. var codeUnit = str.charCodeAt(i); // possibly a lead surrogate SAFE_HEAP_STORE(((outPtr)|0), ((codeUnit)|0), 2); outPtr += 2; } // Null-terminate the pointer to the HEAP. SAFE_HEAP_STORE(((outPtr)|0), ((0)|0), 2); return outPtr - startPtr; } // Returns the number of bytes the given Javascript string takes if encoded as a UTF16 byte array, EXCLUDING the null terminator byte. function lengthBytesUTF16(str) { return str.length*2; } function UTF32ToString(ptr) { assert(ptr % 4 == 0, 'Pointer passed to UTF32ToString must be aligned to four bytes!'); var i = 0; var str = ''; while (1) { var utf32 = ((SAFE_HEAP_LOAD((((ptr)+(i*4))|0), 4, 0))|0); if (utf32 == 0) return str; ++i; // Gotcha: fromCharCode constructs a character from a UTF-16 encoded code (pair), not from a Unicode code point! So encode the code point to UTF-16 for constructing. // See http://unicode.org/faq/utf_bom.html#utf16-3 if (utf32 >= 0x10000) { var ch = utf32 - 0x10000; str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); } else { str += String.fromCharCode(utf32); } } } // Copies the given Javascript String object 'str' to the emscripten HEAP at address 'outPtr', // null-terminated and encoded in UTF32 form. The copy will require at most str.length*4+4 bytes of space in the HEAP. // Use the function lengthBytesUTF32() to compute the exact number of bytes (excluding null terminator) that this function will write. // Parameters: // str: the Javascript string to copy. // outPtr: Byte address in Emscripten HEAP where to write the string to. // maxBytesToWrite: The maximum number of bytes this function can write to the array. This count should include the null // terminator, i.e. if maxBytesToWrite=4, only the null terminator will be written and nothing else. // maxBytesToWrite<4 does not write any bytes to the output, not even the null terminator. // Returns the number of bytes written, EXCLUDING the null terminator.