{"version":3,"file":"GltfSVApp.js","sources":["../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat3.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/vec3.js","../node_modules/gl-matrix/esm/vec4.js","../node_modules/gl-matrix/esm/quat.js","../node_modules/gl-matrix/esm/vec2.js","../gltf-source/gltf/utils.js","../gltf-source/gltf/gltf_object.js","../gltf-source/gltf/camera.js","../gltf-source/gltf/gltf_utils.js","../gltf-source/gltf/user_camera.js","../gltf-source/GltfState/gltf_state.js","../gltf-source/gltf/image_mime_type.js","../gltf-source/Renderer/webgl.js","../gltf-source/Renderer/shader.js","../gltf-source/Renderer/shader_cache.js","../gltf-source/Renderer/environment_renderer.js","../gltf-source/gltf/light.js","../gltf-source/Renderer/renderer.js","../node_modules/axios/lib/helpers/bind.js","../node_modules/axios/lib/utils.js","../node_modules/axios/lib/helpers/buildURL.js","../node_modules/axios/lib/core/InterceptorManager.js","../node_modules/axios/lib/helpers/normalizeHeaderName.js","../node_modules/axios/lib/core/enhanceError.js","../node_modules/axios/lib/core/createError.js","../node_modules/axios/lib/core/settle.js","../node_modules/axios/lib/helpers/cookies.js","../node_modules/axios/lib/helpers/isAbsoluteURL.js","../node_modules/axios/lib/helpers/combineURLs.js","../node_modules/axios/lib/core/buildFullPath.js","../node_modules/axios/lib/helpers/parseHeaders.js","../node_modules/axios/lib/helpers/isURLSameOrigin.js","../node_modules/axios/lib/adapters/xhr.js","../node_modules/axios/lib/defaults.js","../node_modules/axios/lib/core/transformData.js","../node_modules/axios/lib/cancel/isCancel.js","../node_modules/axios/lib/core/dispatchRequest.js","../node_modules/axios/lib/core/mergeConfig.js","../node_modules/axios/lib/helpers/validator.js","../node_modules/axios/lib/core/Axios.js","../node_modules/axios/lib/cancel/Cancel.js","../node_modules/axios/lib/cancel/CancelToken.js","../node_modules/axios/lib/helpers/spread.js","../node_modules/axios/lib/helpers/isAxiosError.js","../node_modules/axios/lib/axios.js","../node_modules/axios/index.js","../gltf-source/gltf/accessor.js","../gltf-source/gltf/buffer.js","../gltf-source/gltf/buffer_view.js","../gltf-source/ResourceLoader/async_file_reader.js","../node_modules/jpeg-js/lib/encoder.js","../node_modules/jpeg-js/lib/decoder.js","../node_modules/jpeg-js/index.js","../node_modules/iobuffer/lib-esm/text-encoding-polyfill.js","../node_modules/iobuffer/lib-esm/text.browser.js","../node_modules/iobuffer/lib-esm/IOBuffer.js","../node_modules/pako/dist/pako.esm.mjs","../node_modules/fast-png/lib-esm/common.js","../node_modules/fast-png/lib-esm/internalTypes.js","../node_modules/fast-png/lib-esm/PNGDecoder.js","../node_modules/fast-png/lib-esm/types.js","../node_modules/fast-png/lib-esm/index.js","../gltf-source/gltf/image.js","../gltf-source/gltf/image_based_light.js","../gltf-source/gltf/texture.js","../gltf-source/gltf/material.js","../gltf-source/gltf/sampler.js","../gltf-source/ResourceLoader/draco.js","../gltf-source/gltf/primitive.js","../gltf-source/gltf/mesh.js","../gltf-source/gltf/node.js","../gltf-source/gltf/scene.js","../gltf-source/gltf/asset.js","../gltf-source/gltf/channel.js","../gltf-source/gltf/animation_sampler.js","../gltf-source/gltf/interpolator.js","../gltf-source/gltf/animation.js","../gltf-source/gltf/skin.js","../gltf-source/gltf/variant.js","../gltf-source/gltf/gltf.js","../gltf-source/ResourceLoader/glb_parser.js","../gltf-source/ResourceLoader/loader.js","../gltf-source/ibl_sampler.js","../gltf-source/ResourceLoader/ktx.js","../gltf-source/libs/hdrpng.js","../gltf-source/ResourceLoader/resource_loader.js","../gltf-source/GltfView/gltf_view.js","../node_modules/tslib/tslib.es6.js","../node_modules/rxjs/_esm5/internal/util/isFunction.js","../node_modules/rxjs/_esm5/internal/config.js","../node_modules/rxjs/_esm5/internal/util/hostReportError.js","../node_modules/rxjs/_esm5/internal/Observer.js","../node_modules/rxjs/_esm5/internal/util/isArray.js","../node_modules/rxjs/_esm5/internal/util/isObject.js","../node_modules/rxjs/_esm5/internal/util/UnsubscriptionError.js","../node_modules/rxjs/_esm5/internal/Subscription.js","../node_modules/rxjs/_esm5/internal/symbol/rxSubscriber.js","../node_modules/rxjs/_esm5/internal/Subscriber.js","../node_modules/rxjs/_esm5/internal/util/canReportError.js","../node_modules/rxjs/_esm5/internal/util/toSubscriber.js","../node_modules/rxjs/_esm5/internal/symbol/observable.js","../node_modules/rxjs/_esm5/internal/util/identity.js","../node_modules/rxjs/_esm5/internal/util/pipe.js","../node_modules/rxjs/_esm5/internal/Observable.js","../node_modules/rxjs/_esm5/internal/util/ObjectUnsubscribedError.js","../node_modules/rxjs/_esm5/internal/SubjectSubscription.js","../node_modules/rxjs/_esm5/internal/Subject.js","../node_modules/rxjs/_esm5/internal/operators/refCount.js","../node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js","../node_modules/rxjs/_esm5/internal/util/isScheduler.js","../node_modules/rxjs/_esm5/internal/util/subscribeToArray.js","../node_modules/rxjs/_esm5/internal/scheduled/scheduleArray.js","../node_modules/rxjs/_esm5/internal/observable/fromArray.js","../node_modules/rxjs/_esm5/internal/observable/of.js","../node_modules/rxjs/_esm5/internal/util/noop.js","../node_modules/rxjs/_esm5/internal/operators/map.js","../node_modules/rxjs/_esm5/internal/util/subscribeToPromise.js","../node_modules/rxjs/_esm5/internal/symbol/iterator.js","../node_modules/rxjs/_esm5/internal/util/subscribeToIterable.js","../node_modules/rxjs/_esm5/internal/util/subscribeToObservable.js","../node_modules/rxjs/_esm5/internal/util/isArrayLike.js","../node_modules/rxjs/_esm5/internal/util/isPromise.js","../node_modules/rxjs/_esm5/internal/util/subscribeTo.js","../node_modules/rxjs/_esm5/internal/scheduled/scheduleObservable.js","../node_modules/rxjs/_esm5/internal/scheduled/schedulePromise.js","../node_modules/rxjs/_esm5/internal/scheduled/scheduleIterable.js","../node_modules/rxjs/_esm5/internal/util/isInteropObservable.js","../node_modules/rxjs/_esm5/internal/util/isIterable.js","../node_modules/rxjs/_esm5/internal/scheduled/scheduled.js","../node_modules/rxjs/_esm5/internal/observable/from.js","../node_modules/rxjs/_esm5/internal/innerSubscribe.js","../node_modules/rxjs/_esm5/internal/operators/mergeMap.js","../node_modules/rxjs/_esm5/internal/operators/mergeAll.js","../node_modules/rxjs/_esm5/internal/operators/concatAll.js","../node_modules/rxjs/_esm5/internal/observable/concat.js","../node_modules/rxjs/_esm5/internal/observable/fromEvent.js","../node_modules/rxjs/_esm5/internal/observable/merge.js","../node_modules/rxjs/_esm5/internal/observable/never.js","../node_modules/rxjs/_esm5/internal/operators/filter.js","../node_modules/rxjs/_esm5/internal/operators/multicast.js","../node_modules/rxjs/_esm5/internal/operators/pairwise.js","../node_modules/rxjs/_esm5/internal/operators/share.js","../node_modules/rxjs/_esm5/internal/operators/startWith.js","../node_modules/rxjs/_esm5/internal/operators/takeUntil.js","../node_modules/simple-dropzone/dist/simple-dropzone.module.js","../node_modules/normalize-wheel/src/UserAgent_DEPRECATED.js","../node_modules/normalize-wheel/src/ExecutionEnvironment.js","../node_modules/normalize-wheel/src/isEventSupported.js","../node_modules/normalize-wheel/src/normalizeWheel.js","../node_modules/normalize-wheel/index.js","../src/logic/uimodel.js","../node_modules/vue/dist/vue.esm.js","../node_modules/vue-rx/dist/vue-rx.esm.js","../node_modules/buefy/dist/esm/_rollupPluginBabelHelpers-df313029.js","../node_modules/buefy/dist/esm/helpers.js","../node_modules/buefy/dist/esm/config-e7d4b9c2.js","../node_modules/buefy/dist/esm/FormElementMixin-b223d3c7.js","../node_modules/buefy/dist/esm/plugins-218aea86.js","../node_modules/buefy/dist/esm/Icon-60d47b31.js","../node_modules/buefy/dist/esm/Input-20612b63.js","../node_modules/buefy/dist/esm/Autocomplete-1a6e8770.js","../node_modules/buefy/dist/esm/autocomplete.js","../node_modules/buefy/dist/esm/breadcrumb.js","../node_modules/buefy/dist/esm/Button-521f6efc.js","../node_modules/buefy/dist/esm/button.js","../node_modules/buefy/dist/esm/InjectedChildMixin-b4220787.js","../node_modules/buefy/dist/esm/Image-75808acb.js","../node_modules/buefy/dist/esm/carousel.js","../node_modules/buefy/dist/esm/CheckRadioMixin-e726a83c.js","../node_modules/buefy/dist/esm/Checkbox-1d02686e.js","../node_modules/buefy/dist/esm/checkbox.js","../node_modules/buefy/dist/esm/collapse.js","../node_modules/buefy/dist/esm/TimepickerMixin-d736b0a9.js","../node_modules/buefy/dist/esm/trapFocus-f0736873.js","../node_modules/buefy/dist/esm/DropdownItem-55682322.js","../node_modules/buefy/dist/esm/Field-3cb24eff.js","../node_modules/buefy/dist/esm/clockpicker.js","../node_modules/buefy/dist/esm/Select-97781d4e.js","../node_modules/buefy/dist/esm/Tooltip-c67e7511.js","../node_modules/buefy/dist/esm/index-0698ec02.js","../node_modules/buefy/dist/esm/Datepicker-153e1b03.js","../node_modules/buefy/dist/esm/datepicker.js","../node_modules/buefy/dist/esm/Timepicker-c1e2bbf4.js","../node_modules/buefy/dist/esm/datetimepicker.js","../node_modules/buefy/dist/esm/Modal-7da7641f.js","../node_modules/buefy/dist/esm/dialog.js","../node_modules/buefy/dist/esm/dropdown.js","../node_modules/buefy/dist/esm/field.js","../node_modules/buefy/dist/esm/icon.js","../node_modules/buefy/dist/esm/image.js","../node_modules/buefy/dist/esm/input.js","../node_modules/buefy/dist/esm/ssr-b847d137.js","../node_modules/buefy/dist/esm/Loading-ae028ea5.js","../node_modules/buefy/dist/esm/loading.js","../node_modules/buefy/dist/esm/menu.js","../node_modules/buefy/dist/esm/MessageMixin-d577a9f5.js","../node_modules/buefy/dist/esm/message.js","../node_modules/buefy/dist/esm/modal.js","../node_modules/buefy/dist/esm/NoticeMixin-bd6f61d9.js","../node_modules/buefy/dist/esm/notification.js","../node_modules/buefy/dist/esm/navbar.js","../node_modules/buefy/dist/esm/numberinput.js","../node_modules/buefy/dist/esm/Pagination-68f12c1e.js","../node_modules/buefy/dist/esm/pagination.js","../node_modules/buefy/dist/esm/progress.js","../node_modules/buefy/dist/esm/radio.js","../node_modules/buefy/dist/esm/rate.js","../node_modules/buefy/dist/esm/select.js","../node_modules/buefy/dist/esm/skeleton.js","../node_modules/buefy/dist/esm/sidebar.js","../node_modules/buefy/dist/esm/slider.js","../node_modules/buefy/dist/esm/snackbar.js","../node_modules/buefy/dist/esm/SlotComponent-8871a20f.js","../node_modules/buefy/dist/esm/TabbedChildMixin-bcb13767.js","../node_modules/buefy/dist/esm/steps.js","../node_modules/buefy/dist/esm/switch.js","../node_modules/buefy/dist/esm/table.js","../node_modules/buefy/dist/esm/tabs.js","../node_modules/buefy/dist/esm/Tag-6365aa46.js","../node_modules/buefy/dist/esm/tag.js","../node_modules/buefy/dist/esm/taginput.js","../node_modules/buefy/dist/esm/timepicker.js","../node_modules/buefy/dist/esm/toast.js","../node_modules/buefy/dist/esm/tooltip.js","../node_modules/buefy/dist/esm/upload.js","../node_modules/buefy/dist/esm/config.js","../node_modules/buefy/dist/esm/index.js","../src/ui/ui.js","../node_modules/rollup-plugin-node-builtins/src/es6/path.js","../src/model_path_provider.js","../src/main.js"],"sourcesContent":["/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\n\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};","import * as glMatrix from \"./common.js\";\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a the source 4x4 matrix\n * @returns {mat3} out\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\n\nexport var perspective = perspectiveNO;\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\n\nexport var ortho = orthoNO;\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\n * Math.round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec3} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec3.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\n * Math.round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec4} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec4.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\n * Quaternion\n * @module quat\n */\n\n/**\n * Creates a new identity quat\n *\n * @returns {quat} a new quaternion\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n out[3] = 1;\n return out;\n}\n/**\n * Set a quat to the identity quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\n * Sets a quat from the given angle and rotation axis,\n * then returns it.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyVec3} axis the axis around which to rotate\n * @param {Number} rad the angle in radians\n * @returns {quat} out\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\n * Gets the rotation axis and angle for a given\n * quaternion. If a quaternion is created with\n * setAxisAngle, this method will return the same\n * values as providied in the original parameter list\n * OR functionally equivalent values.\n * Example: The quaternion formed by axis [0, 0, 1] and\n * angle -90 is the same as the quaternion formed by\n * [0, 0, 1] and 270. This method favors the latter.\n * @param {vec3} out_axis Vector receiving the axis of rotation\n * @param {ReadonlyQuat} q Quaternion to be decomposed\n * @return {Number} Angle, in radians, of the rotation\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\n * Gets the angular distance between two unit quaternions\n *\n * @param {ReadonlyQuat} a Origin unit quaternion\n * @param {ReadonlyQuat} b Destination unit quaternion\n * @return {Number} Angle, in radians, between the two quaternions\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\n * Multiplies two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the X axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Y axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Z axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\n * Calculates the W component of a quat from the X, Y, and Z components.\n * Assumes that quaternion is 1 unit in length.\n * Any existing W component will be ignored.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate W component of\n * @returns {quat} out\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\n * Calculate the exponential of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\n * Calculate the natural logarithm of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\n * Calculate the scalar power of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @param {Number} b amount to scale the quaternion by\n * @returns {quat} out\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\n * Performs a spherical linear interpolation between two quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\n * Generates a random unit quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\n * Calculates the inverse of a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate inverse of\n * @returns {quat} out\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\n * Calculates the conjugate of a quat\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate conjugate of\n * @returns {quat} out\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a quaternion from the given 3x3 rotation matrix.\n *\n * NOTE: The resultant quaternion is not normalized, so you should be sure\n * to renormalize the quaternion yourself where necessary.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyMat3} m rotation matrix\n * @returns {quat} out\n * @function\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\n * Creates a quaternion from the given euler angle x, y, z.\n *\n * @param {quat} out the receiving quaternion\n * @param {x} Angle to rotate around X axis in degrees.\n * @param {y} Angle to rotate around Y axis in degrees.\n * @param {z} Angle to rotate around Z axis in degrees.\n * @returns {quat} out\n * @function\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\n * Returns a string representation of a quatenion\n *\n * @param {ReadonlyQuat} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Creates a new quat initialized with values from an existing quaternion\n *\n * @param {ReadonlyQuat} a quaternion to clone\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var clone = vec4.clone;\n/**\n * Creates a new quat initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var fromValues = vec4.fromValues;\n/**\n * Copy the values from one quat to another\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the source quaternion\n * @returns {quat} out\n * @function\n */\n\nexport var copy = vec4.copy;\n/**\n * Set the components of a quat to the given values\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} out\n * @function\n */\n\nexport var set = vec4.set;\n/**\n * Adds two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n * @function\n */\n\nexport var add = vec4.add;\n/**\n * Alias for {@link quat.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Scales a quat by a scalar number\n *\n * @param {quat} out the receiving vector\n * @param {ReadonlyQuat} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {quat} out\n * @function\n */\n\nexport var scale = vec4.scale;\n/**\n * Calculates the dot product of two quat's\n *\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {Number} dot product of a and b\n * @function\n */\n\nexport var dot = vec4.dot;\n/**\n * Performs a linear interpolation between two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n * @function\n */\n\nexport var lerp = vec4.lerp;\n/**\n * Calculates the length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport var length = vec4.length;\n/**\n * Alias for {@link quat.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Calculates the squared length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate squared length of\n * @returns {Number} squared length of a\n * @function\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\n * Alias for {@link quat.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Normalize a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quaternion to normalize\n * @returns {quat} out\n * @function\n */\n\nexport var normalize = vec4.normalize;\n/**\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyQuat} a The first quaternion.\n * @param {ReadonlyQuat} b The second quaternion.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\n * Returns whether or not the quaternions have approximately the same elements in the same position.\n *\n * @param {ReadonlyQuat} a The first vector.\n * @param {ReadonlyQuat} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var equals = vec4.equals;\n/**\n * Sets a quaternion to represent the shortest rotation from one\n * vector to another.\n *\n * Both vectors are assumed to be unit length.\n *\n * @param {quat} out the receiving quaternion.\n * @param {ReadonlyVec3} a the initial vector\n * @param {ReadonlyVec3} b the destination vector\n * @returns {quat} out\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\n * Performs a spherical linear interpolation with two control points\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {ReadonlyQuat} c the third operand\n * @param {ReadonlyQuat} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\n * Sets the specified quaternion with values corresponding to the given\n * axes. Each axis is a vec3 and is expected to be unit length and\n * perpendicular to all other specified axes.\n *\n * @param {ReadonlyVec3} view the vector representing the viewing direction\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\n * @param {ReadonlyVec3} up the vector representing the local \"up\" direction\n * @returns {quat} out\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 2 Dimensional Vector\n * @module vec2\n */\n\n/**\n * Creates a new, empty vec2\n *\n * @returns {vec2} a new 2D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(2);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec2 initialized with values from an existing vector\n *\n * @param {ReadonlyVec2} a vector to clone\n * @returns {vec2} a new 2D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\n * Creates a new vec2 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} a new 2D vector\n */\n\nexport function fromValues(x, y) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\n * Copy the values from one vec2 to another\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the source vector\n * @returns {vec2} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\n * Set the components of a vec2 to the given values\n *\n * @param {vec2} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @returns {vec2} out\n */\n\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\n * Adds two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n return out;\n}\n/**\n * Multiplies two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n return out;\n}\n/**\n * Divides two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n return out;\n}\n/**\n * Math.ceil the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to ceil\n * @returns {vec2} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n/**\n * Math.floor the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to floor\n * @returns {vec2} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n/**\n * Returns the minimum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n return out;\n}\n/**\n * Returns the maximum of two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec2} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n return out;\n}\n/**\n * Math.round the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to round\n * @returns {vec2} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n return out;\n}\n/**\n * Scales a vec2 by a scalar number\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec2} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n/**\n * Adds two vec2's after scaling the second operand by a scalar value\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec2} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return Math.hypot(x, y);\n}\n/**\n * Calculates the squared euclidian distance between two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0],\n y = b[1] - a[1];\n return x * x + y * y;\n}\n/**\n * Calculates the length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0],\n y = a[1];\n return Math.hypot(x, y);\n}\n/**\n * Calculates the squared length of a vec2\n *\n * @param {ReadonlyVec2} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0],\n y = a[1];\n return x * x + y * y;\n}\n/**\n * Negates the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to negate\n * @returns {vec2} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to invert\n * @returns {vec2} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n/**\n * Normalize a vec2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a vector to normalize\n * @returns {vec2} out\n */\n\nexport function normalize(out, a) {\n var x = a[0],\n y = a[1];\n var len = x * x + y * y;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec2's\n *\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1];\n}\n/**\n * Computes the cross product of two vec2's\n * Note that the cross product must by definition produce a 3D vector\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec2's\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the first operand\n * @param {ReadonlyVec2} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec2} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0],\n ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec2} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec2} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n/**\n * Transforms the vec2 with a mat2\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat2(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n/**\n * Transforms the vec2 with a mat2d\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat2d} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat2d(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n/**\n * Transforms the vec2 with a mat3\n * 3rd vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat3} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n/**\n * Transforms the vec2 with a mat4\n * 3rd vector component is implicitly '0'\n * 4th vector component is implicitly '1'\n *\n * @param {vec2} out the receiving vector\n * @param {ReadonlyVec2} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec2} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0];\n var y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n/**\n * Rotate a 2D vector\n * @param {vec2} out The receiving vec2\n * @param {ReadonlyVec2} a The vec2 point to rotate\n * @param {ReadonlyVec2} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec2} out\n */\n\nexport function rotate(out, a, b, rad) {\n //Translate point to the origin\n var p0 = a[0] - b[0],\n p1 = a[1] - b[1],\n sinC = Math.sin(rad),\n cosC = Math.cos(rad); //perform rotation and translate to correct position\n\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n return out;\n}\n/**\n * Get the angle between two 2D vectors\n * @param {ReadonlyVec2} a The first operand\n * @param {ReadonlyVec2} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var x1 = a[0],\n y1 = a[1],\n x2 = b[0],\n y2 = b[1],\n // mag is the product of the magnitudes of a and b\n mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),\n // mag &&.. short circuits if mag == 0\n cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec2 to zero\n *\n * @param {vec2} out the receiving vector\n * @returns {vec2} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec2} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n/**\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec2} a The first vector.\n * @param {ReadonlyVec2} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1];\n var b0 = b[0],\n b1 = b[1];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1));\n}\n/**\n * Alias for {@link vec2.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec2.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec2.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec2.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec2.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec2.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec2.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec2s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 2;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n }\n\n return a;\n };\n}();","import { glMatrix } from 'gl-matrix';\n\nfunction jsToGl(array) {\n let tensor = new glMatrix.ARRAY_TYPE(array.length);\n\n for (let i = 0; i < array.length; ++i) {\n tensor[i] = array[i];\n }\n\n return tensor;\n}\n\nfunction jsToGlSlice(array, offset, stride) {\n let tensor = new glMatrix.ARRAY_TYPE(stride);\n\n for (let i = 0; i < stride; ++i) {\n tensor[i] = array[offset + i];\n }\n\n return tensor;\n}\n\nfunction initGlForMembers(gltfObj, gltf, webGlContext) {\n for (const name of Object.keys(gltfObj)) {\n const member = gltfObj[name];\n\n if (member === undefined) {\n continue;\n }\n if (member.initGl !== undefined) {\n member.initGl(gltf, webGlContext);\n }\n if (Array.isArray(member)) {\n for (const element of member) {\n if (element !== null && element !== undefined && element.initGl !== undefined) {\n element.initGl(gltf, webGlContext);\n }\n }\n }\n }\n}\n\nfunction objectsFromJsons(jsonObjects, GltfType) {\n if (jsonObjects === undefined) {\n return [];\n }\n\n const objects = [];\n for (const jsonObject of jsonObjects) {\n objects.push(objectFromJson(jsonObject, GltfType));\n }\n return objects;\n}\n\nfunction objectFromJson(jsonObject, GltfType) {\n const object = new GltfType();\n object.fromJson(jsonObject);\n return object;\n}\n\nfunction fromKeys(target, jsonObj, ignore = []) {\n for (let k of Object.keys(target)) {\n if (ignore && ignore.find(function (elem) { return elem == k; }) !== undefined) {\n continue; // skip\n }\n if (jsonObj[k] !== undefined) {\n let normalizedK = k.replace(\"^@\", \"\");\n target[normalizedK] = jsonObj[k];\n }\n }\n}\n\nfunction fromParams(parameters, target, jsonObj) {\n for (let p of parameters) {\n if (jsonObj[p] !== undefined) {\n target[p] = jsonObj[p];\n }\n }\n}\n\nfunction stringHash(str, seed = 0) {\n let hash = seed;\n if (str.length === 0) return hash;\n for (let i = 0; i < str.length; i++) {\n let chr = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n}\n\nfunction clamp(number, min, max) {\n return Math.min(Math.max(number, min), max);\n}\n\nfunction getIsGlb(filename) {\n return getExtension(filename) == \"glb\";\n}\n\nfunction getIsGltf(filename) {\n return getExtension(filename) == \"gltf\";\n}\n\nfunction getIsHdr(filename) {\n return getExtension(filename) == \"hdr\";\n}\n\nfunction getExtension(filename) {\n const split = filename.toLowerCase().split(\".\");\n if (split.length == 1) {\n return undefined;\n }\n return split[split.length - 1];\n}\n\nfunction getFileName(filePath) {\n const split = filePath.split(\"/\");\n return split[split.length - 1];\n}\n\nfunction getFileNameWithoutExtension(filePath) {\n const filename = getFileName(filePath);\n const index = filename.lastIndexOf(\".\");\n return filename.slice(0, index);\n}\n\nfunction getContainingFolder(filePath) {\n return filePath.substring(0, filePath.lastIndexOf(\"/\") + 1);\n}\n\nfunction combinePaths() {\n const parts = Array.from(arguments);\n return parts.join(\"/\");\n}\n\nfunction isNetworkError(error) {\n return error === 'network error';\n}\n\n// marker interface used to for parsing the uniforms\nclass UniformStruct { }\n\nclass Timer {\n constructor() {\n this.startTime = undefined;\n this.endTime = undefined;\n this.seconds = undefined;\n }\n\n start() {\n this.startTime = new Date().getTime() / 1000;\n this.endTime = undefined;\n this.seconds = undefined;\n }\n\n stop() {\n this.endTime = new Date().getTime() / 1000;\n this.seconds = this.endTime - this.startTime;\n }\n}\n\nclass AnimationTimer {\n constructor() {\n this.startTime = 0;\n this.paused = true;\n this.fixedTime = null;\n this.pausedTime = 0;\n }\n\n elapsedSec() {\n if (this.paused) {\n return this.pausedTime / 1000;\n }\n else {\n return this.fixedTime || (new Date().getTime() - this.startTime) / 1000;\n }\n }\n\n toggle() {\n if (this.paused) {\n this.unpause();\n }\n else {\n this.pause();\n }\n }\n\n start() {\n this.startTime = new Date().getTime();\n this.paused = false;\n }\n\n pause() {\n this.pausedTime = new Date().getTime() - this.startTime;\n this.paused = true;\n }\n\n unpause() {\n this.startTime += new Date().getTime() - this.startTime - this.pausedTime;\n this.paused = false;\n }\n\n reset() {\n if (!this.paused) {\n // Animation is running.\n this.startTime = new Date().getTime();\n }\n else {\n this.startTime = 0;\n }\n this.pausedTime = 0;\n }\n\n setFixedTime(timeInSec) {\n this.paused = false;\n this.fixedTime = timeInSec;\n }\n}\n\nexport {\n jsToGl,\n jsToGlSlice,\n objectsFromJsons,\n objectFromJson,\n fromKeys,\n fromParams,\n stringHash,\n clamp,\n getIsGlb,\n getIsGltf,\n getIsHdr,\n getExtension,\n getFileName,\n getFileNameWithoutExtension,\n getContainingFolder,\n combinePaths,\n isNetworkError,\n UniformStruct,\n Timer,\n AnimationTimer,\n initGlForMembers\n};\n","import { initGlForMembers, fromKeys } from \"./utils\";\n\n// base class for all gltf objects\nclass GltfObject\n{\n constructor()\n {\n this.extensions = undefined;\n this.extras = undefined;\n }\n\n fromJson(json)\n {\n fromKeys(this, json);\n }\n\n initGl(gltf, webGlContext)\n {\n initGlForMembers(this, gltf, webGlContext);\n }\n}\n\nexport { GltfObject };\n","import { mat4, vec3, quat } from 'gl-matrix';\nimport { fromKeys } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfCamera extends GltfObject\n{\n constructor(\n type = \"perspective\",\n znear = 0.01,\n zfar = Infinity,\n yfov = 45.0 * Math.PI / 180.0,\n aspectRatio = undefined,\n xmag = 1.0,\n ymag = 1.0,\n name = undefined,\n nodeIndex = undefined)\n {\n super();\n this.type = type;\n this.znear = znear;\n this.zfar = zfar;\n this.yfov = yfov; // radians\n this.xmag = xmag;\n this.ymag = ymag;\n this.aspectRatio = aspectRatio;\n this.name = name;\n this.node = nodeIndex;\n }\n\n initGl(gltf, webGlContext)\n {\n super.initGl(gltf, webGlContext);\n\n let cameraIndex = undefined;\n for (let i = 0; i < gltf.nodes.length; i++)\n {\n cameraIndex = gltf.nodes[i].camera;\n if (cameraIndex === undefined)\n {\n continue;\n }\n\n if (gltf.cameras[cameraIndex] === this)\n {\n this.node = i;\n break;\n }\n }\n\n // cameraIndex stays undefined if camera is not assigned to any node\n if(this.node === undefined && cameraIndex !== undefined)\n {\n console.error(\"Invalid node for camera \" + cameraIndex);\n }\n }\n\n fromJson(jsonCamera)\n {\n this.name = name;\n if(jsonCamera.perspective !== undefined)\n {\n this.type = \"perspective\";\n fromKeys(this, jsonCamera.perspective);\n }\n else if(jsonCamera.orthographic !== undefined)\n {\n this.type = \"orthographic\";\n fromKeys(this, jsonCamera.orthographic);\n }\n }\n\n sortPrimitivesByDepth(gltf, drawables)\n {\n // Precompute the distances to avoid their computation during sorting.\n for (const drawable of drawables)\n {\n const modelView = mat4.create();\n mat4.multiply(modelView, this.getViewMatrix(gltf), drawable.node.worldTransform);\n\n // Transform primitive centroid to find the primitive's depth.\n const pos = vec3.transformMat4(vec3.create(), vec3.clone(drawable.primitive.centroid), modelView);\n\n drawable.depth = pos[2];\n }\n\n // 1. Remove primitives that are behind the camera.\n // --> They will never be visible and it is cheap to discard them here.\n // 2. Sort primitives so that the furthest nodes are rendered first.\n // This is required for correct transparency rendering.\n return drawables\n .sort((a, b) => a.depth - b.depth);\n }\n\n getProjectionMatrix()\n {\n const projection = mat4.create();\n\n if (this.type === \"perspective\")\n {\n mat4.perspective(projection, this.yfov, this.aspectRatio, this.znear, this.zfar);\n }\n else if (this.type === \"orthographic\")\n {\n projection[0] = 1.0 / this.xmag;\n projection[5] = 1.0 / this.ymag;\n projection[10] = 2.0 / (this.znear - this.zfar);\n projection[14] = (this.zfar + this.znear) / (this.znear - this.zfar);\n }\n\n return projection;\n }\n\n getViewMatrix(gltf)\n {\n let result = mat4.create();\n mat4.invert(result, this.getTransformMatrix(gltf));\n return result;\n }\n\n getTarget(gltf)\n {\n const target = vec3.create();\n const position = this.getPosition(gltf);\n const lookDirection = this.getLookDirection(gltf);\n vec3.add(target, lookDirection, position);\n return target;\n }\n\n getPosition(gltf)\n {\n const position = vec3.create();\n const node = this.getNode(gltf);\n mat4.getTranslation(position, node.worldTransform);\n return position;\n }\n\n getLookDirection(gltf)\n {\n const direction = vec3.create();\n const rotation = this.getRotation(gltf);\n vec3.transformQuat(direction, vec3.fromValues(0, 0, -1), rotation);\n return direction;\n }\n\n getRotation(gltf)\n {\n const rotation = quat.create();\n const node = this.getNode(gltf);\n mat4.getRotation(rotation, node.worldTransform);\n return rotation;\n }\n\n clone()\n {\n return new gltfCamera(\n this.type,\n this.znear,\n this.zfar,\n this.yfov,\n this.aspectRatio,\n this.xmag,\n this.ymag,\n this.name,\n this.node);\n }\n\n getNode(gltf)\n {\n return gltf.nodes[this.node];\n }\n\n getTransformMatrix(gltf)\n {\n const node = this.getNode(gltf);\n if (node !== undefined && node.worldTransform !== undefined)\n {\n return node.worldTransform;\n }\n return mat4.create();\n\n }\n\n // Returns a JSON object describing the user camera's current values.\n getDescription(gltf)\n {\n const asset = {\n \"generator\": \"gltf-sample-viewer\",\n \"version\": \"2.0\"\n };\n\n const camera = {\n \"type\": this.type\n };\n\n if (this.name !== undefined)\n {\n camera[\"name\"] = this.name;\n }\n\n if (this.type === \"perspective\")\n {\n camera[\"perspective\"] = {};\n if (this.aspectRatio !== undefined)\n {\n camera[\"perspective\"][\"aspectRatio\"] = this.aspectRatio;\n }\n camera[\"perspective\"][\"yfov\"] = this.yfov;\n if (this.zfar != Infinity)\n {\n camera[\"perspective\"][\"zfar\"] = this.zfar;\n }\n camera[\"perspective\"][\"znear\"] = this.znear;\n }\n else if (this.type === \"orthographic\")\n {\n camera[\"orthographic\"] = {};\n camera[\"orthographic\"][\"xmag\"] = this.xmag;\n camera[\"orthographic\"][\"ymag\"] = this.ymag;\n camera[\"orthographic\"][\"zfar\"] = this.zfar;\n camera[\"orthographic\"][\"znear\"] = this.znear;\n }\n\n const mat = this.getTransformMatrix(gltf);\n\n const node = {\n \"camera\": 0,\n \"matrix\": [mat[0], mat[1], mat[2], mat[3],\n mat[4], mat[5], mat[6], mat[7],\n mat[8], mat[9], mat[10], mat[11],\n mat[12], mat[13], mat[14], mat[15]]\n };\n\n if (this.nodeIndex !== undefined && gltf.nodes[this.nodeIndex].name !== undefined)\n {\n node[\"name\"] = gltf.nodes[this.nodeIndex].name;\n }\n\n return {\n \"asset\": asset,\n \"cameras\": [camera],\n \"nodes\": [node]\n };\n }\n}\n\nexport { gltfCamera };\n","import { vec3 } from 'gl-matrix';\nimport { jsToGl } from './utils.js';\n\nfunction getSceneExtents(gltf, sceneIndex, outMin, outMax)\n{\n for (const i of [0, 1, 2])\n {\n outMin[i] = Number.POSITIVE_INFINITY;\n outMax[i] = Number.NEGATIVE_INFINITY;\n }\n\n const scene = gltf.scenes[sceneIndex];\n\n let nodeIndices = scene.nodes.slice();\n while(nodeIndices.length > 0)\n {\n const node = gltf.nodes[nodeIndices.pop()];\n nodeIndices = nodeIndices.concat(node.children);\n\n if (node.mesh === undefined)\n {\n continue;\n }\n\n const mesh = gltf.meshes[node.mesh];\n if (mesh.primitives === undefined)\n {\n continue;\n }\n\n for (const primitive of mesh.primitives)\n {\n const attribute = primitive.glAttributes.find(a => a.attribute == \"POSITION\");\n if (attribute === undefined)\n {\n continue;\n }\n\n const accessor = gltf.accessors[attribute.accessor];\n const assetMin = vec3.create();\n const assetMax = vec3.create();\n getExtentsFromAccessor(accessor, node.worldTransform, assetMin, assetMax);\n\n for (const i of [0, 1, 2])\n {\n outMin[i] = Math.min(outMin[i], assetMin[i]);\n outMax[i] = Math.max(outMax[i], assetMax[i]);\n }\n }\n }\n}\n\nfunction getExtentsFromAccessor(accessor, worldTransform, outMin, outMax)\n{\n const boxMin = vec3.create();\n let min = jsToGl(accessor.min);\n if (accessor.normalized){\n vec3.normalize(min, min);\n }\n vec3.transformMat4(boxMin, min, worldTransform);\n\n const boxMax = vec3.create();\n let max = jsToGl(accessor.max);\n if (accessor.normalized){\n vec3.normalize(max, max);\n }\n vec3.transformMat4(boxMax, max, worldTransform);\n\n const center = vec3.create();\n vec3.add(center, boxMax, boxMin);\n vec3.scale(center, center, 0.5);\n\n const centerToSurface = vec3.create();\n vec3.sub(centerToSurface, boxMax, center);\n\n const radius = vec3.length(centerToSurface);\n\n for (const i of [0, 1, 2])\n {\n outMin[i] = center[i] - radius;\n outMax[i] = center[i] + radius;\n }\n}\n\nexport { getSceneExtents };\n","import { vec3, mat4, quat } from 'gl-matrix';\nimport { gltfCamera } from './camera.js';\nimport { clamp } from './utils.js';\nimport { getSceneExtents } from './gltf_utils.js';\n\n\nconst PanSpeedDenominator = 3500;\nconst MaxNearFarRatio = 10000;\n\nclass UserCamera extends gltfCamera\n{\n /**\n * Create a new user camera.\n */\n constructor()\n {\n super();\n\n this.transform = mat4.create();\n this.rotAroundY = 0;\n this.rotAroundX = 0;\n this.distance = 1;\n this.baseDistance = 1.0;\n this.zoomExponent = 5.0;\n this.zoomFactor = 0.01;\n this.orbitSpeed = 1 / 180;\n this.panSpeed = 1;\n this.sceneExtents = {\n min: vec3.create(),\n max: vec3.create()\n };\n }\n\n getTransformMatrix()\n {\n return this.transform;\n }\n\n /**\n * Sets the vertical FoV of the user camera.\n * @param {number} yfov \n */\n setVerticalFoV(yfov)\n {\n this.yfov = yfov;\n }\n\n /**\n * Returns the current position of the user camera as a vec3.\n */\n getPosition()\n {\n let pos = vec3.create();\n mat4.getTranslation(pos, this.transform);\n return pos;\n }\n\n /**\n * Returns the current rotation of the user camera as quat.\n */\n getRotation()\n {\n let rot = quat.create();\n mat4.getRotation(rot, this.transform);\n return rot;\n }\n\n /**\n * Returns the normalized direction the user camera looks at as vec3.\n */\n getLookDirection()\n {\n let dir = [-this.transform[8], -this.transform[9], -this.transform[10]];\n vec3.normalize(dir, dir);\n return dir;\n }\n\n /**\n * Returns the current target the camera looks at as vec3.\n * This multiplies the viewing direction with the distance.\n * For distance 0 the normalized viewing direction is used.\n */\n getTarget()\n {\n const target = vec3.create();\n const position = this.getPosition();\n let lookDirection = this.getLookDirection();\n if (this.distance != 0 && this.distance != 1)\n {\n lookDirection = lookDirection.map(x => x * this.distance);\n }\n vec3.add(target, lookDirection, position);\n return target;\n }\n\n /**\n * Look from user camera to target.\n * This changes the transformation of the user camera.\n * @param {vec3} from \n * @param {vec3} to \n */\n lookAt(from, to)\n {\n this.transform = mat4.create();\n mat4.lookAt(this.transform, from, to, vec3.fromValues(0, 1, 0));\n }\n\n /**\n * Sets the position of the user camera.\n * @param {vec3} position \n */\n setPosition(position)\n {\n this.transform[12] = position[0];\n this.transform[13] = position[1];\n this.transform[14] = position[2];\n }\n\n /**\n * This rotates the user camera towards the target and sets the position of the user camera\n * according to the current distance.\n * @param {vec3} target \n */\n setTarget(target)\n {\n let pos = vec3.create();\n mat4.getTranslation(pos, this.transform);\n this.transform = mat4.create();\n mat4.lookAt(this.transform, pos, target, vec3.fromValues(0, 1, 0));\n this.setDistanceFromTarget(this.distance, target);\n }\n\n /**\n * Sets the rotation of the camera.\n * Yaw and pitch in euler angles (degrees).\n * @param {number} yaw \n * @param {number} pitch \n */\n setRotation(yaw, pitch)\n {\n const tmpPos = this.getPosition();\n let mat4x = mat4.create();\n let mat4y = mat4.create();\n mat4.fromXRotation(mat4x, pitch);\n mat4.fromYRotation(mat4y, yaw);\n this.transform = mat4y;\n this.setPosition(tmpPos);\n mat4.multiply(this.transform, this.transform, mat4x);\n }\n\n /**\n * Transforms the user camera to look at a target from a specfic distance using the current rotation.\n * This will only change the position of the user camera, not the rotation.\n * Use this function to set the distance.\n * @param {number} distance \n * @param {vec3} target \n */\n setDistanceFromTarget(distance, target)\n {\n const lookDirection = this.getLookDirection();\n const distVec = lookDirection.map(x => x * -distance);\n let pos = vec3.create();\n vec3.add(pos, target, distVec);\n this.setPosition(pos);\n this.distance = distance;\n }\n\n /**\n * Zoom exponentially according to this.zoomFactor and this.zoomExponent.\n * The default zoomFactor provides good zoom speed for values from [-1,1].\n * @param {number} value \n */\n zoomBy(value)\n {\n let target = this.getTarget();\n\n // zoom exponentially\n let zoomDistance = Math.pow(this.distance / this.baseDistance, 1.0 / this.zoomExponent);\n zoomDistance += this.zoomFactor * value;\n zoomDistance = Math.max(zoomDistance, 0.0001);\n this.distance = Math.pow(zoomDistance, this.zoomExponent) * this.baseDistance;\n\n this.setDistanceFromTarget(this.distance, target);\n this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);\n }\n\n /**\n * Orbit around the target.\n * x and y should be in radient and are added to the current rotation.\n * The rotation around the x-axis is limited to 180 degree.\n * The axes are inverted: e.g. if y is positive the camera will look further down.\n * @param {number} x \n * @param {number} y \n */\n orbit(x, y)\n {\n const target = this.getTarget();\n const rotAroundXMax = Math.PI / 2 - 0.01;\n this.rotAroundY += (-x * this.orbitSpeed);\n this.rotAroundX += (-y * this.orbitSpeed);\n this.rotAroundX = clamp(this.rotAroundX, -rotAroundXMax, rotAroundXMax);\n this.setRotation(this.rotAroundY, this.rotAroundX);\n this.setDistanceFromTarget(this.distance, target);\n }\n\n /**\n * Pan the user camera.\n * The axes are inverted: e.g. if y is positive the camera will move down.\n * @param {number} x \n * @param {number} y \n */\n pan(x, y)\n {\n const right = vec3.fromValues(this.transform[0], this.transform[1], this.transform[2]);\n vec3.normalize(right, right);\n vec3.scale(right, right, -x * this.panSpeed * (this.distance / this.baseDistance));\n\n const up = vec3.fromValues(this.transform[4], this.transform[5], this.transform[6]);\n vec3.normalize(up, up);\n vec3.scale(up, up, -y * this.panSpeed * (this.distance / this.baseDistance));\n\n let pos = this.getPosition();\n\n vec3.add(pos, pos, up);\n vec3.add(pos, pos, right);\n\n this.setPosition(pos);\n }\n\n fitPanSpeedToScene(min, max)\n {\n const longestDistance = vec3.distance(min, max);\n this.panSpeed = longestDistance / PanSpeedDenominator;\n }\n\n reset()\n {\n this.transform = mat4.create();\n this.rotAroundX = 0;\n this.rotAroundY = 0;\n this.fitDistanceToExtents(this.sceneExtents.min, this.sceneExtents.max);\n this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max);\n }\n\n /**\n * Calculates a camera position which looks at the center of the scene from an appropriate distance.\n * This calculates near and far plane as well.\n * @param {Gltf} gltf \n * @param {number} sceneIndex \n * @param {number} cameraNodeIndex camera index in gltf file nodes\n */\n fitViewToScene(gltf, sceneIndex, cameraNodeIndex)\n {\n this.transform = mat4.create();\n if (cameraNodeIndex !== undefined) {\n this.setRotationFromDefinedCameraNode(gltf, cameraNodeIndex);\n } else {\n this.rotAroundX = 0;\n this.rotAroundY = 0;\n }\n\n getSceneExtents(gltf, sceneIndex, this.sceneExtents.min, this.sceneExtents.max);\n this.fitDistanceToExtents(this.sceneExtents.min, this.sceneExtents.max);\n this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max);\n\n this.fitPanSpeedToScene(this.sceneExtents.min, this.sceneExtents.max);\n this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max);\n\n }\n\n fitDistanceToExtents(min, max)\n {\n const maxAxisLength = Math.max(max[0] - min[0], max[1] - min[1]);\n const yfov = this.yfov;\n const xfov = this.yfov * this.aspectRatio;\n\n const yZoom = maxAxisLength / 2 / Math.tan(yfov / 2);\n const xZoom = maxAxisLength / 2 / Math.tan(xfov / 2);\n\n\n this.distance = Math.max(xZoom, yZoom);\n this.baseDistance = this.distance;\n }\n\n setRotationFromDefinedCameraNode(gltf, cameraNodeIndex) {\n const rotation = mat4.create();\n const out = mat4.create();\n\n function applyTransform(gltf, node, parentTransform) {\n mat4.multiply(out, parentTransform, node.getLocalTransform());\n\n for (const child of node.children) {\n applyTransform(gltf, gltf.nodes[child], out);\n }\n }\n\n applyTransform(gltf, gltf.nodes[cameraNodeIndex], mat4.create());\n\n mat4.getRotation(rotation, out);\n\n const angles = this.getEulerAngles({\n x: -rotation[0],\n y: -rotation[1],\n z: -rotation[2],\n w: rotation[3]\n });\n\n this.rotAroundX = angles.y;\n this.rotAroundY = -angles.x;\n }\n\n fitCameraTargetToExtents(min, max)\n {\n let target = [0,0,0];\n for (const i of [0, 1, 2])\n {\n target[i] = (max[i] + min[i]) / 2;\n }\n this.setRotation(this.rotAroundY, this.rotAroundX);\n this.setDistanceFromTarget(this.distance, target);\n }\n\n fitCameraPlanesToExtents(min, max)\n {\n // depends only on scene min/max and the camera distance\n\n // Manually increase scene extent just for the camera planes to avoid camera clipping in most situations.\n const longestDistance = 10 * vec3.distance(min, max);\n let zNear = this.distance - (longestDistance * 0.6);\n let zFar = this.distance + (longestDistance * 0.6);\n\n // minimum near plane value needs to depend on far plane value to avoid z fighting or too large near planes\n zNear = Math.max(zNear, zFar / MaxNearFarRatio);\n\n this.znear = zNear;\n this.zfar = zFar;\n }\n\n getEulerAngles(q) {\n let roll = Math.atan2(2 * (q.w * q.x + q.y * q.z), 1 - 2 * (q.x * q.x + q.y * q.y));\n let pitch = Math.asin(2 * (q.w * q.y - q.z * q.x));\n let yaw = Math.atan2(2 * (q.w * q.z + q.x * q.y), 1 - 2 * (q.y * q.y + q.z * q.z));\n return {x: pitch, y: yaw, z: roll};\n }\n}\n\nexport { UserCamera };\n","import { UserCamera } from '../gltf/user_camera.js';\nimport { AnimationTimer } from '../gltf/utils.js';\n\n/**\n * GltfState containing a state for visualization in GltfView\n */\nclass GltfState\n{\n /**\n * GltfState represents all state that can be visualized in a view. You could have\n * multiple GltfStates configured and switch between them on demand.\n * @param {*} view GltfView to which this state belongs\n */\n constructor(view)\n {\n /** loaded gltf data @see ResourceLoader.loadGltf */\n this.gltf = undefined;\n /** loaded environment data @see ResourceLoader.loadEnvironment */\n this.environment = undefined;\n /** user camera @see UserCamera, convenient camera controls */\n this.userCamera = new UserCamera();\n /** gltf scene that is visible in the view */\n this.sceneIndex = 0;\n /**\n * index of the camera that is used to render the view. a\n * value of 'undefined' enables the user camera\n */\n this.cameraIndex = undefined;\n this.userCameraIndex = undefined;\n /** indices of active animations */\n this.animationIndices = [];\n /** animation timer allows to control the animation time */\n this.animationTimer = new AnimationTimer();\n /** KHR_materials_variants */\n this.variant = undefined;\n\n /** parameters used to configure the rendering */\n this.renderingParameters = {\n /** morphing between vertices */\n morphing: true,\n /** skin / skeleton */\n skinning: true,\n\n enabledExtensions: {\n /** KHR_materials_clearcoat */\n KHR_materials_clearcoat: true,\n /** KHR_materials_sheen */\n KHR_materials_sheen: true,\n /** KHR_materials_transmission */\n KHR_materials_transmission: true,\n /** KHR_materials_volume */\n KHR_materials_volume: true,\n /** KHR_materials_ior makes the index of refraction configurable */\n KHR_materials_ior: true,\n /** KHR_materials_specular allows configuring specular color (f0 color) and amount of specular reflection */\n KHR_materials_specular: true,\n /** KHR_materials_iridescence adds a thin-film iridescence effect */\n KHR_materials_iridescence: true,\n KHR_materials_emissive_strength: true,\n },\n /** clear color expressed as list of ints in the range [0, 255] */\n clearColor: [58, 64, 74, 255],\n /** exposure factor */\n exposure: 1.0,\n /** KHR_lights_punctual */\n usePunctual: true,\n /** image based lighting */\n useIBL: true,\n /** image based lighting intensity */\n iblIntensity: 2.19,\n /** render the environment map in the background */\n renderEnvironmentMap: false,\n /** apply blur to the background environment map */\n blurEnvironmentMap: false,\n /** which tonemap to use, use ACES for a filmic effect */\n toneMap: GltfState.ToneMaps.ACES_HILL_EXPOSURE_BOOST,\n /** render some debug output channes, such as for example the normals */\n debugOutput: GltfState.DebugOutput.NONE,\n /**\n * By default the front face of the environment is +Z (90)\n * Front faces:\n * +X = 0 \n * +Z = 90 \n * -X = 180 \n * -Z = 270\n */\n environmentRotation: 90.0,\n /** If this is set to true, directional lights will be generated if IBL is disabled */\n useDirectionalLightsWithDisabledIBL: false,\n /** MSAA used for cases which are not handled by the browser (e.g. Transmission)*/\n internalMSAA: 4\n };\n\n // retain a reference to the view with which the state was created, so that it can be validated\n this._view = view;\n }\n}\n\n/** \n * ToneMaps enum for the different tonemappings that are supported \n * by gltf sample viewer\n*/\nGltfState.ToneMaps = {\n /** don't apply tone mapping */\n NONE: \"None\",\n /** ACES sRGB RRT+ODT implementation for 3D Commerce based on Stephen Hill's implementation with a exposure factor of 1.0 / 0.6 */\n ACES_HILL_EXPOSURE_BOOST: \"ACES Filmic Tone Mapping (Hill - Exposure Boost)\",\n /** fast implementation of the ACES sRGB RRT+ODT based on Krzysztof Narkowicz' implementation*/\n ACES_NARKOWICZ: \"ACES Filmic Tone Mapping (Narkowicz)\",\n /** more accurate implementation of the ACES sRGB RRT+ODT based on Stephen Hill's implementation*/\n ACES_HILL: \"ACES Filmic Tone Mapping (Hill)\",\n};\n\n/**\n * DebugOutput enum for selecting debug output channels\n * such as \"NORMAL\"\n */\nGltfState.DebugOutput = {\n /** standard rendering - debug output is disabled */\n NONE: \"None\",\n\n /** generic debug outputs */\n generic: {\n /** output the texture coordinates 0 */\n UV_COORDS_0: \"Texture Coordinates 0\",\n /** output the texture coordinates 1 */\n UV_COORDS_1: \"Texture Coordinates 1\",\n /** output the world space normals (i.e. with TBN applied) */\n NORMAL: \"Normal Texture\",\n /** output the normal from the TBN*/\n GEOMETRYNORMAL: \"Geometry Normal\",\n /** output the tangent from the TBN*/\n TANGENT: \"Geometry Tangent\",\n /** output the bitangent from the TBN */\n BITANGENT: \"Geometry Bitangent\",\n /** output the world space normals (i.e. with TBN applied) */\n WORLDSPACENORMAL: \"Shading Normal\",\n /** output the alpha value */\n ALPHA: \"Alpha\",\n /** output the occlusion value */\n OCCLUSION: \"Occlusion\",\n /** output the emissive value */\n EMISSIVE: \"Emissive\",\n },\n\n /** output metallic roughness */\n mr: {\n /** output the combined metallic roughness */\n METALLIC_ROUGHNESS: \"Metallic Roughness\",\n /** output the base color value */\n BASECOLOR: \"Base Color\",\n /** output the metallic value from pbr metallic roughness */\n METALLIC: \"Metallic\",\n /** output the roughness value from pbr metallic roughness */\n ROUGHNESS: \"Roughness\",\n },\n\n /** output clearcoat lighting */\n clearcoat: {\n /** output the combined clear coat */\n CLEARCOAT: \"ClearCoat\",\n /** output the clear coat factor */\n CLEARCOAT_FACTOR: \"ClearCoat Factor\",\n /** output the clear coat roughness */\n CLEARCOAT_ROUGHNESS: \"ClearCoat Roughness\",\n /** output the clear coat normal */\n CLEARCOAT_NORMAL: \"ClearCoat Normal\", \n },\n\n /** output sheen lighting */\n sheen: {\n /** output the combined sheen */\n SHEEN: \"Sheen\",\n /** output the sheen color*/\n SHEEN_COLOR: \"Sheen Color\",\n /** output the sheen roughness*/\n SHEEN_ROUGHNESS: \"Sheen Roughness\",\n },\n\n /** output specular lighting */\n specular: {\n /** output the combined specular */\n SPECULAR: \"Specular\",\n /** output the specular factor*/\n SPECULAR_FACTOR: \"Specular Factor\",\n /** output the specular color*/\n SPECULAR_COLOR: \"Specular Color\",\n },\n\n /** output tranmission lighting */\n transmission: {\n /** output the combined transmission/volume */\n TRANSMISSION_VOLUME: \"Transmission/Volume\",\n /** output the transmission factor*/\n TRANSMISSION_FACTOR: \"Transmission Factor\",\n /** output the volume thickness*/\n VOLUME_THICKNESS: \"Volume Thickness\",\n },\n\n /** output tranmission lighting */\n iridescence: {\n /** output the combined iridescence */\n IRIDESCENCE: \"Iridescence\",\n /** output the iridescence factor*/\n IRIDESCENCE_FACTOR: \"Iridescence Factor\",\n /** output the iridescence thickness*/\n IRIDESCENCE_THICKNESS: \"Iridescence Thickness\",\n },\n};\n\nexport { GltfState };\n","const ImageMimeType = {JPEG: \"image/jpeg\", PNG: \"image/png\", HDR: \"image/vnd.radiance\", KTX2: \"image/ktx2\", GLTEXTURE: \"image/texture\"};\n\nexport { ImageMimeType };\n","import { ImageMimeType } from \"../gltf/image_mime_type.js\";\n\nlet GL = undefined;\n\nclass gltfWebGl\n{\n constructor(context)\n {\n this.context = context;\n if(GL === undefined)\n {\n GL = context;\n }\n }\n\n loadWebGlExtensions()\n {\n let EXT_texture_filter_anisotropic = this.context.getExtension(\"EXT_texture_filter_anisotropic\");\n if (EXT_texture_filter_anisotropic)\n {\n this.context.anisotropy = EXT_texture_filter_anisotropic.TEXTURE_MAX_ANISOTROPY_EXT;\n this.context.maxAnisotropy = this.context.getParameter(EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n this.context.supports_EXT_texture_filter_anisotropic = true;\n }\n else\n {\n console.warn(\"Anisotropic filtering is not supported\");\n this.context.supports_EXT_texture_filter_anisotropic = false;\n }\n }\n\n setTexture(loc, gltf, textureInfo, texSlot)\n {\n if (loc === -1)\n {\n return false;\n }\n\n let gltfTex = gltf.textures[textureInfo.index];\n\n if (gltfTex === undefined)\n {\n console.warn(\"Texture is undefined: \" + textureInfo.index);\n return false;\n }\n\n const image = gltf.images[gltfTex.source];\n if (image === undefined)\n {\n console.warn(\"Image is undefined for texture: \" + gltfTex.source);\n return false;\n }\n\n if (gltfTex.glTexture === undefined)\n {\n if (image.mimeType === ImageMimeType.KTX2 ||\n image.mimeType === ImageMimeType.GLTEXTURE)\n {\n // these image resources are directly loaded to a GPU resource by resource loader\n gltfTex.glTexture = image.image;\n }\n else\n {\n // other images will be uploaded in a later step\n gltfTex.glTexture = this.context.createTexture();\n }\n }\n\n this.context.activeTexture(GL.TEXTURE0 + texSlot);\n this.context.bindTexture(gltfTex.type, gltfTex.glTexture);\n\n this.context.uniform1i(loc, texSlot);\n\n if (!gltfTex.initialized)\n {\n const gltfSampler = gltf.samplers[gltfTex.sampler];\n\n if (gltfSampler === undefined)\n {\n console.warn(\"Sampler is undefined for texture: \" + textureInfo.index);\n return false;\n }\n\n this.context.pixelStorei(GL.UNPACK_FLIP_Y_WEBGL, false);\n\n // upload images that are not directly loaded as GPU resource\n if (image.mimeType === ImageMimeType.PNG ||\n image.mimeType === ImageMimeType.JPEG ||\n image.mimeType === ImageMimeType.HDR)\n {\n // the check `GL.SRGB8_ALPHA8 === undefined` is needed as at the moment node-gles does not define the full format enum\n const internalformat = (textureInfo.linear || GL.SRGB8_ALPHA8 === undefined) ? GL.RGBA : GL.SRGB8_ALPHA8;\n this.context.texImage2D(image.type, image.miplevel, internalformat, GL.RGBA, GL.UNSIGNED_BYTE, image.image);\n }\n\n this.setSampler(gltfSampler, gltfTex.type, textureInfo.generateMips);\n\n if (textureInfo.generateMips)\n {\n switch (gltfSampler.minFilter)\n {\n case GL.NEAREST_MIPMAP_NEAREST:\n case GL.NEAREST_MIPMAP_LINEAR:\n case GL.LINEAR_MIPMAP_NEAREST:\n case GL.LINEAR_MIPMAP_LINEAR:\n this.context.generateMipmap(gltfTex.type);\n break;\n default:\n break;\n }\n }\n\n gltfTex.initialized = true;\n }\n\n return gltfTex.initialized;\n }\n\n setIndices(gltf, accessorIndex)\n {\n let gltfAccessor = gltf.accessors[accessorIndex];\n\n if (gltfAccessor.glBuffer === undefined)\n {\n gltfAccessor.glBuffer = this.context.createBuffer();\n\n let data = gltfAccessor.getTypedView(gltf);\n\n if (data === undefined)\n {\n return false;\n }\n\n this.context.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, gltfAccessor.glBuffer);\n this.context.bufferData(GL.ELEMENT_ARRAY_BUFFER, data, GL.STATIC_DRAW);\n }\n else\n {\n this.context.bindBuffer(GL.ELEMENT_ARRAY_BUFFER, gltfAccessor.glBuffer);\n }\n\n return true;\n }\n\n enableAttribute(gltf, attributeLocation, gltfAccessor)\n {\n if (attributeLocation === -1)\n {\n console.warn(\"Tried to access unknown attribute\");\n return false;\n }\n\n if(gltfAccessor.bufferView === undefined)\n {\n console.warn(\"Tried to access undefined bufferview\");\n return true;\n }\n\n let gltfBufferView = gltf.bufferViews[gltfAccessor.bufferView];\n\n if (gltfAccessor.glBuffer === undefined)\n {\n gltfAccessor.glBuffer = this.context.createBuffer();\n\n let data = gltfAccessor.getTypedView(gltf);\n\n if (data === undefined)\n {\n return false;\n }\n\n this.context.bindBuffer(GL.ARRAY_BUFFER, gltfAccessor.glBuffer);\n this.context.bufferData(GL.ARRAY_BUFFER, data, GL.STATIC_DRAW);\n }\n else\n {\n this.context.bindBuffer(GL.ARRAY_BUFFER, gltfAccessor.glBuffer);\n }\n\n this.context.vertexAttribPointer(attributeLocation, gltfAccessor.getComponentCount(gltfAccessor.type), gltfAccessor.componentType, gltfAccessor.normalized, gltfBufferView.byteStride, 0);\n this.context.enableVertexAttribArray(attributeLocation);\n\n return true;\n }\n\n compileShader(shaderIdentifier, isVert, shaderSource)\n {\n const shader = this.context.createShader(isVert ? GL.VERTEX_SHADER : GL.FRAGMENT_SHADER);\n this.context.shaderSource(shader, shaderSource);\n this.context.compileShader(shader);\n const compiled = this.context.getShaderParameter(shader, GL.COMPILE_STATUS);\n\n if (!compiled)\n {\n // output surrounding source code\n let info = \"\";\n const messages = this.context.getShaderInfoLog(shader).split(\"\\n\");\n for(const message of messages)\n {\n \n const matches = message.match(/(WARNING|ERROR): ([0-9]*):([0-9]*):(.*)/i);\n if (matches && matches.length == 5)\n {\n const lineNumber = parseInt(matches[3]) - 1;\n const lines = shaderSource.split(\"\\n\");\n\n info += `${matches[1]}: ${shaderIdentifier}+includes:${lineNumber}: ${matches[4]}`;\n\n for(let i = Math.max(0, lineNumber - 2); i < Math.min(lines.length, lineNumber + 3); i++)\n {\n if (lineNumber === i)\n {\n info += \"->\";\n }\n info += \"\\t\" + lines[i] + \"\\n\";\n }\n }\n else\n {\n info += message + \"\\n\";\n }\n }\n\n throw new Error(\"Could not compile WebGL program '\" + shaderIdentifier + \"': \" + info);\n }\n\n return shader;\n }\n\n linkProgram(vertex, fragment)\n {\n let program = this.context.createProgram();\n this.context.attachShader(program, vertex);\n this.context.attachShader(program, fragment);\n this.context.linkProgram(program);\n\n if (!this.context.getProgramParameter(program, GL.LINK_STATUS))\n {\n var info = this.context.getProgramInfoLog(program);\n throw new Error('Could not link WebGL program. \\n\\n' + info);\n }\n\n return program;\n }\n\n //https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Constants\n setSampler(gltfSamplerObj, type, generateMipmaps) // TEXTURE_2D\n {\n if (generateMipmaps)\n {\n this.context.texParameteri(type, GL.TEXTURE_WRAP_S, gltfSamplerObj.wrapS);\n this.context.texParameteri(type, GL.TEXTURE_WRAP_T, gltfSamplerObj.wrapT);\n }\n else\n {\n this.context.texParameteri(type, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE);\n this.context.texParameteri(type, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE);\n }\n\n // If not mip-mapped, force to non-mip-mapped sampler.\n if (!generateMipmaps && (gltfSamplerObj.minFilter != GL.NEAREST) && (gltfSamplerObj.minFilter != GL.LINEAR))\n {\n if ((gltfSamplerObj.minFilter == GL.NEAREST_MIPMAP_NEAREST) || (gltfSamplerObj.minFilter == GL.NEAREST_MIPMAP_LINEAR))\n {\n this.context.texParameteri(type, GL.TEXTURE_MIN_FILTER, GL.NEAREST);\n }\n else\n {\n this.context.texParameteri(type, GL.TEXTURE_MIN_FILTER, GL.LINEAR);\n }\n }\n else\n {\n this.context.texParameteri(type, GL.TEXTURE_MIN_FILTER, gltfSamplerObj.minFilter);\n }\n this.context.texParameteri(type, GL.TEXTURE_MAG_FILTER, gltfSamplerObj.magFilter);\n\n if (this.context.supports_EXT_texture_filter_anisotropic)\n {\n this.context.texParameterf(type, this.context.anisotropy, this.context.maxAnisotropy); // => 16xAF\n }\n }\n}\n\nexport { gltfWebGl, GL };\n","import { UniformStruct } from '../gltf/utils.js';\nimport { GL } from './webgl.js';\n\nclass gltfShader\n{\n constructor(program, hash, gl)\n {\n this.program = program;\n this.hash = hash;\n this.uniforms = new Map();\n this.attributes = new Map();\n this.unknownAttributes = [];\n this.unknownUniforms = [];\n this.gl = gl;\n\n if(this.program !== undefined)\n {\n const uniformCount = this.gl.context.getProgramParameter(this.program, GL.ACTIVE_UNIFORMS);\n for(let i = 0; i < uniformCount; ++i)\n {\n const info = this.gl.context.getActiveUniform(this.program, i);\n const loc = this.gl.context.getUniformLocation(this.program, info.name);\n this.uniforms.set(info.name, {type: info.type, loc: loc});\n }\n\n const attribCount = this.gl.context.getProgramParameter(this.program, GL.ACTIVE_ATTRIBUTES);\n for(let i = 0; i < attribCount; ++i)\n {\n const info = this.gl.context.getActiveAttrib(this.program, i);\n const loc = this.gl.context.getAttribLocation(this.program, info.name);\n this.attributes.set(info.name, loc);\n }\n }\n }\n\n destroy()\n {\n if (this.program !== undefined)\n {\n this.deleteProgram(this.program);\n }\n\n this.program = undefined;\n }\n\n getAttributeLocation(name)\n {\n const loc = this.attributes.get(name);\n if (loc === undefined)\n {\n if (this.unknownAttributes.find(n => n === name) === undefined)\n {\n console.log(\"Attribute '%s' does not exist\", name);\n this.unknownAttributes.push(name);\n }\n return -1;\n }\n return loc;\n }\n\n getUniformLocation(name)\n {\n const uniform = this.uniforms.get(name);\n if (uniform === undefined)\n {\n if (this.unknownUniforms.find(n => n === name) === undefined)\n {\n this.unknownUniforms.push(name);\n }\n return -1;\n }\n return uniform.loc;\n }\n\n updateUniform(objectName, object, log = false)\n {\n if (object instanceof UniformStruct)\n {\n this.updateUniformStruct(objectName, object, log);\n }\n else if (Array.isArray(object))\n {\n this.updateUniformArray(objectName, object, log);\n }\n else\n {\n this.updateUniformValue(objectName, object, log);\n }\n }\n\n updateUniformArray(arrayName, array, log)\n {\n if(array[0] instanceof UniformStruct)\n {\n for (let i = 0; i < array.length; ++i)\n {\n let element = array[i];\n let uniformName = arrayName + \"[\" + i + \"]\";\n this.updateUniform(uniformName, element, log);\n }\n }else{\n let uniformName = arrayName + \"[0]\";\n\n let flat = [];\n\n if(Array.isArray(array[0]) || array[0].length !== undefined)\n {\n for (let i = 0; i < array.length; ++i)\n {\n flat.push.apply(flat, Array.from(array[i]));\n }\n }\n else\n {\n flat = array;\n }\n\n if(flat.length === 0)\n {\n console.error(\"Failed to flatten uniform array \" + uniformName);\n return;\n }\n\n this.updateUniformValue(uniformName, flat, log);\n }\n }\n\n updateUniformStruct(structName, object, log)\n {\n let memberNames = Object.keys(object);\n for (let memberName of memberNames)\n {\n let uniformName = structName + \".\" + memberName;\n this.updateUniform(uniformName, object[memberName], log);\n }\n }\n\n // upload the values of a uniform with the given name using type resolve to get correct function call\n updateUniformValue(uniformName, value, log)\n {\n const uniform = this.uniforms.get(uniformName);\n\n if(uniform !== undefined)\n {\n switch (uniform.type) {\n case GL.FLOAT:\n {\n if(Array.isArray(value) || value instanceof Float32Array)\n {\n this.gl.context.uniform1fv(uniform.loc, value);\n }else{\n this.gl.context.uniform1f(uniform.loc, value);\n }\n break;\n }\n case GL.FLOAT_VEC2: this.gl.context.uniform2fv(uniform.loc, value); break;\n case GL.FLOAT_VEC3: this.gl.context.uniform3fv(uniform.loc, value); break;\n case GL.FLOAT_VEC4: this.gl.context.uniform4fv(uniform.loc, value); break;\n\n case GL.INT:\n {\n if(Array.isArray(value) || value instanceof Uint32Array || value instanceof Int32Array)\n {\n this.gl.context.uniform1iv(uniform.loc, value);\n }else{\n this.gl.context.uniform1i(uniform.loc, value);\n }\n break;\n }\n case GL.INT_VEC2: this.gl.context.uniform2iv(uniform.loc, value); break;\n case GL.INT_VEC3: this.gl.context.uniform3iv(uniform.loc, value); break;\n case GL.INT_VEC4: this.gl.context.uniform4iv(uniform.loc, value); break;\n\n case GL.FLOAT_MAT2: this.gl.context.uniformMatrix2fv(uniform.loc, false, value); break;\n case GL.FLOAT_MAT3: this.gl.context.uniformMatrix3fv(uniform.loc, false, value); break;\n case GL.FLOAT_MAT4: this.gl.context.uniformMatrix4fv(uniform.loc, false, value); break;\n }\n }\n else if(log)\n {\n console.warn(\"Unkown uniform: \" + uniformName);\n }\n }\n}\n\nexport { gltfShader };\n","import { gltfShader } from './shader.js';\nimport { stringHash } from '../gltf/utils.js';\n\n// THis class generates and caches the shader source text for a given permutation\nclass ShaderCache\n{\n constructor(sources, gl)\n {\n this.sources = sources; // shader name -> source code\n this.shaders = new Map(); // name & permutations hashed -> compiled shader\n this.programs = new Map(); // (vertex shader, fragment shader) -> program\n this.gl = gl;\n\n // resovle / expande sources (TODO: break include cycles)\n for (let [key, src] of this.sources)\n {\n let changed = false;\n for (let [includeName, includeSource] of this.sources)\n {\n //var pattern = RegExp(/#include/);\n const pattern = \"#include <\" + includeName + \">\";\n\n if(src.includes(pattern))\n {\n // only replace the first occurance\n src = src.replace(pattern, includeSource);\n\n // remove the others\n while (src.includes(pattern))\n {\n src = src.replace(pattern, \"\");\n }\n\n changed = true;\n }\n }\n\n if(changed)\n {\n this.sources.set(key, src);\n }\n }\n }\n\n destroy()\n {\n for (let [, shader] of this.shaders.entries())\n {\n this.gl.context.deleteShader(shader);\n shader = undefined;\n }\n\n this.shaders.clear();\n\n for (let [, program] of this.programs)\n {\n program.destroy();\n }\n\n this.programs.clear();\n }\n\n // example args: \"pbr.vert\", [\"NORMALS\", \"TANGENTS\"]\n selectShader(shaderIdentifier, permutationDefines)\n {\n // first check shaders for the exact permutation\n // if not present, check sources and compile it\n // if not present, return null object\n\n const src = this.sources.get(shaderIdentifier);\n if(src === undefined)\n {\n console.log(\"Shader source for \" + shaderIdentifier + \" not found\");\n return null;\n }\n\n const isVert = shaderIdentifier.endsWith(\".vert\");\n let hash = stringHash(shaderIdentifier);\n\n // console.log(shaderIdentifier);\n\n let defines = \"#version 300 es\\n\";\n for(let define of permutationDefines)\n {\n // console.log(define);\n hash ^= stringHash(define);\n defines += \"#define \" + define + \"\\n\";\n }\n\n let shader = this.shaders.get(hash);\n\n if(shader === undefined)\n {\n // console.log(defines);\n // compile this variant\n shader = this.gl.compileShader(shaderIdentifier, isVert, defines + src);\n this.shaders.set(hash, shader);\n }\n\n return hash;\n }\n\n getShaderProgram(vertexShaderHash, fragmentShaderHash)\n {\n // just use a long string for this (the javascript engine should be fast enough with comparing this)\n const hash = String(vertexShaderHash) + \",\" + String(fragmentShaderHash);\n\n let program = this.programs.get(hash);\n\n if (program) // program already linked\n {\n return program;\n }\n else // link this shader program type!\n {\n let linkedProg = this.gl.linkProgram(this.shaders.get(vertexShaderHash), this.shaders.get(fragmentShaderHash));\n if(linkedProg)\n {\n let program = new gltfShader(linkedProg, hash, this.gl);\n this.programs.set(hash, program);\n return program;\n }\n }\n\n return undefined;\n }\n}\n\nexport { ShaderCache };\n","import { mat4, mat3, vec3 } from 'gl-matrix';\n\n\nclass EnvironmentRenderer\n{\n constructor(webgl)\n {\n const gl = webgl.context;\n\n this.indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([\n 1, 2, 0,\n 2, 3, 0,\n 6, 2, 1,\n 1, 5, 6,\n 6, 5, 4,\n 4, 7, 6,\n 6, 3, 2,\n 7, 3, 6,\n 3, 7, 0,\n 7, 4, 0,\n 5, 1, 0,\n 4, 5, 0\n ]), gl.STATIC_DRAW);\n\n this.vertexBuffer = gl.createBuffer()\n gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([\n -1, -1, -1,\n 1, -1, -1,\n 1, 1, -1,\n -1, 1, -1,\n -1, -1, 1,\n 1, -1, 1,\n 1, 1, 1,\n -1, 1, 1\n ]), gl.STATIC_DRAW);\n }\n\n drawEnvironmentMap(webGl, viewProjectionMatrix, state, shaderCache, fragDefines)\n {\n if (state.environment == undefined || state.renderingParameters.renderEnvironmentMap == false)\n {\n return;\n }\n\n const gl = webGl.context;\n\n const vertShader = shaderCache.selectShader(\"cubemap.vert\", []);\n const fragShader = shaderCache.selectShader(\"cubemap.frag\", fragDefines);\n const shader = shaderCache.getShaderProgram(vertShader, fragShader);\n\n gl.useProgram(shader.program);\n webGl.setTexture(shader.getUniformLocation(\"u_GGXEnvSampler\"), state.environment, state.environment.specularEnvMap, 0);\n shader.updateUniform(\"u_MipCount\", state.environment.mipCount);\n shader.updateUniform(\"u_EnvBlurNormalized\", state.renderingParameters.blurEnvironmentMap ? 0.6 : 0.0);\n shader.updateUniform(\"u_EnvIntensity\", state.renderingParameters.iblIntensity);\n\n shader.updateUniform(\"u_ViewProjectionMatrix\", viewProjectionMatrix);\n shader.updateUniform(\"u_Exposure\", state.renderingParameters.exposure, false);\n\n let rotMatrix4 = mat4.create();\n mat4.rotateY(rotMatrix4, rotMatrix4, state.renderingParameters.environmentRotation / 180.0 * Math.PI);\n let rotMatrix3 = mat3.create();\n mat3.fromMat4(rotMatrix3, rotMatrix4);\n shader.updateUniform(\"u_EnvRotation\", rotMatrix3);\n\n gl.frontFace(gl.CCW);\n gl.enable(gl.CULL_FACE);\n gl.disable(gl.BLEND);\n gl.disable(gl.DEPTH_TEST);\n\n const positionAttributeLocation = shader.getAttributeLocation(\"a_position\");\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);\n gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);\n gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);\n gl.enableVertexAttribArray(positionAttributeLocation);\n gl.drawElements(gl.TRIANGLES, 36, gl.UNSIGNED_SHORT, 0);\n\n gl.enable(gl.DEPTH_TEST);\n }\n}\n\nexport { EnvironmentRenderer }\n","import { mat4, vec3, quat } from 'gl-matrix';\nimport { jsToGl, UniformStruct } from './utils.js';\nimport { fromKeys } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfLight extends GltfObject\n{\n constructor(\n type = \"directional\",\n color = [1, 1, 1],\n intensity = 1,\n innerConeAngle = 0,\n outerConeAngle = Math.PI / 4,\n range = -1,\n name = undefined)\n {\n super();\n this.type = type;\n this.color = color;\n this.intensity = intensity;\n this.innerConeAngle = innerConeAngle;\n this.outerConeAngle = outerConeAngle;\n this.range = range;\n this.name = name;\n\n //Can be used to overwrite direction from node\n this.direction = undefined;\n }\n\n initGl(gltf, webGlContext)\n {\n super.initGl(gltf, webGlContext);\n }\n\n fromJson(jsonLight)\n {\n super.fromJson(jsonLight);\n\n if(jsonLight.spot !== undefined)\n {\n fromKeys(this, jsonLight.spot);\n }\n }\n\n toUniform(node)\n {\n const matrix = node?.worldTransform ?? mat4.identity;\n\n // To extract a correct rotation, the scaling component must be eliminated.\n var scale = vec3.fromValues(1, 1, 1);\n mat4.getScaling(scale, matrix);\n const mn = mat4.create();\n for(const col of [0, 1, 2])\n {\n mn[col] = matrix[col] / scale[0];\n mn[col + 4] = matrix[col + 4] / scale[1];\n mn[col + 8] = matrix[col + 8] / scale[2];\n }\n var rotation = quat.create();\n mat4.getRotation(rotation, mn);\n quat.normalize(rotation, rotation);\n\n const uLight = new UniformLight();\n\n const alongNegativeZ = vec3.fromValues(0, 0, -1);\n vec3.transformQuat(uLight.direction, alongNegativeZ, rotation);\n\n var translation = vec3.fromValues(0, 0, 0);\n mat4.getTranslation(translation, matrix);\n uLight.position = translation;\n\n if (this.direction !== undefined)\n {\n uLight.direction = this.direction;\n }\n\n uLight.range = this.range;\n uLight.color = jsToGl(this.color);\n uLight.intensity = this.intensity;\n\n uLight.innerConeCos = Math.cos(this.innerConeAngle);\n uLight.outerConeCos = Math.cos(this.outerConeAngle);\n\n switch(this.type)\n {\n case \"spot\":\n uLight.type = Type_Spot;\n break;\n case \"point\":\n uLight.type = Type_Point;\n break;\n case \"directional\":\n default:\n uLight.type = Type_Directional;\n break;\n }\n\n return uLight;\n }\n}\n\nconst Type_Directional = 0;\nconst Type_Point = 1;\nconst Type_Spot = 2;\n\nclass UniformLight extends UniformStruct\n{\n constructor()\n {\n super();\n\n const defaultDirection = vec3.fromValues(-0.7399, -0.6428, -0.1983);\n this.direction = defaultDirection;\n this.range = -1;\n\n this.color = jsToGl([1, 1, 1]);\n this.intensity = 1;\n\n this.position = jsToGl([0, 0, 0]);\n this.innerConeCos = 0.0;\n\n this.outerConeCos = Math.PI / 4;\n this.type = Type_Directional;\n }\n}\n\nexport { gltfLight };\n","import { mat4, mat3, vec3, quat } from 'gl-matrix';\nimport { ShaderCache } from './shader_cache.js';\nimport { GltfState } from '../GltfState/gltf_state.js';\nimport { gltfWebGl, GL } from './webgl.js';\nimport { EnvironmentRenderer } from './environment_renderer.js';\n\nimport pbrShader from './shaders/pbr.frag';\nimport brdfShader from './shaders/brdf.glsl';\nimport iridescenceShader from './shaders/iridescence.glsl';\nimport materialInfoShader from './shaders/material_info.glsl';\nimport iblShader from './shaders/ibl.glsl';\nimport punctualShader from './shaders/punctual.glsl';\nimport primitiveShader from './shaders/primitive.vert';\nimport texturesShader from './shaders/textures.glsl';\nimport tonemappingShader from './shaders/tonemapping.glsl';\nimport shaderFunctions from './shaders/functions.glsl';\nimport animationShader from './shaders/animation.glsl';\nimport cubemapVertShader from './shaders/cubemap.vert';\nimport cubemapFragShader from './shaders/cubemap.frag';\nimport { gltfLight } from '../gltf/light.js';\n\nclass gltfRenderer\n{\n constructor(context)\n {\n this.shader = undefined; // current shader\n\n this.currentWidth = 0;\n this.currentHeight = 0;\n\n this.webGl = new gltfWebGl(context);\n this.initialized = false;\n this.samples = 4;\n\n // create render target for non transmission materials\n this.opaqueRenderTexture = 0;\n this.opaqueFramebuffer = 0;\n this.opaqueDepthTexture = 0;\n this.opaqueFramebufferWidth = 1024;\n this.opaqueFramebufferHeight = 1024;\n\n const shaderSources = new Map();\n shaderSources.set(\"primitive.vert\", primitiveShader);\n shaderSources.set(\"pbr.frag\", pbrShader);\n shaderSources.set(\"material_info.glsl\", materialInfoShader);\n shaderSources.set(\"brdf.glsl\", brdfShader);\n shaderSources.set(\"iridescence.glsl\", iridescenceShader);\n shaderSources.set(\"ibl.glsl\", iblShader);\n shaderSources.set(\"punctual.glsl\", punctualShader);\n shaderSources.set(\"tonemapping.glsl\", tonemappingShader);\n shaderSources.set(\"textures.glsl\", texturesShader);\n shaderSources.set(\"functions.glsl\", shaderFunctions);\n shaderSources.set(\"animation.glsl\", animationShader);\n shaderSources.set(\"cubemap.vert\", cubemapVertShader);\n shaderSources.set(\"cubemap.frag\", cubemapFragShader);\n\n this.shaderCache = new ShaderCache(shaderSources, this.webGl);\n\n this.webGl.loadWebGlExtensions();\n\n this.visibleLights = [];\n\n this.viewMatrix = mat4.create();\n this.projMatrix = mat4.create();\n this.viewProjectionMatrix = mat4.create();\n\n this.currentCameraPosition = vec3.create();\n\n this.lightKey = new gltfLight();\n this.lightFill = new gltfLight();\n this.lightFill.intensity = 0.5;\n const quatKey = quat.fromValues(\n -0.3535534,\n -0.353553385,\n -0.146446586,\n 0.8535534);\n const quatFill = quat.fromValues(\n -0.8535534,\n 0.146446645,\n -0.353553325,\n -0.353553444);\n this.lightKey.direction = vec3.create();\n this.lightFill.direction = vec3.create();\n vec3.transformQuat(this.lightKey.direction, [0, 0, -1], quatKey);\n vec3.transformQuat(this.lightFill.direction, [0, 0, -1], quatFill);\n }\n\n /////////////////////////////////////////////////////////////////////\n // Render glTF scene graph\n /////////////////////////////////////////////////////////////////////\n\n // app state\n init(state)\n {\n const context = this.webGl.context;\n const maxSamples = context.getParameter(context.MAX_SAMPLES);\n const samples = state.internalMSAA < maxSamples ? state.internalMSAA : maxSamples;\n if (!this.initialized){\n\n context.pixelStorei(GL.UNPACK_COLORSPACE_CONVERSION_WEBGL, GL.NONE);\n context.enable(GL.DEPTH_TEST);\n context.depthFunc(GL.LEQUAL);\n context.colorMask(true, true, true, true);\n context.clearDepth(1.0);\n\n this.opaqueRenderTexture = context.createTexture();\n context.bindTexture(context.TEXTURE_2D, this.opaqueRenderTexture);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR_MIPMAP_LINEAR);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);\n context.texImage2D(context.TEXTURE_2D, 0, context.RGBA, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight, 0, context.RGBA, context.UNSIGNED_BYTE, null);\n context.bindTexture(context.TEXTURE_2D, null);\n\n this.opaqueDepthTexture = context.createTexture();\n context.bindTexture(context.TEXTURE_2D, this.opaqueDepthTexture);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);\n context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);\n context.texImage2D( context.TEXTURE_2D, 0, context.DEPTH_COMPONENT16, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight, 0, context.DEPTH_COMPONENT, context.UNSIGNED_SHORT, null);\n context.bindTexture(context.TEXTURE_2D, null);\n\n\n this.colorRenderBuffer = context.createRenderbuffer();\n context.bindRenderbuffer(context.RENDERBUFFER, this.colorRenderBuffer);\n context.renderbufferStorageMultisample( context.RENDERBUFFER, samples, context.RGBA8, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight);\n\n this.depthRenderBuffer = context.createRenderbuffer();\n context.bindRenderbuffer(context.RENDERBUFFER, this.depthRenderBuffer);\n context.renderbufferStorageMultisample( context.RENDERBUFFER,\n samples,\n context.DEPTH_COMPONENT16, \n this.opaqueFramebufferWidth,\n this.opaqueFramebufferHeight);\n\n this.samples = samples;\n\n this.opaqueFramebufferMSAA = context.createFramebuffer();\n context.bindFramebuffer(context.FRAMEBUFFER, this.opaqueFramebufferMSAA);\n context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, this.colorRenderBuffer);\n context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, this.depthRenderBuffer);\n\n\n this.opaqueFramebuffer = context.createFramebuffer();\n context.bindFramebuffer(context.FRAMEBUFFER, this.opaqueFramebuffer);\n context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.opaqueRenderTexture, 0);\n context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.opaqueDepthTexture, 0);\n context.viewport(0, 0, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight);\n context.bindFramebuffer(context.FRAMEBUFFER, null);\n\n this.initialized = true;\n\n this.environmentRenderer = new EnvironmentRenderer(this.webGl);\n }\n else {\n if (this.samples != samples)\n {\n this.samples = samples;\n context.bindRenderbuffer(context.RENDERBUFFER, this.colorRenderBuffer);\n context.renderbufferStorageMultisample( context.RENDERBUFFER,\n samples,\n context.RGBA8, \n this.opaqueFramebufferWidth,\n this.opaqueFramebufferHeight);\n \n context.bindRenderbuffer(context.RENDERBUFFER, this.depthRenderBuffer);\n context.renderbufferStorageMultisample( context.RENDERBUFFER,\n samples,\n context.DEPTH_COMPONENT16, \n this.opaqueFramebufferWidth,\n this.opaqueFramebufferHeight);\n }\n }\n }\n\n resize(width, height)\n {\n if (this.currentWidth !== width || this.currentHeight !== height)\n {\n this.currentHeight = height;\n this.currentWidth = width;\n this.webGl.context.viewport(0, 0, width, height);\n }\n }\n\n // frame state\n clearFrame(clearColor)\n {\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, null);\n this.webGl.context.clearColor(clearColor[0] / 255.0, clearColor[1] / 255.0, clearColor[2] / 255.0, clearColor[3] / 255.0);\n this.webGl.context.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, this.opaqueFramebuffer);\n this.webGl.context.clearColor(clearColor[0] / 255.0, clearColor[1] / 255.0, clearColor[2] / 255.0, clearColor[3] / 255.0);\n this.webGl.context.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, null);\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, this.opaqueFramebufferMSAA);\n this.webGl.context.clearColor(clearColor[0] / 255.0, clearColor[1] / 255.0, clearColor[2] / 255.0, clearColor[3] / 255.0);\n this.webGl.context.clear(GL.COLOR_BUFFER_BIT | GL.DEPTH_BUFFER_BIT);\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, null);\n }\n\n prepareScene(state, scene) {\n this.nodes = scene.gatherNodes(state.gltf);\n\n // collect drawables by essentially zipping primitives (for geometry and material)\n // and nodes for the transform\n const drawables = this.nodes\n .filter(node => node.mesh !== undefined)\n .reduce((acc, node) => acc.concat(state.gltf.meshes[node.mesh].primitives.map( primitive => {\n return {node: node, primitive: primitive};\n })), [])\n .filter(({primitive}) => primitive.material !== undefined);\n\n this.opaqueDrawables = drawables\n .filter(({primitive}) => state.gltf.materials[primitive.material].alphaMode !== \"BLEND\"\n && (state.gltf.materials[primitive.material].extensions === undefined\n || state.gltf.materials[primitive.material].extensions.KHR_materials_transmission === undefined));\n\n // transparent drawables need sorting before they can be drawn\n this.transparentDrawables = drawables\n .filter(({primitive}) => state.gltf.materials[primitive.material].alphaMode === \"BLEND\"\n && (state.gltf.materials[primitive.material].extensions === undefined\n || state.gltf.materials[primitive.material].extensions.KHR_materials_transmission === undefined));\n\n this.transmissionDrawables = drawables\n .filter(({primitive}) => state.gltf.materials[primitive.material].extensions !== undefined\n && state.gltf.materials[primitive.material].extensions.KHR_materials_transmission !== undefined);\n }\n\n // render complete gltf scene with given camera\n drawScene(state, scene)\n {\n if (this.preparedScene !== scene) {\n this.prepareScene(state, scene);\n this.preparedScene = scene;\n }\n\n let currentCamera = undefined;\n\n if (state.cameraIndex === undefined)\n {\n currentCamera = state.userCamera;\n }\n else\n {\n currentCamera = state.gltf.cameras[state.cameraIndex].clone();\n }\n\n currentCamera.aspectRatio = this.currentWidth / this.currentHeight;\n if(currentCamera.aspectRatio > 1.0) {\n currentCamera.xmag = currentCamera.ymag * currentCamera.aspectRatio; \n } else {\n currentCamera.ymag = currentCamera.xmag / currentCamera.aspectRatio;\n }\n\n this.projMatrix = currentCamera.getProjectionMatrix();\n this.viewMatrix = currentCamera.getViewMatrix(state.gltf);\n this.currentCameraPosition = currentCamera.getPosition(state.gltf);\n\n this.visibleLights = this.getVisibleLights(state.gltf, scene.nodes);\n if (this.visibleLights.length === 0 && !state.renderingParameters.useIBL &&\n state.renderingParameters.useDirectionalLightsWithDisabledIBL)\n {\n this.visibleLights.push([null, this.lightKey]);\n this.visibleLights.push([null, this.lightFill]);\n }\n\n mat4.multiply(this.viewProjectionMatrix, this.projMatrix, this.viewMatrix);\n\n // Update skins.\n for (const node of this.nodes)\n {\n if (node.mesh !== undefined && node.skin !== undefined)\n {\n this.updateSkin(state, node);\n }\n }\n\n // If any transmissive drawables are present, render all opaque and transparent drawables into a separate framebuffer.\n if (this.transmissionDrawables.length > 0) {\n // Render transmission sample texture\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, this.opaqueFramebufferMSAA);\n this.webGl.context.viewport(0, 0, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight);\n\n // Render environment for the transmission background\n this.environmentRenderer.drawEnvironmentMap(this.webGl, this.viewProjectionMatrix, state, this.shaderCache, [\"LINEAR_OUTPUT 1\"]);\n\n for (const drawable of this.opaqueDrawables)\n {\n let renderpassConfiguration = {};\n renderpassConfiguration.linearOutput = true;\n this.drawPrimitive(state, renderpassConfiguration, drawable.primitive, drawable.node, this.viewProjectionMatrix);\n }\n\n this.transparentDrawables = currentCamera.sortPrimitivesByDepth(state.gltf, this.transparentDrawables);\n for (const drawable of this.transparentDrawables)\n {\n let renderpassConfiguration = {};\n renderpassConfiguration.linearOutput = true;\n this.drawPrimitive(state, renderpassConfiguration, drawable.primitive, drawable.node, this.viewProjectionMatrix);\n }\n\n // \"blit\" the multisampled opaque texture into the color buffer, which adds antialiasing\n this.webGl.context.bindFramebuffer(this.webGl.context.READ_FRAMEBUFFER, this.opaqueFramebufferMSAA);\n this.webGl.context.bindFramebuffer(this.webGl.context.DRAW_FRAMEBUFFER, this.opaqueFramebuffer);\n this.webGl.context.blitFramebuffer(0, 0, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight, 0, 0, this.opaqueFramebufferWidth, this.opaqueFramebufferHeight, this.webGl.context.COLOR_BUFFER_BIT, this.webGl.context.NEAREST);\n\n // Create Framebuffer Mipmaps\n this.webGl.context.bindTexture(this.webGl.context.TEXTURE_2D, this.opaqueRenderTexture);\n\n this.webGl.context.generateMipmap(this.webGl.context.TEXTURE_2D);\n }\n\n // Render to canvas\n this.webGl.context.bindFramebuffer(this.webGl.context.FRAMEBUFFER, null);\n this.webGl.context.viewport(0, 0, this.currentWidth, this.currentHeight);\n\n // Render environment\n const fragDefines = [];\n this.pushFragParameterDefines(fragDefines, state);\n this.environmentRenderer.drawEnvironmentMap(this.webGl, this.viewProjectionMatrix, state, this.shaderCache, fragDefines);\n\n for (const drawable of this.opaqueDrawables)\n { \n let renderpassConfiguration = {};\n renderpassConfiguration.linearOutput = false;\n this.drawPrimitive(state, renderpassConfiguration, drawable.primitive, drawable.node, this.viewProjectionMatrix);\n }\n\n // filter materials with transmission extension\n this.transmissionDrawables = currentCamera.sortPrimitivesByDepth(state.gltf, this.transmissionDrawables);\n for (const drawable of this.transmissionDrawables)\n {\n let renderpassConfiguration = {};\n renderpassConfiguration.linearOutput = false;\n this.drawPrimitive(state, renderpassConfiguration, drawable.primitive, drawable.node, this.viewProjectionMatrix, this.opaqueRenderTexture);\n }\n\n for (const drawable of this.transparentDrawables)\n {\n let renderpassConfiguration = {};\n renderpassConfiguration.linearOutput = false;\n this.drawPrimitive(state, renderpassConfiguration, drawable.primitive, drawable.node, this.viewProjectionMatrix);\n }\n }\n\n // vertices with given material\n drawPrimitive(state, renderpassConfiguration, primitive, node, viewProjectionMatrix, transmissionSampleTexture)\n {\n if (primitive.skip) return;\n\n let material;\n if(primitive.mappings !== undefined && state.variant != \"default\")\n {\n const names = state.gltf.variants.map(obj => obj.name);\n const idx = names.indexOf(state.variant);\n let materialIdx = primitive.material;\n primitive.mappings.forEach(element => {\n if(element.variants.indexOf(idx) >= 0)\n {\n materialIdx = element.material;\n }\n });\n material = state.gltf.materials[materialIdx];\n }\n else\n {\n material = state.gltf.materials[primitive.material];\n }\n\n //select shader permutation, compile and link program.\n\n let vertDefines = [];\n this.pushVertParameterDefines(vertDefines, state.renderingParameters, state.gltf, node, primitive);\n vertDefines = primitive.getDefines().concat(vertDefines);\n\n let fragDefines = material.getDefines(state.renderingParameters).concat(vertDefines);\n if(renderpassConfiguration.linearOutput === true)\n {\n fragDefines.push(\"LINEAR_OUTPUT 1\");\n }\n this.pushFragParameterDefines(fragDefines, state);\n \n const fragmentHash = this.shaderCache.selectShader(material.getShaderIdentifier(), fragDefines);\n const vertexHash = this.shaderCache.selectShader(primitive.getShaderIdentifier(), vertDefines);\n\n if (fragmentHash && vertexHash)\n {\n this.shader = this.shaderCache.getShaderProgram(fragmentHash, vertexHash);\n }\n\n if (this.shader === undefined)\n {\n return;\n }\n\n this.webGl.context.useProgram(this.shader.program);\n\n if (state.renderingParameters.usePunctual)\n {\n this.applyLights();\n }\n\n // update model dependant matrices once per node\n this.shader.updateUniform(\"u_ViewProjectionMatrix\", viewProjectionMatrix);\n this.shader.updateUniform(\"u_ModelMatrix\", node.worldTransform);\n this.shader.updateUniform(\"u_NormalMatrix\", node.normalMatrix, false);\n this.shader.updateUniform(\"u_Exposure\", state.renderingParameters.exposure, false);\n this.shader.updateUniform(\"u_Camera\", this.currentCameraPosition, false);\n\n this.updateAnimationUniforms(state, node, primitive);\n\n if (mat4.determinant(node.worldTransform) < 0.0)\n {\n this.webGl.context.frontFace(GL.CW);\n }\n else\n {\n this.webGl.context.frontFace(GL.CCW);\n }\n\n if (material.doubleSided)\n {\n this.webGl.context.disable(GL.CULL_FACE);\n }\n else\n {\n this.webGl.context.enable(GL.CULL_FACE);\n }\n\n if (material.alphaMode === 'BLEND')\n {\n this.webGl.context.enable(GL.BLEND);\n this.webGl.context.blendFuncSeparate(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA, GL.ONE, GL.ONE_MINUS_SRC_ALPHA);\n this.webGl.context.blendEquation(GL.FUNC_ADD);\n }\n else\n {\n this.webGl.context.disable(GL.BLEND);\n }\n\n const drawIndexed = primitive.indices !== undefined;\n if (drawIndexed)\n {\n if (!this.webGl.setIndices(state.gltf, primitive.indices))\n {\n return;\n }\n }\n\n let vertexCount = 0;\n for (const attribute of primitive.glAttributes)\n {\n const gltfAccessor = state.gltf.accessors[attribute.accessor];\n vertexCount = gltfAccessor.count;\n\n const location = this.shader.getAttributeLocation(attribute.name);\n if (location < 0)\n {\n continue; // only skip this attribute\n }\n if (!this.webGl.enableAttribute(state.gltf, location, gltfAccessor))\n {\n return; // skip this primitive\n }\n }\n\n for (let [uniform, val] of material.getProperties().entries())\n {\n this.shader.updateUniform(uniform, val, false);\n }\n\n let textureIndex = 0;\n for (; textureIndex < material.textures.length; ++textureIndex)\n {\n let info = material.textures[textureIndex];\n const location = this.shader.getUniformLocation(info.samplerName);\n\n if (location < 0)\n {\n console.log(\"Unable to find uniform location of \"+info.samplerName);\n continue; // only skip this texture\n }\n if (!this.webGl.setTexture(location, state.gltf, info, textureIndex)) // binds texture and sampler\n {\n return; // skip this material\n }\n }\n\n // set the morph target texture\n if (primitive.morphTargetTextureInfo !== undefined) \n {\n const location = this.shader.getUniformLocation(primitive.morphTargetTextureInfo.samplerName);\n if (location < 0)\n {\n console.log(\"Unable to find uniform location of \" + primitive.morphTargetTextureInfo.samplerName);\n }\n\n this.webGl.setTexture(location, state.gltf, primitive.morphTargetTextureInfo, textureIndex); // binds texture and sampler\n textureIndex++;\n }\n\n // set the joints texture\n if (state.renderingParameters.skinning && node.skin !== undefined && primitive.hasWeights && primitive.hasJoints) \n {\n const skin = state.gltf.skins[node.skin];\n const location = this.shader.getUniformLocation(skin.jointTextureInfo.samplerName);\n if (location < 0)\n {\n console.log(\"Unable to find uniform location of \" + skin.jointTextureInfo.samplerName);\n }\n\n this.webGl.setTexture(location, state.gltf, skin.jointTextureInfo, textureIndex); // binds texture and sampler\n textureIndex++;\n }\n\n let textureCount = textureIndex;\n if (state.renderingParameters.useIBL && state.environment !== undefined)\n {\n textureCount = this.applyEnvironmentMap(state, textureCount);\n }\n\n if (state.renderingParameters.usePunctual && state.environment !== undefined)\n {\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_SheenELUT\"), state.environment, state.environment.sheenELUT, textureCount++);\n }\n\n if(transmissionSampleTexture !== undefined && (state.renderingParameters.useIBL || state.renderingParameters.usePunctual)\n && state.environment && state.renderingParameters.enabledExtensions.KHR_materials_transmission)\n {\n this.webGl.context.activeTexture(GL.TEXTURE0 + textureCount);\n this.webGl.context.bindTexture(this.webGl.context.TEXTURE_2D, this.opaqueRenderTexture);\n this.webGl.context.uniform1i(this.shader.getUniformLocation(\"u_TransmissionFramebufferSampler\"), textureCount);\n textureCount++;\n\n this.webGl.context.uniform2i(this.shader.getUniformLocation(\"u_TransmissionFramebufferSize\"), this.opaqueFramebufferWidth, this.opaqueFramebufferHeight);\n\n this.webGl.context.uniformMatrix4fv(this.shader.getUniformLocation(\"u_ModelMatrix\"),false, node.worldTransform);\n this.webGl.context.uniformMatrix4fv(this.shader.getUniformLocation(\"u_ViewMatrix\"),false, this.viewMatrix);\n this.webGl.context.uniformMatrix4fv(this.shader.getUniformLocation(\"u_ProjectionMatrix\"),false, this.projMatrix);\n }\n\n if (drawIndexed)\n {\n const indexAccessor = state.gltf.accessors[primitive.indices];\n this.webGl.context.drawElements(primitive.mode, indexAccessor.count, indexAccessor.componentType, 0);\n }\n else\n {\n this.webGl.context.drawArrays(primitive.mode, 0, vertexCount);\n }\n\n for (const attribute of primitive.glAttributes)\n {\n const location = this.shader.getAttributeLocation(attribute.name);\n if (location < 0)\n {\n continue; // skip this attribute\n }\n this.webGl.context.disableVertexAttribArray(location);\n }\n }\n\n /// Compute a list of lights instantiated by one or more nodes as a list of node-light tuples.\n getVisibleLights(gltf, nodes)\n {\n let nodeLights = [];\n\n for (const nodeIndex of nodes) {\n const node = gltf.nodes[nodeIndex];\n\n if (node.children !== undefined) {\n nodeLights = nodeLights.concat(this.getVisibleLights(gltf, node.children));\n }\n\n const lightIndex = node.extensions?.KHR_lights_punctual?.light;\n if (lightIndex === undefined) {\n continue;\n }\n const light = gltf.lights[lightIndex];\n nodeLights.push([node, light]);\n }\n\n return nodeLights;\n }\n\n updateSkin(state, node)\n {\n if (state.renderingParameters.skinning && state.gltf.skins !== undefined)\n {\n const skin = state.gltf.skins[node.skin];\n skin.computeJoints(state.gltf, node, this.webGl.context);\n }\n }\n\n pushVertParameterDefines(vertDefines, parameters, gltf, node, primitive)\n {\n // skinning\n if (parameters.skinning && node.skin !== undefined && primitive.hasWeights && primitive.hasJoints)\n {\n vertDefines.push(\"USE_SKINNING 1\");\n }\n\n // morphing\n if (parameters.morphing && node.mesh !== undefined && primitive.targets.length > 0)\n {\n const mesh = gltf.meshes[node.mesh];\n if (mesh.getWeightsAnimated() !== undefined && mesh.getWeightsAnimated().length > 0)\n {\n vertDefines.push(\"USE_MORPHING 1\");\n vertDefines.push(\"WEIGHT_COUNT \" + mesh.getWeightsAnimated().length);\n }\n }\n }\n\n updateAnimationUniforms(state, node, primitive)\n {\n if (state.renderingParameters.morphing && node.mesh !== undefined && primitive.targets.length > 0)\n {\n const mesh = state.gltf.meshes[node.mesh];\n const weightsAnimated = mesh.getWeightsAnimated();\n if (weightsAnimated !== undefined && weightsAnimated.length > 0)\n {\n this.shader.updateUniformArray(\"u_morphWeights\", weightsAnimated);\n }\n }\n }\n\n pushFragParameterDefines(fragDefines, state)\n {\n if (state.renderingParameters.usePunctual)\n {\n fragDefines.push(\"USE_PUNCTUAL 1\");\n fragDefines.push(`LIGHT_COUNT ${this.visibleLights.length}`);\n }\n\n if (state.renderingParameters.useIBL && state.environment)\n {\n fragDefines.push(\"USE_IBL 1\");\n }\n\n switch (state.renderingParameters.toneMap)\n {\n case (GltfState.ToneMaps.ACES_NARKOWICZ):\n fragDefines.push(\"TONEMAP_ACES_NARKOWICZ 1\");\n break;\n case (GltfState.ToneMaps.ACES_HILL):\n fragDefines.push(\"TONEMAP_ACES_HILL 1\");\n break;\n case (GltfState.ToneMaps.ACES_HILL_EXPOSURE_BOOST):\n fragDefines.push(\"TONEMAP_ACES_HILL_EXPOSURE_BOOST 1\");\n break;\n case (GltfState.ToneMaps.NONE):\n default:\n break;\n }\n\n let debugOutputMapping = [\n {debugOutput: GltfState.DebugOutput.NONE, shaderDefine: \"DEBUG_NONE\"},\n \n {debugOutput: GltfState.DebugOutput.generic.WORLDSPACENORMAL, shaderDefine: \"DEBUG_NORMAL_SHADING\"},\n {debugOutput: GltfState.DebugOutput.generic.NORMAL, shaderDefine: \"DEBUG_NORMAL_TEXTURE\"},\n {debugOutput: GltfState.DebugOutput.generic.GEOMETRYNORMAL, shaderDefine: \"DEBUG_NORMAL_GEOMETRY\"},\n {debugOutput: GltfState.DebugOutput.generic.TANGENT, shaderDefine: \"DEBUG_TANGENT\"},\n {debugOutput: GltfState.DebugOutput.generic.BITANGENT, shaderDefine: \"DEBUG_BITANGENT\"},\n {debugOutput: GltfState.DebugOutput.generic.ALPHA, shaderDefine: \"DEBUG_ALPHA\"},\n {debugOutput: GltfState.DebugOutput.generic.UV_COORDS_0, shaderDefine: \"DEBUG_UV_0\"},\n {debugOutput: GltfState.DebugOutput.generic.UV_COORDS_1, shaderDefine: \"DEBUG_UV_1\"},\n {debugOutput: GltfState.DebugOutput.generic.OCCLUSION, shaderDefine: \"DEBUG_OCCLUSION\"},\n {debugOutput: GltfState.DebugOutput.generic.EMISSIVE, shaderDefine: \"DEBUG_EMISSIVE\"},\n\n {debugOutput: GltfState.DebugOutput.mr.METALLIC_ROUGHNESS, shaderDefine: \"DEBUG_METALLIC_ROUGHNESS\"},\n {debugOutput: GltfState.DebugOutput.mr.BASECOLOR, shaderDefine: \"DEBUG_BASE_COLOR\"},\n {debugOutput: GltfState.DebugOutput.mr.ROUGHNESS, shaderDefine: \"DEBUG_ROUGHNESS\"},\n {debugOutput: GltfState.DebugOutput.mr.METALLIC, shaderDefine: \"DEBUG_METALLIC\"},\n \n {debugOutput: GltfState.DebugOutput.clearcoat.CLEARCOAT, shaderDefine: \"DEBUG_CLEARCOAT\"},\n {debugOutput: GltfState.DebugOutput.clearcoat.CLEARCOAT_FACTOR, shaderDefine: \"DEBUG_CLEARCOAT_FACTOR\"},\n {debugOutput: GltfState.DebugOutput.clearcoat.CLEARCOAT_ROUGHNESS, shaderDefine: \"DEBUG_CLEARCOAT_ROUGHNESS\"},\n {debugOutput: GltfState.DebugOutput.clearcoat.CLEARCOAT_NORMAL, shaderDefine: \"DEBUG_CLEARCOAT_NORMAL\"},\n \n {debugOutput: GltfState.DebugOutput.sheen.SHEEN, shaderDefine: \"DEBUG_SHEEN\"},\n {debugOutput: GltfState.DebugOutput.sheen.SHEEN_COLOR, shaderDefine: \"DEBUG_SHEEN_COLOR\"},\n {debugOutput: GltfState.DebugOutput.sheen.SHEEN_ROUGHNESS, shaderDefine: \"DEBUG_SHEEN_ROUGHNESS\"},\n\n {debugOutput: GltfState.DebugOutput.specular.SPECULAR, shaderDefine: \"DEBUG_SPECULAR\"},\n {debugOutput: GltfState.DebugOutput.specular.SPECULAR_FACTOR, shaderDefine: \"DEBUG_SPECULAR_FACTOR\"},\n {debugOutput: GltfState.DebugOutput.specular.SPECULAR_COLOR, shaderDefine: \"DEBUG_SPECULAR_COLOR\"},\n\n {debugOutput: GltfState.DebugOutput.transmission.TRANSMISSION_VOLUME, shaderDefine: \"DEBUG_TRANSMISSION_VOLUME\"},\n {debugOutput: GltfState.DebugOutput.transmission.TRANSMISSION_FACTOR, shaderDefine: \"DEBUG_TRANSMISSION_FACTOR\"},\n {debugOutput: GltfState.DebugOutput.transmission.VOLUME_THICKNESS, shaderDefine: \"DEBUG_VOLUME_THICKNESS\"},\n\n {debugOutput: GltfState.DebugOutput.iridescence.IRIDESCENCE, shaderDefine: \"DEBUG_IRIDESCENCE\"},\n {debugOutput: GltfState.DebugOutput.iridescence.IRIDESCENCE_FACTOR, shaderDefine: \"DEBUG_IRIDESCENCE_FACTOR\"},\n {debugOutput: GltfState.DebugOutput.iridescence.IRIDESCENCE_THICKNESS, shaderDefine: \"DEBUG_IRIDESCENCE_THICKNESS\"},\n ];\n\n let mappingCount = 0;\n let mappingFound = false;\n for (let mapping of debugOutputMapping) {\n fragDefines.push(mapping.shaderDefine+\" \"+mappingCount++);\n if(state.renderingParameters.debugOutput == mapping.debugOutput){\n fragDefines.push(\"DEBUG \"+mapping.shaderDefine);\n mappingFound = true;\n }\n }\n\n if(mappingFound == false) { // fallback\n fragDefines.push(\"DEBUG DEBUG_NONE\");\n }\n\n }\n\n applyLights()\n {\n const uniforms = [];\n for (const [node, light] of this.visibleLights)\n {\n uniforms.push(light.toUniform(node));\n }\n if (uniforms.length > 0)\n {\n this.shader.updateUniform(\"u_Lights\", uniforms);\n }\n }\n\n applyEnvironmentMap(state, texSlotOffset)\n {\n const environment = state.environment;\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_LambertianEnvSampler\"), environment, environment.diffuseEnvMap, texSlotOffset++);\n\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_GGXEnvSampler\"), environment, environment.specularEnvMap, texSlotOffset++);\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_GGXLUT\"), environment, environment.lut, texSlotOffset++);\n\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_CharlieEnvSampler\"), environment, environment.sheenEnvMap, texSlotOffset++);\n this.webGl.setTexture(this.shader.getUniformLocation(\"u_CharlieLUT\"), environment, environment.sheenLUT, texSlotOffset++);\n\n this.shader.updateUniform(\"u_MipCount\", environment.mipCount);\n\n let rotMatrix4 = mat4.create();\n mat4.rotateY(rotMatrix4, rotMatrix4, state.renderingParameters.environmentRotation / 180.0 * Math.PI);\n let rotMatrix3 = mat3.create();\n mat3.fromMat4(rotMatrix3, rotMatrix4);\n this.shader.updateUniform(\"u_EnvRotation\", rotMatrix3);\n\n this.shader.updateUniform(\"u_EnvIntensity\", state.renderingParameters.iblIntensity);\n\n return texSlotOffset;\n }\n\n destroy()\n {\n this.shaderCache.destroy();\n }\n}\n\nexport { gltfRenderer };\n","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return toString.call(val) === '[object Array]';\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nfunction isArrayBuffer(val) {\n return toString.call(val) === '[object ArrayBuffer]';\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(val) {\n return (typeof FormData !== 'undefined') && (val instanceof FormData);\n}\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (toString.call(val) !== '[object Object]') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nfunction isDate(val) {\n return toString.call(val) === '[object Date]';\n}\n\n/**\n * Determine if a value is a File\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nfunction isFile(val) {\n return toString.call(val) === '[object File]';\n}\n\n/**\n * Determine if a value is a Blob\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nfunction isBlob(val) {\n return toString.call(val) === '[object Blob]';\n}\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nfunction isURLSearchParams(val) {\n return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;\n}\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","'use strict';\n\n/**\n * Update an Error with the specified config, error code, and response.\n *\n * @param {Error} error The error to update.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The error.\n */\nmodule.exports = function enhanceError(error, config, code, request, response) {\n error.config = config;\n if (code) {\n error.code = code;\n }\n\n error.request = request;\n error.response = response;\n error.isAxiosError = true;\n\n error.toJSON = function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code\n };\n };\n return error;\n};\n","'use strict';\n\nvar enhanceError = require('./enhanceError');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {Object} config The config.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nmodule.exports = function createError(message, config, code, request, response) {\n var error = new Error(message);\n return enhanceError(error, config, code, request, response);\n};\n","'use strict';\n\nvar createError = require('./createError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(createError(\n 'Request failed with status code ' + response.status,\n response.config,\n null,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d\\+\\-\\.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar createError = require('../core/createError');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n\n if (utils.isFormData(requestData)) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(resolve, reject, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(createError('Request aborted', config, 'ECONNABORTED', request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(createError('Network Error', config, null, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(createError(\n timeoutErrorMessage,\n config,\n config.transitional && config.transitional.clarifyTimeoutError ? 'ETIMEDOUT' : 'ECONNABORTED',\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken) {\n // Handle cancellation\n config.cancelToken.promise.then(function onCanceled(cancel) {\n if (!request) {\n return;\n }\n\n request.abort();\n reject(cancel);\n // Clean up request\n request = null;\n });\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar normalizeHeaderName = require('./helpers/normalizeHeaderName');\nvar enhanceError = require('./core/enhanceError');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('./adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('./adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n },\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n if (utils.isObject(data) || (headers && headers['Content-Type'] === 'application/json')) {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw enhanceError(e, this, 'E_JSON_PARSE');\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n }\n};\n\ndefaults.headers = {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('./../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n var valueFromConfig2Keys = ['url', 'method', 'data'];\n var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy', 'params'];\n var defaultToConfig2Keys = [\n 'baseURL', 'transformRequest', 'transformResponse', 'paramsSerializer',\n 'timeout', 'timeoutMessage', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',\n 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'decompress',\n 'maxContentLength', 'maxBodyLength', 'maxRedirects', 'transport', 'httpAgent',\n 'httpsAgent', 'cancelToken', 'socketPath', 'responseEncoding'\n ];\n var directMergeKeys = ['validateStatus'];\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n }\n\n utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n }\n });\n\n utils.forEach(mergeDeepPropertiesKeys, mergeDeepProperties);\n\n utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n config[prop] = getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n utils.forEach(directMergeKeys, function merge(prop) {\n if (prop in config2) {\n config[prop] = getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n config[prop] = getMergedValue(undefined, config1[prop]);\n }\n });\n\n var axiosKeys = valueFromConfig2Keys\n .concat(mergeDeepPropertiesKeys)\n .concat(defaultToConfig2Keys)\n .concat(directMergeKeys);\n\n var otherKeys = Object\n .keys(config1)\n .concat(Object.keys(config2))\n .filter(function filterAxiosKeys(key) {\n return axiosKeys.indexOf(key) === -1;\n });\n\n utils.forEach(otherKeys, mergeDeepProperties);\n\n return config;\n};\n","'use strict';\n\nvar pkg = require('./../../package.json');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\nvar currentVerArr = pkg.version.split('.');\n\n/**\n * Compare package versions\n * @param {string} version\n * @param {string?} thanVersion\n * @returns {boolean}\n */\nfunction isOlderVersion(version, thanVersion) {\n var pkgVersionArr = thanVersion ? thanVersion.split('.') : currentVerArr;\n var destVer = version.split('.');\n for (var i = 0; i < 3; i++) {\n if (pkgVersionArr[i] > destVer[i]) {\n return true;\n } else if (pkgVersionArr[i] < destVer[i]) {\n return false;\n }\n }\n return false;\n}\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator\n * @param {string?} version\n * @param {string} message\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n var isDeprecated = version && isOlderVersion(version);\n\n function formatMessage(opt, desc) {\n return '[Axios v' + pkg.version + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new Error(formatMessage(opt, ' has been removed in ' + version));\n }\n\n if (isDeprecated && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new TypeError('option ' + opt + ' must be ' + result);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw Error('Unknown option ' + opt);\n }\n }\n}\n\nmodule.exports = {\n isOlderVersion: isOlderVersion,\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof config === 'string') {\n config = arguments[1] || {};\n config.url = arguments[0];\n } else {\n config = config || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n forcedJSONParsing: validators.transitional(validators.boolean, '1.0.0'),\n clarifyTimeoutError: validators.transitional(validators.boolean, '1.0.0')\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\\?/, '');\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: data\n }));\n };\n});\n\nmodule.exports = Axios;\n","'use strict';\n\n/**\n * A `Cancel` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction Cancel(message) {\n this.message = message;\n}\n\nCancel.prototype.toString = function toString() {\n return 'Cancel' + (this.message ? ': ' + this.message : '');\n};\n\nCancel.prototype.__CANCEL__ = true;\n\nmodule.exports = Cancel;\n","'use strict';\n\nvar Cancel = require('./Cancel');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new Cancel(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `Cancel` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return (typeof payload === 'object') && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Factory for creating new instances\naxios.create = function create(instanceConfig) {\n return createInstance(mergeConfig(axios.defaults, instanceConfig));\n};\n\n// Expose Cancel & CancelToken\naxios.Cancel = require('./cancel/Cancel');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","module.exports = require('./lib/axios');","import { GL } from '../Renderer/webgl.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfAccessor extends GltfObject\n{\n constructor()\n {\n super();\n this.bufferView = undefined;\n this.byteOffset = 0;\n this.componentType = undefined;\n this.normalized = false;\n this.count = undefined;\n this.type = undefined;\n this.max = undefined;\n this.min = undefined;\n this.sparse = undefined;\n this.name = undefined;\n\n // non gltf\n this.glBuffer = undefined;\n this.typedView = undefined;\n this.filteredView = undefined;\n this.normalizedFilteredView = undefined;\n this.normalizedTypedView = undefined;\n }\n\n // getTypedView provides a view to the accessors data in form of\n // a TypedArray. This data can directly be passed to vertexAttribPointer\n getTypedView(gltf)\n {\n if (this.typedView !== undefined)\n {\n return this.typedView;\n }\n\n if (this.bufferView !== undefined)\n {\n const bufferView = gltf.bufferViews[this.bufferView];\n const buffer = gltf.buffers[bufferView.buffer];\n const byteOffset = this.byteOffset + bufferView.byteOffset;\n\n const componentSize = this.getComponentSize(this.componentType);\n let componentCount = this.getComponentCount(this.type);\n\n let arrayLength = 0;\n if(bufferView.byteStride !== 0)\n {\n if (componentSize !== 0)\n {\n arrayLength = bufferView.byteStride / componentSize * (this.count - 1) + componentCount;\n }\n else\n {\n console.warn(\"Invalid component type in accessor '\" + (this.name ? this.name : \"\") + \"'\");\n }\n }\n else\n {\n arrayLength = this.count * componentCount;\n }\n\n if (arrayLength * componentSize > buffer.buffer.byteLength - byteOffset)\n {\n arrayLength = (buffer.buffer.byteLength - byteOffset) / componentSize;\n console.warn(\"Count in accessor '\" + (this.name ? this.name : \"\") + \"' is too large.\");\n }\n\n switch (this.componentType)\n {\n case GL.BYTE:\n this.typedView = new Int8Array(buffer.buffer, byteOffset, arrayLength);\n break;\n case GL.UNSIGNED_BYTE:\n this.typedView = new Uint8Array(buffer.buffer, byteOffset, arrayLength);\n break;\n case GL.SHORT:\n this.typedView = new Int16Array(buffer.buffer, byteOffset, arrayLength);\n break;\n case GL.UNSIGNED_SHORT:\n this.typedView = new Uint16Array(buffer.buffer, byteOffset, arrayLength);\n break;\n case GL.UNSIGNED_INT:\n this.typedView = new Uint32Array(buffer.buffer, byteOffset, arrayLength);\n break;\n case GL.FLOAT:\n this.typedView = new Float32Array(buffer.buffer, byteOffset, arrayLength);\n break;\n }\n }\n else if (this.sparse !== undefined)\n {\n this.typedView = this.createView();\n }\n\n if (this.typedView === undefined)\n {\n console.warn(\"Failed to convert buffer view to typed view!: \" + this.bufferView);\n }\n else if (this.sparse !== undefined)\n {\n this.applySparse(gltf, this.typedView);\n }\n\n return this.typedView;\n }\n\n // getNormalizedTypedView provides an alternative view to the accessors data,\n // where quantized data is already normalized. This is useful if the data is not passed\n // to vertexAttribPointer but used immediately (like e.g. animations)\n getNormalizedTypedView(gltf)\n {\n if(this.normalizedTypedView !== undefined)\n {\n return this.normalizedTypedView;\n }\n\n const typedView = this.getTypedView(gltf);\n this.normalizedTypedView = this.normalized ? gltfAccessor.dequantize(typedView, this.componentType) : typedView;\n return this.normalizedTypedView;\n }\n\n // getDeinterlacedView provides a view to the accessors data in form of\n // a TypedArray. In contrast to getTypedView, getDeinterlacedView deinterlaces\n // data, i.e. stripping padding and unrelated components from the array. It then\n // only contains the data of the accessor\n getDeinterlacedView(gltf)\n {\n if (this.filteredView !== undefined)\n {\n return this.filteredView;\n }\n\n const componentSize = this.getComponentSize(this.componentType);\n const componentCount = this.getComponentCount(this.type);\n const arrayLength = this.count * componentCount;\n\n let func = 'getFloat32';\n switch (this.componentType)\n {\n case GL.BYTE:\n this.filteredView = new Int8Array(arrayLength);\n func = 'getInt8';\n break;\n case GL.UNSIGNED_BYTE:\n this.filteredView = new Uint8Array(arrayLength);\n func = 'getUint8';\n break;\n case GL.SHORT:\n this.filteredView = new Int16Array(arrayLength);\n func = 'getInt16';\n break;\n case GL.UNSIGNED_SHORT:\n this.filteredView = new Uint16Array(arrayLength);\n func = 'getUint16';\n break;\n case GL.UNSIGNED_INT:\n this.filteredView = new Uint32Array(arrayLength);\n func = 'getUint32';\n break;\n case GL.FLOAT:\n this.filteredView = new Float32Array(arrayLength);\n func = 'getFloat32';\n break;\n default:\n return;\n }\n\n if (this.bufferView !== undefined) {\n const bufferView = gltf.bufferViews[this.bufferView];\n const buffer = gltf.buffers[bufferView.buffer];\n const byteOffset = this.byteOffset + bufferView.byteOffset;\n const stride = bufferView.byteStride !== 0 ? bufferView.byteStride : componentCount * componentSize;\n const dataView = new DataView(buffer.buffer, byteOffset, this.count * stride);\n for (let i = 0; i < arrayLength; ++i)\n {\n const offset = Math.floor(i / componentCount) * stride + (i % componentCount) * componentSize;\n this.filteredView[i] = dataView[func](offset, true);\n }\n }\n else if (this.sparse !== undefined)\n {\n this.filteredView = this.createView();\n }\n\n if (this.sparse !== undefined)\n {\n this.applySparse(gltf, this.filteredView);\n }\n\n return this.filteredView;\n }\n\n createView()\n {\n const size = this.count * this.getComponentCount(this.type);\n if (this.componentType == GL.BYTE) return new Int8Array(size);\n if (this.componentType == GL.UNSIGNED_BYTE) return new Uint8Array(size);\n if (this.componentType == GL.SHORT) return new Int16Array(size);\n if (this.componentType == GL.UNSIGNED_SHORT) return new Uint16Array(size);\n if (this.componentType == GL.UNSIGNED_INT) return new Uint32Array(size);\n if (this.componentType == GL.FLOAT) return new Float32Array(size);\n return undefined;\n }\n\n // getNormalizedDeinterlacedView provides an alternative view to the accessors data,\n // where quantized data is already normalized. This is useful if the data is not passed\n // to vertexAttribPointer but used immediately (like e.g. animations)\n getNormalizedDeinterlacedView(gltf)\n {\n if(this.normalizedFilteredView !== undefined)\n {\n return this.normalizedFilteredView;\n }\n\n const filteredView = this.getDeinterlacedView(gltf);\n this.normalizedFilteredView = this.normalized ? gltfAccessor.dequantize(filteredView, this.componentType) : filteredView;\n return this.normalizedFilteredView;\n }\n\n applySparse(gltf, view)\n {\n // Gather indices.\n\n const indicesBufferView = gltf.bufferViews[this.sparse.indices.bufferView];\n const indicesBuffer = gltf.buffers[indicesBufferView.buffer];\n const indicesByteOffset = this.sparse.indices.byteOffset + indicesBufferView.byteOffset;\n\n const indicesComponentSize = this.getComponentSize(this.sparse.indices.componentType);\n let indicesComponentCount = 1;\n\n if(indicesBufferView.byteStride !== 0)\n {\n indicesComponentCount = indicesBufferView.byteStride / indicesComponentSize;\n }\n\n const indicesArrayLength = this.sparse.count * indicesComponentCount;\n\n let indicesTypedView;\n switch (this.sparse.indices.componentType)\n {\n case GL.UNSIGNED_BYTE:\n indicesTypedView = new Uint8Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);\n break;\n case GL.UNSIGNED_SHORT:\n indicesTypedView = new Uint16Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);\n break;\n case GL.UNSIGNED_INT:\n indicesTypedView = new Uint32Array(indicesBuffer.buffer, indicesByteOffset, indicesArrayLength);\n break;\n }\n\n // Gather values.\n\n const valuesBufferView = gltf.bufferViews[this.sparse.values.bufferView];\n const valuesBuffer = gltf.buffers[valuesBufferView.buffer];\n const valuesByteOffset = this.sparse.values.byteOffset + valuesBufferView.byteOffset;\n\n const valuesComponentSize = this.getComponentSize(this.componentType);\n let valuesComponentCount = this.getComponentCount(this.type);\n\n if(valuesBufferView.byteStride !== 0)\n {\n valuesComponentCount = valuesBufferView.byteStride / valuesComponentSize;\n }\n\n const valuesArrayLength = this.sparse.count * valuesComponentCount;\n\n let valuesTypedView;\n switch (this.componentType)\n {\n case GL.BYTE:\n valuesTypedView = new Int8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n case GL.UNSIGNED_BYTE:\n valuesTypedView = new Uint8Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n case GL.SHORT:\n valuesTypedView = new Int16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n case GL.UNSIGNED_SHORT:\n valuesTypedView = new Uint16Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n case GL.UNSIGNED_INT:\n valuesTypedView = new Uint32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n case GL.FLOAT:\n valuesTypedView = new Float32Array(valuesBuffer.buffer, valuesByteOffset, valuesArrayLength);\n break;\n }\n\n // Overwrite values.\n\n for(let i = 0; i < this.sparse.count; ++i)\n {\n for(let k = 0; k < valuesComponentCount; ++k)\n {\n view[indicesTypedView[i] * valuesComponentCount + k] = valuesTypedView[i * valuesComponentCount + k];\n }\n }\n }\n\n // dequantize can be used to perform the normalization from WebGL2 vertexAttribPointer explicitly\n static dequantize(typedArray, componentType)\n {\n switch (componentType)\n {\n case GL.BYTE:\n return new Float32Array(typedArray).map(c => Math.max(c / 127.0, -1.0));\n case GL.UNSIGNED_BYTE:\n return new Float32Array(typedArray).map(c => c / 255.0);\n case GL.SHORT:\n return new Float32Array(typedArray).map(c => Math.max(c / 32767.0, -1.0));\n case GL.UNSIGNED_SHORT:\n return new Float32Array(typedArray).map(c => c / 65535.0);\n default:\n return typedArray;\n }\n }\n\n getComponentCount(type)\n {\n return CompononentCount.get(type);\n }\n\n getComponentSize(componentType)\n {\n switch (componentType)\n {\n case GL.BYTE:\n case GL.UNSIGNED_BYTE:\n return 1;\n case GL.SHORT:\n case GL.UNSIGNED_SHORT:\n return 2;\n case GL.UNSIGNED_INT:\n case GL.FLOAT:\n return 4;\n default:\n return 0;\n }\n }\n\n destroy()\n {\n if (this.glBuffer !== undefined)\n {\n // TODO: this breaks the dependency direction\n WebGl.context.deleteBuffer(this.glBuffer);\n }\n\n this.glBuffer = undefined;\n }\n}\n\nconst CompononentCount = new Map(\n [\n [\"SCALAR\", 1],\n [\"VEC2\", 2],\n [\"VEC3\", 3],\n [\"VEC4\", 4],\n [\"MAT2\", 4],\n [\"MAT3\", 9],\n [\"MAT4\", 16]\n ]\n);\n\nexport { gltfAccessor };\n","import axios from 'axios';\nimport { getContainingFolder } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfBuffer extends GltfObject\n{\n constructor()\n {\n super();\n this.uri = undefined;\n this.byteLength = undefined;\n this.name = undefined;\n\n // non gltf\n this.buffer = undefined; // raw data blob\n }\n\n load(gltf, additionalFiles = undefined)\n {\n if (this.buffer !== undefined)\n {\n console.error(\"buffer has already been loaded\");\n return;\n }\n\n const self = this;\n return new Promise(function(resolve)\n {\n if (!self.setBufferFromFiles(additionalFiles, resolve) &&\n !self.setBufferFromUri(gltf, resolve))\n {\n console.error(\"Was not able to resolve buffer with uri '%s'\", self.uri);\n resolve();\n }\n });\n }\n\n setBufferFromUri(gltf, callback)\n {\n if (this.uri === undefined)\n {\n return false;\n }\n\n const self = this;\n axios.get(getContainingFolder(gltf.path) + this.uri, { responseType: 'arraybuffer'})\n .then(function(response)\n {\n self.buffer = response.data;\n callback();\n });\n return true;\n }\n\n setBufferFromFiles(files, callback)\n {\n if (this.uri === undefined || files === undefined)\n {\n return false;\n }\n\n const foundFile = files.find(function(file)\n {\n if (file.name === this.uri || file.fullPath === this.uri)\n {\n return true;\n }\n }, this);\n\n if (foundFile === undefined)\n {\n return false;\n }\n\n const self = this;\n const reader = new FileReader();\n reader.onloadend = function(event)\n {\n self.buffer = event.target.result;\n callback();\n };\n reader.readAsArrayBuffer(foundFile);\n\n return true;\n }\n}\n\nexport { gltfBuffer };\n","import { GltfObject } from './gltf_object.js';\n\nclass gltfBufferView extends GltfObject\n{\n constructor()\n {\n super();\n this.buffer = undefined;\n this.byteOffset = 0;\n this.byteLength = undefined;\n this.byteStride = 0;\n this.target = undefined;\n this.name = undefined;\n }\n}\n\nexport { gltfBufferView };\n","class AsyncFileReader\n{\n static async readAsArrayBuffer(path) {\n return new Promise( (resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.onerror = reject;\n reader.readAsArrayBuffer(path);\n });\n }\n\n static async readAsText(path) {\n return new Promise( (resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.onerror = reject;\n reader.readAsText(path);\n });\n }\n\n static async readAsDataURL(path) {\n return new Promise( (resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n reader.onerror = reject;\n reader.readAsDataURL(path);\n });\n }\n}\n\nexport { AsyncFileReader };\n","/*\n Copyright (c) 2008, Adobe Systems Incorporated\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without \n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the \n documentation and/or other materials provided with the distribution.\n \n * Neither the name of Adobe Systems Incorporated nor the names of its \n contributors may be used to endorse or promote products derived from \n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR \n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\nJPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009\n\nBasic GUI blocking jpeg encoder\n*/\n\nvar btoa = btoa || function(buf) {\n return Buffer.from(buf).toString('base64');\n};\n\nfunction JPEGEncoder(quality) {\n var self = this;\n\tvar fround = Math.round;\n\tvar ffloor = Math.floor;\n\tvar YTable = new Array(64);\n\tvar UVTable = new Array(64);\n\tvar fdtbl_Y = new Array(64);\n\tvar fdtbl_UV = new Array(64);\n\tvar YDC_HT;\n\tvar UVDC_HT;\n\tvar YAC_HT;\n\tvar UVAC_HT;\n\t\n\tvar bitcode = new Array(65535);\n\tvar category = new Array(65535);\n\tvar outputfDCTQuant = new Array(64);\n\tvar DU = new Array(64);\n\tvar byteout = [];\n\tvar bytenew = 0;\n\tvar bytepos = 7;\n\t\n\tvar YDU = new Array(64);\n\tvar UDU = new Array(64);\n\tvar VDU = new Array(64);\n\tvar clt = new Array(256);\n\tvar RGB_YUV_TABLE = new Array(2048);\n\tvar currentQuality;\n\t\n\tvar ZigZag = [\n\t\t\t 0, 1, 5, 6,14,15,27,28,\n\t\t\t 2, 4, 7,13,16,26,29,42,\n\t\t\t 3, 8,12,17,25,30,41,43,\n\t\t\t 9,11,18,24,31,40,44,53,\n\t\t\t10,19,23,32,39,45,52,54,\n\t\t\t20,22,33,38,46,51,55,60,\n\t\t\t21,34,37,47,50,56,59,61,\n\t\t\t35,36,48,49,57,58,62,63\n\t\t];\n\t\n\tvar std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];\n\tvar std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];\n\tvar std_ac_luminance_values = [\n\t\t\t0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,\n\t\t\t0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,\n\t\t\t0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,\n\t\t\t0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,\n\t\t\t0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,\n\t\t\t0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,\n\t\t\t0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,\n\t\t\t0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,\n\t\t\t0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,\n\t\t\t0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,\n\t\t\t0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,\n\t\t\t0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,\n\t\t\t0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,\n\t\t\t0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,\n\t\t\t0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,\n\t\t\t0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,\n\t\t\t0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,\n\t\t\t0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,\n\t\t\t0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,\n\t\t\t0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tvar std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];\n\tvar std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];\n\tvar std_ac_chrominance_values = [\n\t\t\t0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,\n\t\t\t0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,\n\t\t\t0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,\n\t\t\t0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,\n\t\t\t0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,\n\t\t\t0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,\n\t\t\t0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,\n\t\t\t0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,\n\t\t\t0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,\n\t\t\t0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,\n\t\t\t0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,\n\t\t\t0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,\n\t\t\t0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,\n\t\t\t0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,\n\t\t\t0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,\n\t\t\t0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,\n\t\t\t0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,\n\t\t\t0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,\n\t\t\t0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,\n\t\t\t0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tfunction initQuantTables(sf){\n\t\t\tvar YQT = [\n\t\t\t\t16, 11, 10, 16, 24, 40, 51, 61,\n\t\t\t\t12, 12, 14, 19, 26, 58, 60, 55,\n\t\t\t\t14, 13, 16, 24, 40, 57, 69, 56,\n\t\t\t\t14, 17, 22, 29, 51, 87, 80, 62,\n\t\t\t\t18, 22, 37, 56, 68,109,103, 77,\n\t\t\t\t24, 35, 55, 64, 81,104,113, 92,\n\t\t\t\t49, 64, 78, 87,103,121,120,101,\n\t\t\t\t72, 92, 95, 98,112,100,103, 99\n\t\t\t];\n\t\t\t\n\t\t\tfor (var i = 0; i < 64; i++) {\n\t\t\t\tvar t = ffloor((YQT[i]*sf+50)/100);\n\t\t\t\tif (t < 1) {\n\t\t\t\t\tt = 1;\n\t\t\t\t} else if (t > 255) {\n\t\t\t\t\tt = 255;\n\t\t\t\t}\n\t\t\t\tYTable[ZigZag[i]] = t;\n\t\t\t}\n\t\t\tvar UVQT = [\n\t\t\t\t17, 18, 24, 47, 99, 99, 99, 99,\n\t\t\t\t18, 21, 26, 66, 99, 99, 99, 99,\n\t\t\t\t24, 26, 56, 99, 99, 99, 99, 99,\n\t\t\t\t47, 66, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99\n\t\t\t];\n\t\t\tfor (var j = 0; j < 64; j++) {\n\t\t\t\tvar u = ffloor((UVQT[j]*sf+50)/100);\n\t\t\t\tif (u < 1) {\n\t\t\t\t\tu = 1;\n\t\t\t\t} else if (u > 255) {\n\t\t\t\t\tu = 255;\n\t\t\t\t}\n\t\t\t\tUVTable[ZigZag[j]] = u;\n\t\t\t}\n\t\t\tvar aasf = [\n\t\t\t\t1.0, 1.387039845, 1.306562965, 1.175875602,\n\t\t\t\t1.0, 0.785694958, 0.541196100, 0.275899379\n\t\t\t];\n\t\t\tvar k = 0;\n\t\t\tfor (var row = 0; row < 8; row++)\n\t\t\t{\n\t\t\t\tfor (var col = 0; col < 8; col++)\n\t\t\t\t{\n\t\t\t\t\tfdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tfdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction computeHuffmanTbl(nrcodes, std_table){\n\t\t\tvar codevalue = 0;\n\t\t\tvar pos_in_table = 0;\n\t\t\tvar HT = new Array();\n\t\t\tfor (var k = 1; k <= 16; k++) {\n\t\t\t\tfor (var j = 1; j <= nrcodes[k]; j++) {\n\t\t\t\t\tHT[std_table[pos_in_table]] = [];\n\t\t\t\t\tHT[std_table[pos_in_table]][0] = codevalue;\n\t\t\t\t\tHT[std_table[pos_in_table]][1] = k;\n\t\t\t\t\tpos_in_table++;\n\t\t\t\t\tcodevalue++;\n\t\t\t\t}\n\t\t\t\tcodevalue*=2;\n\t\t\t}\n\t\t\treturn HT;\n\t\t}\n\t\t\n\t\tfunction initHuffmanTbl()\n\t\t{\n\t\t\tYDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);\n\t\t\tUVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);\n\t\t\tYAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);\n\t\t\tUVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);\n\t\t}\n\t\n\t\tfunction initCategoryNumber()\n\t\t{\n\t\t\tvar nrlower = 1;\n\t\t\tvar nrupper = 2;\n\t\t\tfor (var cat = 1; cat <= 15; cat++) {\n\t\t\t\t//Positive numbers\n\t\t\t\tfor (var nr = nrlower; nr>0] \t= 38470 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+ 512)>>0] \t= 7471 * i + 0x8000;\n\t\t\t\tRGB_YUV_TABLE[(i+ 768)>>0] \t= -11059 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1024)>>0] \t= -21709 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1280)>>0] \t= 32768 * i + 0x807FFF;\n\t\t\t\tRGB_YUV_TABLE[(i+1536)>>0] \t= -27439 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1792)>>0] \t= - 5329 * i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// IO functions\n\t\tfunction writeBits(bs)\n\t\t{\n\t\t\tvar value = bs[0];\n\t\t\tvar posval = bs[1]-1;\n\t\t\twhile ( posval >= 0 ) {\n\t\t\t\tif (value & (1 << posval) ) {\n\t\t\t\t\tbytenew |= (1 << bytepos);\n\t\t\t\t}\n\t\t\t\tposval--;\n\t\t\t\tbytepos--;\n\t\t\t\tif (bytepos < 0) {\n\t\t\t\t\tif (bytenew == 0xFF) {\n\t\t\t\t\t\twriteByte(0xFF);\n\t\t\t\t\t\twriteByte(0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twriteByte(bytenew);\n\t\t\t\t\t}\n\t\t\t\t\tbytepos=7;\n\t\t\t\t\tbytenew=0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeByte(value)\n\t\t{\n\t\t\t//byteout.push(clt[value]); // write char directly instead of converting later\n byteout.push(value);\n\t\t}\n\t\n\t\tfunction writeWord(value)\n\t\t{\n\t\t\twriteByte((value>>8)&0xFF);\n\t\t\twriteByte((value )&0xFF);\n\t\t}\n\t\t\n\t\t// DCT & quantization core\n\t\tfunction fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}\n\t\t\n\t\tfunction writeAPP0()\n\t\t{\n\t\t\twriteWord(0xFFE0); // marker\n\t\t\twriteWord(16); // length\n\t\t\twriteByte(0x4A); // J\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0x49); // I\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0); // = \"JFIF\",'\\0'\n\t\t\twriteByte(1); // versionhi\n\t\t\twriteByte(1); // versionlo\n\t\t\twriteByte(0); // xyunits\n\t\t\twriteWord(1); // xdensity\n\t\t\twriteWord(1); // ydensity\n\t\t\twriteByte(0); // thumbnwidth\n\t\t\twriteByte(0); // thumbnheight\n\t\t}\n\n\t\tfunction writeAPP1(exifBuffer) {\n\t\t\tif (!exifBuffer) return;\n\n\t\t\twriteWord(0xFFE1); // APP1 marker\n\n\t\t\tif (exifBuffer[0] === 0x45 &&\n\t\t\t\t\texifBuffer[1] === 0x78 &&\n\t\t\t\t\texifBuffer[2] === 0x69 &&\n\t\t\t\t\texifBuffer[3] === 0x66) {\n\t\t\t\t// Buffer already starts with EXIF, just use it directly\n\t\t\t\twriteWord(exifBuffer.length + 2); // length is buffer + length itself!\n\t\t\t} else {\n\t\t\t\t// Buffer doesn't start with EXIF, write it for them\n\t\t\t\twriteWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\\0 + length itself!\n\t\t\t\twriteByte(0x45); // E\n\t\t\t\twriteByte(0x78); // X\n\t\t\t\twriteByte(0x69); // I\n\t\t\t\twriteByte(0x66); // F\n\t\t\t\twriteByte(0); // = \"EXIF\",'\\0'\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < exifBuffer.length; i++) {\n\t\t\t\twriteByte(exifBuffer[i]);\n\t\t\t}\n\t\t}\n\n\t\tfunction writeSOF0(width, height)\n\t\t{\n\t\t\twriteWord(0xFFC0); // marker\n\t\t\twriteWord(17); // length, truecolor YUV JPG\n\t\t\twriteByte(8); // precision\n\t\t\twriteWord(height);\n\t\t\twriteWord(width);\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0x11); // HVY\n\t\t\twriteByte(0); // QTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HVU\n\t\t\twriteByte(1); // QTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HVV\n\t\t\twriteByte(1); // QTV\n\t\t}\n\t\n\t\tfunction writeDQT()\n\t\t{\n\t\t\twriteWord(0xFFDB); // marker\n\t\t\twriteWord(132);\t // length\n\t\t\twriteByte(0);\n\t\t\tfor (var i=0; i<64; i++) {\n\t\t\t\twriteByte(YTable[i]);\n\t\t\t}\n\t\t\twriteByte(1);\n\t\t\tfor (var j=0; j<64; j++) {\n\t\t\t\twriteByte(UVTable[j]);\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeDHT()\n\t\t{\n\t\t\twriteWord(0xFFC4); // marker\n\t\t\twriteWord(0x01A2); // length\n\t\n\t\t\twriteByte(0); // HTYDCinfo\n\t\t\tfor (var i=0; i<16; i++) {\n\t\t\t\twriteByte(std_dc_luminance_nrcodes[i+1]);\n\t\t\t}\n\t\t\tfor (var j=0; j<=11; j++) {\n\t\t\t\twriteByte(std_dc_luminance_values[j]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x10); // HTYACinfo\n\t\t\tfor (var k=0; k<16; k++) {\n\t\t\t\twriteByte(std_ac_luminance_nrcodes[k+1]);\n\t\t\t}\n\t\t\tfor (var l=0; l<=161; l++) {\n\t\t\t\twriteByte(std_ac_luminance_values[l]);\n\t\t\t}\n\t\n\t\t\twriteByte(1); // HTUDCinfo\n\t\t\tfor (var m=0; m<16; m++) {\n\t\t\t\twriteByte(std_dc_chrominance_nrcodes[m+1]);\n\t\t\t}\n\t\t\tfor (var n=0; n<=11; n++) {\n\t\t\t\twriteByte(std_dc_chrominance_values[n]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x11); // HTUACinfo\n\t\t\tfor (var o=0; o<16; o++) {\n\t\t\t\twriteByte(std_ac_chrominance_nrcodes[o+1]);\n\t\t\t}\n\t\t\tfor (var p=0; p<=161; p++) {\n\t\t\t\twriteByte(std_ac_chrominance_values[p]);\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction writeCOM(comments)\n\t\t{\n\t\t\tif (typeof comments === \"undefined\" || comments.constructor !== Array) return;\n\t\t\tcomments.forEach(e => {\n\t\t\t\tif (typeof e !== \"string\") return;\n\t\t\t\twriteWord(0xFFFE); // marker\n\t\t\t\tvar l = e.length;\n\t\t\t\twriteWord(l + 2); // length itself as well\n\t\t\t\tvar i;\n\t\t\t\tfor (i = 0; i < l; i++)\n\t\t\t\t\twriteByte(e.charCodeAt(i));\n\t\t\t});\n\t\t}\n\t\n\t\tfunction writeSOS()\n\t\t{\n\t\t\twriteWord(0xFFDA); // marker\n\t\t\twriteWord(12); // length\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0); // HTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HTV\n\t\t\twriteByte(0); // Ss\n\t\t\twriteByte(0x3f); // Se\n\t\t\twriteByte(0); // Bf\n\t\t}\n\t\t\n\t\tfunction processDU(CDU, fdtbl, DC, HTDC, HTAC){\n\t\t\tvar EOB = HTAC[0x00];\n\t\t\tvar M16zeroes = HTAC[0xF0];\n\t\t\tvar pos;\n\t\t\tvar I16 = 16;\n\t\t\tvar I63 = 63;\n\t\t\tvar I64 = 64;\n\t\t\tvar DU_DCT = fDCTQuant(CDU, fdtbl);\n\t\t\t//ZigZag reorder\n\t\t\tfor (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};\n\t\t\t//end0pos = first element in reverse order !=0\n\t\t\tif ( end0pos == 0) {\n\t\t\t\twriteBits(EOB);\n\t\t\t\treturn DC;\n\t\t\t}\n\t\t\tvar i = 1;\n\t\t\tvar lng;\n\t\t\twhile ( i <= end0pos ) {\n\t\t\t\tvar startpos = i;\n\t\t\t\tfor (; (DU[i]==0) && (i<=end0pos); ++i) {}\n\t\t\t\tvar nrzeroes = i-startpos;\n\t\t\t\tif ( nrzeroes >= I16 ) {\n\t\t\t\t\tlng = nrzeroes>>4;\n\t\t\t\t\tfor (var nrmarker=1; nrmarker <= lng; ++nrmarker)\n\t\t\t\t\t\twriteBits(M16zeroes);\n\t\t\t\t\tnrzeroes = nrzeroes&0xF;\n\t\t\t\t}\n\t\t\t\tpos = 32767+DU[i];\n\t\t\t\twriteBits(HTAC[(nrzeroes<<4)+category[pos]]);\n\t\t\t\twriteBits(bitcode[pos]);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif ( end0pos != I63 ) {\n\t\t\t\twriteBits(EOB);\n\t\t\t}\n\t\t\treturn DC;\n\t\t}\n\n\t\tfunction initCharLookupTable(){\n\t\t\tvar sfcc = String.fromCharCode;\n\t\t\tfor(var i=0; i < 256; i++){ ///// ACHTUNG // 255\n\t\t\t\tclt[i] = sfcc(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.encode = function(image,quality) // image data object\n\t\t{\n\t\t\tvar time_start = new Date().getTime();\n\t\t\t\n\t\t\tif(quality) setQuality(quality);\n\t\t\t\n\t\t\t// Initialize bit writer\n\t\t\tbyteout = new Array();\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\n\t\t\t// Add JPEG headers\n\t\t\twriteWord(0xFFD8); // SOI\n\t\t\twriteAPP0();\n\t\t\twriteCOM(image.comments);\n\t\t\twriteAPP1(image.exifBuffer);\n\t\t\twriteDQT();\n\t\t\twriteSOF0(image.width,image.height);\n\t\t\twriteDHT();\n\t\t\twriteSOS();\n\n\t\n\t\t\t// Encode 8x8 macroblocks\n\t\t\tvar DCY=0;\n\t\t\tvar DCU=0;\n\t\t\tvar DCV=0;\n\t\t\t\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\t\t\n\t\t\t\n\t\t\tthis.encode.displayName = \"_encode_\";\n\n\t\t\tvar imageData = image.data;\n\t\t\tvar width = image.width;\n\t\t\tvar height = image.height;\n\n\t\t\tvar quadWidth = width*4;\n\t\t\tvar tripleWidth = width*3;\n\t\t\t\n\t\t\tvar x, y = 0;\n\t\t\tvar r, g, b;\n\t\t\tvar start,p, col,row,pos;\n\t\t\twhile(y < height){\n\t\t\t\tx = 0;\n\t\t\t\twhile(x < quadWidth){\n\t\t\t\tstart = quadWidth * y + x;\n\t\t\t\tp = start;\n\t\t\t\tcol = -1;\n\t\t\t\trow = 0;\n\t\t\t\t\n\t\t\t\tfor(pos=0; pos < 64; pos++){\n\t\t\t\t\trow = pos >> 3;// /8\n\t\t\t\t\tcol = ( pos & 7 ) * 4; // %8\n\t\t\t\t\tp = start + ( row * quadWidth ) + col;\t\t\n\t\t\t\t\t\n\t\t\t\t\tif(y+row >= height){ // padding bottom\n\t\t\t\t\t\tp-= (quadWidth*(y+1+row-height));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(x+col >= quadWidth){ // padding right\t\n\t\t\t\t\t\tp-= ((x+col) - quadWidth +4)\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tr = imageData[ p++ ];\n\t\t\t\t\tg = imageData[ p++ ];\n\t\t\t\t\tb = imageData[ p++ ];\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t/* // calculate YUV values dynamically\n\t\t\t\t\tYDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80\n\t\t\t\t\tUDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));\n\t\t\t\t\tVDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));\n\t\t\t\t\t*/\n\t\t\t\t\t\n\t\t\t\t\t// use lookup table (slightly faster)\n\t\t\t\t\tYDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;\n\t\t\t\t\tUDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;\n\t\t\t\t\tVDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n\t\t\t\tDCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n\t\t\t\tDCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n\t\t\t\tx+=32;\n\t\t\t\t}\n\t\t\t\ty+=8;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t////////////////////////////////////////////////////////////////\n\t\n\t\t\t// Do the bit alignment of the EOI marker\n\t\t\tif ( bytepos >= 0 ) {\n\t\t\t\tvar fillbits = [];\n\t\t\t\tfillbits[1] = bytepos+1;\n\t\t\t\tfillbits[0] = (1<<(bytepos+1))-1;\n\t\t\t\twriteBits(fillbits);\n\t\t\t}\n\t\n\t\t\twriteWord(0xFFD9); //EOI\n\n\t\t\tif (typeof module === 'undefined') return new Uint8Array(byteout);\n return Buffer.from(byteout);\n\n\t\t\tvar jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));\n\t\t\t\n\t\t\tbyteout = [];\n\t\t\t\n\t\t\t// benchmarking\n\t\t\tvar duration = new Date().getTime() - time_start;\n \t\t//console.log('Encoding time: '+ duration + 'ms');\n \t\t//\n\t\t\t\n\t\t\treturn jpegDataUri\t\t\t\n\t}\n\t\n\tfunction setQuality(quality){\n\t\tif (quality <= 0) {\n\t\t\tquality = 1;\n\t\t}\n\t\tif (quality > 100) {\n\t\t\tquality = 100;\n\t\t}\n\t\t\n\t\tif(currentQuality == quality) return // don't recalc if unchanged\n\t\t\n\t\tvar sf = 0;\n\t\tif (quality < 50) {\n\t\t\tsf = Math.floor(5000 / quality);\n\t\t} else {\n\t\t\tsf = Math.floor(200 - quality*2);\n\t\t}\n\t\t\n\t\tinitQuantTables(sf);\n\t\tcurrentQuality = quality;\n\t\t//console.log('Quality set to: '+quality +'%');\n\t}\n\t\n\tfunction init(){\n\t\tvar time_start = new Date().getTime();\n\t\tif(!quality) quality = 50;\n\t\t// Create tables\n\t\tinitCharLookupTable()\n\t\tinitHuffmanTbl();\n\t\tinitCategoryNumber();\n\t\tinitRGBYUVTable();\n\t\t\n\t\tsetQuality(quality);\n\t\tvar duration = new Date().getTime() - time_start;\n \t//console.log('Initialization '+ duration + 'ms');\n\t}\n\t\n\tinit();\n\t\n};\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = encode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].encode = encode;\n}\n\nfunction encode(imgData, qu) {\n if (typeof qu === 'undefined') qu = 50;\n var encoder = new JPEGEncoder(qu);\n\tvar data = encoder.encode(imgData, qu);\n return {\n data: data,\n width: imgData.width,\n height: imgData.height,\n };\n}\n\n// helper function to get the imageData of an existing image on the current page.\nfunction getImageDataFromImage(idOrElement){\n\tvar theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;\n\tvar cvs = document.createElement('canvas');\n\tcvs.width = theImg.width;\n\tcvs.height = theImg.height;\n\tvar ctx = cvs.getContext(\"2d\");\n\tctx.drawImage(theImg,0,0);\n\t\n\treturn (ctx.getImageData(0, 0, cvs.width, cvs.height));\n}\n","/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\n/*\n Copyright 2011 notmasteryet\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// - The JPEG specification can be found in the ITU CCITT Recommendation T.81\n// (www.w3.org/Graphics/JPEG/itu-t81.pdf)\n// - The JFIF specification can be found in the JPEG File Interchange Format\n// (www.w3.org/Graphics/JPEG/jfif3.pdf)\n// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters\n// in PostScript Level 2, Technical Note #5116\n// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)\n\nvar JpegImage = (function jpegImage() {\n \"use strict\";\n var dctZigZag = new Int32Array([\n 0,\n 1, 8,\n 16, 9, 2,\n 3, 10, 17, 24,\n 32, 25, 18, 11, 4,\n 5, 12, 19, 26, 33, 40,\n 48, 41, 34, 27, 20, 13, 6,\n 7, 14, 21, 28, 35, 42, 49, 56,\n 57, 50, 43, 36, 29, 22, 15,\n 23, 30, 37, 44, 51, 58,\n 59, 52, 45, 38, 31,\n 39, 46, 53, 60,\n 61, 54, 47,\n 55, 62,\n 63\n ]);\n\n var dctCos1 = 4017 // cos(pi/16)\n var dctSin1 = 799 // sin(pi/16)\n var dctCos3 = 3406 // cos(3*pi/16)\n var dctSin3 = 2276 // sin(3*pi/16)\n var dctCos6 = 1567 // cos(6*pi/16)\n var dctSin6 = 3784 // sin(6*pi/16)\n var dctSqrt2 = 5793 // sqrt(2)\n var dctSqrt1d2 = 2896 // sqrt(2) / 2\n\n function constructor() {\n }\n\n function buildHuffmanTable(codeLengths, values) {\n var k = 0, code = [], i, j, length = 16;\n while (length > 0 && !codeLengths[length - 1])\n length--;\n code.push({children: [], index: 0});\n var p = code[0], q;\n for (i = 0; i < length; i++) {\n for (j = 0; j < codeLengths[i]; j++) {\n p = code.pop();\n p.children[p.index] = values[k];\n while (p.index > 0) {\n if (code.length === 0)\n throw new Error('Could not recreate Huffman Table');\n p = code.pop();\n }\n p.index++;\n code.push(p);\n while (code.length <= i) {\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n k++;\n }\n if (i + 1 < length) {\n // p here points to last code\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n }\n return code[0].children;\n }\n\n function decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successivePrev, successive, opts) {\n var precision = frame.precision;\n var samplesPerLine = frame.samplesPerLine;\n var scanLines = frame.scanLines;\n var mcusPerLine = frame.mcusPerLine;\n var progressive = frame.progressive;\n var maxH = frame.maxH, maxV = frame.maxV;\n\n var startOffset = offset, bitsData = 0, bitsCount = 0;\n function readBit() {\n if (bitsCount > 0) {\n bitsCount--;\n return (bitsData >> bitsCount) & 1;\n }\n bitsData = data[offset++];\n if (bitsData == 0xFF) {\n var nextByte = data[offset++];\n if (nextByte) {\n throw new Error(\"unexpected marker: \" + ((bitsData << 8) | nextByte).toString(16));\n }\n // unstuff 0\n }\n bitsCount = 7;\n return bitsData >>> 7;\n }\n function decodeHuffman(tree) {\n var node = tree, bit;\n while ((bit = readBit()) !== null) {\n node = node[bit];\n if (typeof node === 'number')\n return node;\n if (typeof node !== 'object')\n throw new Error(\"invalid huffman sequence\");\n }\n return null;\n }\n function receive(length) {\n var n = 0;\n while (length > 0) {\n var bit = readBit();\n if (bit === null) return;\n n = (n << 1) | bit;\n length--;\n }\n return n;\n }\n function receiveAndExtend(length) {\n var n = receive(length);\n if (n >= 1 << (length - 1))\n return n;\n return n + (-1 << length) + 1;\n }\n function decodeBaseline(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : receiveAndExtend(t);\n zz[0]= (component.pred += diff);\n var k = 1;\n while (k < 64) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15)\n break;\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s);\n k++;\n }\n }\n function decodeDCFirst(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);\n zz[0] = (component.pred += diff);\n }\n function decodeDCSuccessive(component, zz) {\n zz[0] |= readBit() << successive;\n }\n var eobrun = 0;\n function decodeACFirst(component, zz) {\n if (eobrun > 0) {\n eobrun--;\n return;\n }\n var k = spectralStart, e = spectralEnd;\n while (k <= e) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r) - 1;\n break;\n }\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s) * (1 << successive);\n k++;\n }\n }\n var successiveACState = 0, successiveACNextValue;\n function decodeACSuccessive(component, zz) {\n var k = spectralStart, e = spectralEnd, r = 0;\n while (k <= e) {\n var z = dctZigZag[k];\n var direction = zz[z] < 0 ? -1 : 1;\n switch (successiveACState) {\n case 0: // initial state\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r);\n successiveACState = 4;\n } else {\n r = 16;\n successiveACState = 1;\n }\n } else {\n if (s !== 1)\n throw new Error(\"invalid ACn encoding\");\n successiveACNextValue = receiveAndExtend(s);\n successiveACState = r ? 2 : 3;\n }\n continue;\n case 1: // skipping r zero items\n case 2:\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n r--;\n if (r === 0)\n successiveACState = successiveACState == 2 ? 3 : 0;\n }\n break;\n case 3: // set value for a zero item\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n zz[z] = successiveACNextValue << successive;\n successiveACState = 0;\n }\n break;\n case 4: // eob\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n break;\n }\n k++;\n }\n if (successiveACState === 4) {\n eobrun--;\n if (eobrun === 0)\n successiveACState = 0;\n }\n }\n function decodeMcu(component, decode, mcu, row, col) {\n var mcuRow = (mcu / mcusPerLine) | 0;\n var mcuCol = mcu % mcusPerLine;\n var blockRow = mcuRow * component.v + row;\n var blockCol = mcuCol * component.h + col;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n function decodeBlock(component, decode, mcu) {\n var blockRow = (mcu / component.blocksPerLine) | 0;\n var blockCol = mcu % component.blocksPerLine;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n\n var componentsLength = components.length;\n var component, i, j, k, n;\n var decodeFn;\n if (progressive) {\n if (spectralStart === 0)\n decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;\n else\n decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;\n } else {\n decodeFn = decodeBaseline;\n }\n\n var mcu = 0, marker;\n var mcuExpected;\n if (componentsLength == 1) {\n mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;\n } else {\n mcuExpected = mcusPerLine * frame.mcusPerColumn;\n }\n if (!resetInterval) resetInterval = mcuExpected;\n\n var h, v;\n while (mcu < mcuExpected) {\n // reset interval stuff\n for (i = 0; i < componentsLength; i++)\n components[i].pred = 0;\n eobrun = 0;\n\n if (componentsLength == 1) {\n component = components[0];\n for (n = 0; n < resetInterval; n++) {\n decodeBlock(component, decodeFn, mcu);\n mcu++;\n }\n } else {\n for (n = 0; n < resetInterval; n++) {\n for (i = 0; i < componentsLength; i++) {\n component = components[i];\n h = component.h;\n v = component.v;\n for (j = 0; j < v; j++) {\n for (k = 0; k < h; k++) {\n decodeMcu(component, decodeFn, mcu, j, k);\n }\n }\n }\n mcu++;\n\n // If we've reached our expected MCU's, stop decoding\n if (mcu === mcuExpected) break;\n }\n }\n\n if (mcu === mcuExpected) {\n // Skip trailing bytes at the end of the scan - until we reach the next marker\n do {\n if (data[offset] === 0xFF) {\n if (data[offset + 1] !== 0x00) {\n break;\n }\n }\n offset += 1;\n } while (offset < data.length - 2);\n }\n\n // find marker\n bitsCount = 0;\n marker = (data[offset] << 8) | data[offset + 1];\n if (marker < 0xFF00) {\n throw new Error(\"marker was not found\");\n }\n\n if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx\n offset += 2;\n }\n else\n break;\n }\n\n return offset - startOffset;\n }\n\n function buildComponentData(frame, component) {\n var lines = [];\n var blocksPerLine = component.blocksPerLine;\n var blocksPerColumn = component.blocksPerColumn;\n var samplesPerLine = blocksPerLine << 3;\n // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.\n var R = new Int32Array(64), r = new Uint8Array(64);\n\n // A port of poppler's IDCT method which in turn is taken from:\n // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,\n // \"Practical Fast 1-D DCT Algorithms with 11 Multiplications\",\n // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,\n // 988-991.\n function quantizeAndInverse(zz, dataOut, dataIn) {\n var qt = component.quantizationTable;\n var v0, v1, v2, v3, v4, v5, v6, v7, t;\n var p = dataIn;\n var i;\n\n // dequant\n for (i = 0; i < 64; i++)\n p[i] = zz[i] * qt[i];\n\n // inverse DCT on rows\n for (i = 0; i < 8; ++i) {\n var row = 8 * i;\n\n // check for all-zero AC coefficients\n if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&\n p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&\n p[7 + row] == 0) {\n t = (dctSqrt2 * p[0 + row] + 512) >> 10;\n p[0 + row] = t;\n p[1 + row] = t;\n p[2 + row] = t;\n p[3 + row] = t;\n p[4 + row] = t;\n p[5 + row] = t;\n p[6 + row] = t;\n p[7 + row] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;\n v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;\n v2 = p[2 + row];\n v3 = p[6 + row];\n v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;\n v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;\n v5 = p[3 + row] << 4;\n v6 = p[5 + row] << 4;\n\n // stage 3\n t = (v0 - v1+ 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0 + row] = v0 + v7;\n p[7 + row] = v0 - v7;\n p[1 + row] = v1 + v6;\n p[6 + row] = v1 - v6;\n p[2 + row] = v2 + v5;\n p[5 + row] = v2 - v5;\n p[3 + row] = v3 + v4;\n p[4 + row] = v3 - v4;\n }\n\n // inverse DCT on columns\n for (i = 0; i < 8; ++i) {\n var col = i;\n\n // check for all-zero AC coefficients\n if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&\n p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&\n p[7*8 + col] == 0) {\n t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;\n p[0*8 + col] = t;\n p[1*8 + col] = t;\n p[2*8 + col] = t;\n p[3*8 + col] = t;\n p[4*8 + col] = t;\n p[5*8 + col] = t;\n p[6*8 + col] = t;\n p[7*8 + col] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;\n v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;\n v2 = p[2*8 + col];\n v3 = p[6*8 + col];\n v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;\n v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;\n v5 = p[3*8 + col];\n v6 = p[5*8 + col];\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0*8 + col] = v0 + v7;\n p[7*8 + col] = v0 - v7;\n p[1*8 + col] = v1 + v6;\n p[6*8 + col] = v1 - v6;\n p[2*8 + col] = v2 + v5;\n p[5*8 + col] = v2 - v5;\n p[3*8 + col] = v3 + v4;\n p[4*8 + col] = v3 - v4;\n }\n\n // convert to 8-bit integers\n for (i = 0; i < 64; ++i) {\n var sample = 128 + ((p[i] + 8) >> 4);\n dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;\n }\n }\n\n requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);\n\n var i, j;\n for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {\n var scanLine = blockRow << 3;\n for (i = 0; i < 8; i++)\n lines.push(new Uint8Array(samplesPerLine));\n for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {\n quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);\n\n var offset = 0, sample = blockCol << 3;\n for (j = 0; j < 8; j++) {\n var line = lines[scanLine + j];\n for (i = 0; i < 8; i++)\n line[sample + i] = r[offset++];\n }\n }\n }\n return lines;\n }\n\n function clampTo8bit(a) {\n return a < 0 ? 0 : a > 255 ? 255 : a;\n }\n\n constructor.prototype = {\n load: function load(path) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", path, true);\n xhr.responseType = \"arraybuffer\";\n xhr.onload = (function() {\n // TODO catch parse error\n var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);\n this.parse(data);\n if (this.onload)\n this.onload();\n }).bind(this);\n xhr.send(null);\n },\n parse: function parse(data) {\n var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;\n var offset = 0, length = data.length;\n function readUint16() {\n var value = (data[offset] << 8) | data[offset + 1];\n offset += 2;\n return value;\n }\n function readDataBlock() {\n var length = readUint16();\n var array = data.subarray(offset, offset + length - 2);\n offset += array.length;\n return array;\n }\n function prepareComponents(frame) {\n // According to the JPEG standard, the sampling factor must be between 1 and 4\n // See https://github.com/libjpeg-turbo/libjpeg-turbo/blob/9abeff46d87bd201a952e276f3e4339556a403a3/libjpeg.txt#L1138-L1146\n var maxH = 1, maxV = 1;\n var component, componentId;\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n if (maxH < component.h) maxH = component.h;\n if (maxV < component.v) maxV = component.v;\n }\n }\n var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);\n var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);\n var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);\n var blocksPerLineForMcu = mcusPerLine * component.h;\n var blocksPerColumnForMcu = mcusPerColumn * component.v;\n var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;\n var blocks = [];\n\n // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)\n requestMemoryAllocation(blocksToAllocate * 256);\n\n for (var i = 0; i < blocksPerColumnForMcu; i++) {\n var row = [];\n for (var j = 0; j < blocksPerLineForMcu; j++)\n row.push(new Int32Array(64));\n blocks.push(row);\n }\n component.blocksPerLine = blocksPerLine;\n component.blocksPerColumn = blocksPerColumn;\n component.blocks = blocks;\n }\n }\n frame.maxH = maxH;\n frame.maxV = maxV;\n frame.mcusPerLine = mcusPerLine;\n frame.mcusPerColumn = mcusPerColumn;\n }\n var jfif = null;\n var adobe = null;\n var pixels = null;\n var frame, resetInterval;\n var quantizationTables = [], frames = [];\n var huffmanTablesAC = [], huffmanTablesDC = [];\n var fileMarker = readUint16();\n var malformedDataOffset = -1;\n this.comments = [];\n if (fileMarker != 0xFFD8) { // SOI (Start of Image)\n throw new Error(\"SOI not found\");\n }\n\n fileMarker = readUint16();\n while (fileMarker != 0xFFD9) { // EOI (End of image)\n var i, j, l;\n switch(fileMarker) {\n case 0xFF00: break;\n case 0xFFE0: // APP0 (Application Specific)\n case 0xFFE1: // APP1\n case 0xFFE2: // APP2\n case 0xFFE3: // APP3\n case 0xFFE4: // APP4\n case 0xFFE5: // APP5\n case 0xFFE6: // APP6\n case 0xFFE7: // APP7\n case 0xFFE8: // APP8\n case 0xFFE9: // APP9\n case 0xFFEA: // APP10\n case 0xFFEB: // APP11\n case 0xFFEC: // APP12\n case 0xFFED: // APP13\n case 0xFFEE: // APP14\n case 0xFFEF: // APP15\n case 0xFFFE: // COM (Comment)\n var appData = readDataBlock();\n\n if (fileMarker === 0xFFFE) {\n var comment = String.fromCharCode.apply(null, appData);\n this.comments.push(comment);\n }\n\n if (fileMarker === 0xFFE0) {\n if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&\n appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\\x00'\n jfif = {\n version: { major: appData[5], minor: appData[6] },\n densityUnits: appData[7],\n xDensity: (appData[8] << 8) | appData[9],\n yDensity: (appData[10] << 8) | appData[11],\n thumbWidth: appData[12],\n thumbHeight: appData[13],\n thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])\n };\n }\n }\n // TODO APP1 - Exif\n if (fileMarker === 0xFFE1) {\n if (appData[0] === 0x45 &&\n appData[1] === 0x78 &&\n appData[2] === 0x69 &&\n appData[3] === 0x66 &&\n appData[4] === 0) { // 'EXIF\\x00'\n this.exifBuffer = appData.subarray(5, appData.length);\n }\n }\n\n if (fileMarker === 0xFFEE) {\n if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&\n appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\\x00'\n adobe = {\n version: appData[6],\n flags0: (appData[7] << 8) | appData[8],\n flags1: (appData[9] << 8) | appData[10],\n transformCode: appData[11]\n };\n }\n }\n break;\n\n case 0xFFDB: // DQT (Define Quantization Tables)\n var quantizationTablesLength = readUint16();\n var quantizationTablesEnd = quantizationTablesLength + offset - 2;\n while (offset < quantizationTablesEnd) {\n var quantizationTableSpec = data[offset++];\n requestMemoryAllocation(64 * 4);\n var tableData = new Int32Array(64);\n if ((quantizationTableSpec >> 4) === 0) { // 8 bit values\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = data[offset++];\n }\n } else if ((quantizationTableSpec >> 4) === 1) { //16 bit\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = readUint16();\n }\n } else\n throw new Error(\"DQT: invalid table spec\");\n quantizationTables[quantizationTableSpec & 15] = tableData;\n }\n break;\n\n case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)\n case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)\n case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)\n readUint16(); // skip data length\n frame = {};\n frame.extended = (fileMarker === 0xFFC1);\n frame.progressive = (fileMarker === 0xFFC2);\n frame.precision = data[offset++];\n frame.scanLines = readUint16();\n frame.samplesPerLine = readUint16();\n frame.components = {};\n frame.componentsOrder = [];\n\n var pixelsInFrame = frame.scanLines * frame.samplesPerLine;\n if (pixelsInFrame > maxResolutionInPixels) {\n var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);\n throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);\n }\n\n var componentsCount = data[offset++], componentId;\n var maxH = 0, maxV = 0;\n for (i = 0; i < componentsCount; i++) {\n componentId = data[offset];\n var h = data[offset + 1] >> 4;\n var v = data[offset + 1] & 15;\n var qId = data[offset + 2];\n\n if ( h <= 0 || v <= 0 ) {\n throw new Error('Invalid sampling factor, expected values above 0');\n }\n\n frame.componentsOrder.push(componentId);\n frame.components[componentId] = {\n h: h,\n v: v,\n quantizationIdx: qId\n };\n offset += 3;\n }\n prepareComponents(frame);\n frames.push(frame);\n break;\n\n case 0xFFC4: // DHT (Define Huffman Tables)\n var huffmanLength = readUint16();\n for (i = 2; i < huffmanLength;) {\n var huffmanTableSpec = data[offset++];\n var codeLengths = new Uint8Array(16);\n var codeLengthSum = 0;\n for (j = 0; j < 16; j++, offset++) {\n codeLengthSum += (codeLengths[j] = data[offset]);\n }\n requestMemoryAllocation(16 + codeLengthSum);\n var huffmanValues = new Uint8Array(codeLengthSum);\n for (j = 0; j < codeLengthSum; j++, offset++)\n huffmanValues[j] = data[offset];\n i += 17 + codeLengthSum;\n\n ((huffmanTableSpec >> 4) === 0 ?\n huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =\n buildHuffmanTable(codeLengths, huffmanValues);\n }\n break;\n\n case 0xFFDD: // DRI (Define Restart Interval)\n readUint16(); // skip data length\n resetInterval = readUint16();\n break;\n\n case 0xFFDC: // Number of Lines marker\n readUint16() // skip data length\n readUint16() // Ignore this data since it represents the image height\n break;\n \n case 0xFFDA: // SOS (Start of Scan)\n var scanLength = readUint16();\n var selectorsCount = data[offset++];\n var components = [], component;\n for (i = 0; i < selectorsCount; i++) {\n component = frame.components[data[offset++]];\n var tableSpec = data[offset++];\n component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];\n component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];\n components.push(component);\n }\n var spectralStart = data[offset++];\n var spectralEnd = data[offset++];\n var successiveApproximation = data[offset++];\n var processed = decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successiveApproximation >> 4, successiveApproximation & 15, this.opts);\n offset += processed;\n break;\n\n case 0xFFFF: // Fill bytes\n if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.\n offset--;\n }\n break;\n default:\n if (data[offset - 3] == 0xFF &&\n data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {\n // could be incorrect encoding -- last 0xFF byte of the previous\n // block was eaten by the encoder\n offset -= 3;\n break;\n }\n else if (fileMarker === 0xE0 || fileMarker == 0xE1) {\n // Recover from malformed APP1 markers popular in some phone models.\n // See https://github.com/eugeneware/jpeg-js/issues/82\n if (malformedDataOffset !== -1) {\n throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);\n }\n malformedDataOffset = offset - 1;\n const nextOffset = readUint16();\n if (data[offset + nextOffset - 2] === 0xFF) {\n offset += nextOffset - 2;\n break;\n }\n }\n throw new Error(\"unknown JPEG marker \" + fileMarker.toString(16));\n }\n fileMarker = readUint16();\n }\n if (frames.length != 1)\n throw new Error(\"only single frame JPEGs supported\");\n\n // set each frame's components quantization table\n for (var i = 0; i < frames.length; i++) {\n var cp = frames[i].components;\n for (var j in cp) {\n cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];\n delete cp[j].quantizationIdx;\n }\n }\n\n this.width = frame.samplesPerLine;\n this.height = frame.scanLines;\n this.jfif = jfif;\n this.adobe = adobe;\n this.components = [];\n for (var i = 0; i < frame.componentsOrder.length; i++) {\n var component = frame.components[frame.componentsOrder[i]];\n this.components.push({\n lines: buildComponentData(frame, component),\n scaleX: component.h / frame.maxH,\n scaleY: component.v / frame.maxV\n });\n }\n },\n getData: function getData(width, height) {\n var scaleX = this.width / width, scaleY = this.height / height;\n\n var component1, component2, component3, component4;\n var component1Line, component2Line, component3Line, component4Line;\n var x, y;\n var offset = 0;\n var Y, Cb, Cr, K, C, M, Ye, R, G, B;\n var colorTransform;\n var dataLength = width * height * this.components.length;\n requestMemoryAllocation(dataLength);\n var data = new Uint8Array(dataLength);\n switch (this.components.length) {\n case 1:\n component1 = this.components[0];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n\n data[offset++] = Y;\n }\n }\n break;\n case 2:\n // PDF might compress two component data in custom colorspace\n component1 = this.components[0];\n component2 = this.components[1];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n data[offset++] = Y;\n Y = component2Line[0 | (x * component2.scaleX * scaleX)];\n data[offset++] = Y;\n }\n }\n break;\n case 3:\n // The default transform for three components is true\n colorTransform = true;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n R = component1Line[0 | (x * component1.scaleX * scaleX)];\n G = component2Line[0 | (x * component2.scaleX * scaleX)];\n B = component3Line[0 | (x * component3.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n\n R = clampTo8bit(Y + 1.402 * (Cr - 128));\n G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n B = clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n\n data[offset++] = R;\n data[offset++] = G;\n data[offset++] = B;\n }\n }\n break;\n case 4:\n if (!this.adobe)\n throw new Error('Unsupported color mode (4 components)');\n // The default transform for four components is false\n colorTransform = false;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n component4 = this.components[3];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n C = component1Line[0 | (x * component1.scaleX * scaleX)];\n M = component2Line[0 | (x * component2.scaleX * scaleX)];\n Ye = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n\n C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));\n M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n data[offset++] = 255-C;\n data[offset++] = 255-M;\n data[offset++] = 255-Ye;\n data[offset++] = 255-K;\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n return data;\n },\n copyToImageData: function copyToImageData(imageData, formatAsRGBA) {\n var width = imageData.width, height = imageData.height;\n var imageDataArray = imageData.data;\n var data = this.getData(width, height);\n var i = 0, j = 0, x, y;\n var Y, K, C, M, R, G, B;\n switch (this.components.length) {\n case 1:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n Y = data[i++];\n\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 3:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n R = data[i++];\n G = data[i++];\n B = data[i++];\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 4:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n C = data[i++];\n M = data[i++];\n Y = data[i++];\n K = data[i++];\n\n R = 255 - clampTo8bit(C * (1 - K / 255) + K);\n G = 255 - clampTo8bit(M * (1 - K / 255) + K);\n B = 255 - clampTo8bit(Y * (1 - K / 255) + K);\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n }\n };\n\n\n // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.\n var totalBytesAllocated = 0;\n var maxMemoryUsageBytes = 0;\n function requestMemoryAllocation(increaseAmount = 0) {\n var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;\n if (totalMemoryImpactBytes > maxMemoryUsageBytes) {\n var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);\n throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);\n }\n\n totalBytesAllocated = totalMemoryImpactBytes;\n }\n\n constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {\n totalBytesAllocated = 0;\n maxMemoryUsageBytes = maxMemoryUsageBytes_;\n };\n\n constructor.getBytesAllocated = function () {\n return totalBytesAllocated;\n };\n\n constructor.requestMemoryAllocation = requestMemoryAllocation;\n\n return constructor;\n})();\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = decode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].decode = decode;\n}\n\nfunction decode(jpegData, userOpts = {}) {\n var defaultOpts = {\n // \"undefined\" means \"Choose whether to transform colors based on the image’s color model.\"\n colorTransform: undefined,\n useTArray: false,\n formatAsRGBA: true,\n tolerantDecoding: true,\n maxResolutionInMP: 100, // Don't decode more than 100 megapixels\n maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB\n };\n\n var opts = {...defaultOpts, ...userOpts};\n var arr = new Uint8Array(jpegData);\n var decoder = new JpegImage();\n decoder.opts = opts;\n // If this constructor ever supports async decoding this will need to be done differently.\n // Until then, treating as singleton limit is fine.\n JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);\n decoder.parse(arr);\n\n var channels = (opts.formatAsRGBA) ? 4 : 3;\n var bytesNeeded = decoder.width * decoder.height * channels;\n try {\n JpegImage.requestMemoryAllocation(bytesNeeded);\n var image = {\n width: decoder.width,\n height: decoder.height,\n exifBuffer: decoder.exifBuffer,\n data: opts.useTArray ?\n new Uint8Array(bytesNeeded) :\n Buffer.alloc(bytesNeeded)\n };\n if(decoder.comments.length > 0) {\n image[\"comments\"] = decoder.comments;\n }\n } catch (err) {\n if (err instanceof RangeError) {\n throw new Error(\"Could not allocate enough memory for the image. \" +\n \"Required: \" + bytesNeeded);\n } \n \n if (err instanceof ReferenceError) {\n if (err.message === \"Buffer is not defined\") {\n throw new Error(\"Buffer is not globally defined in this environment. \" +\n \"Consider setting useTArray to true\");\n }\n }\n throw err;\n }\n\n decoder.copyToImageData(image, opts.formatAsRGBA);\n\n return image;\n}\n","var encode = require('./lib/encoder'),\n decode = require('./lib/decoder');\n\nmodule.exports = {\n encode: encode,\n decode: decode\n};\n","\"use strict\";\n/*\n * Copyright 2017 Sam Thorogood. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n * use this file except in compliance with the License. You may obtain a copy of\n * the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n * License for the specific language governing permissions and limitations under\n * the License.\n */\n(function (scope) {\n 'use strict';\n // fail early\n if (scope['TextEncoder'] && scope['TextDecoder']) {\n return false;\n }\n /**\n * @constructor\n * @param {string=} utfLabel\n */\n function FastTextEncoder(utfLabel = 'utf-8') {\n if (utfLabel !== 'utf-8') {\n throw new RangeError(`Failed to construct 'TextEncoder': The encoding label provided ('${utfLabel}') is invalid.`);\n }\n }\n Object.defineProperty(FastTextEncoder.prototype, 'encoding', {\n value: 'utf-8',\n });\n /**\n * @param {string} string\n * @param {{stream: boolean}=} options\n * @return {!Uint8Array}\n */\n FastTextEncoder.prototype.encode = function (string, options = { stream: false }) {\n if (options.stream) {\n throw new Error(`Failed to encode: the 'stream' option is unsupported.`);\n }\n let pos = 0;\n const len = string.length;\n const out = [];\n let at = 0; // output position\n let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size\n let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset\n while (pos < len) {\n let value = string.charCodeAt(pos++);\n if (value >= 0xd800 && value <= 0xdbff) {\n // high surrogate\n if (pos < len) {\n const extra = string.charCodeAt(pos);\n if ((extra & 0xfc00) === 0xdc00) {\n ++pos;\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\n }\n }\n if (value >= 0xd800 && value <= 0xdbff) {\n continue; // drop lone surrogate\n }\n }\n // expand the buffer if we couldn't write 4 bytes\n if (at + 4 > target.length) {\n tlen += 8; // minimum extra\n tlen *= 1.0 + (pos / string.length) * 2; // take 2x the remaining\n tlen = (tlen >> 3) << 3; // 8 byte offset\n const update = new Uint8Array(tlen);\n update.set(target);\n target = update;\n }\n if ((value & 0xffffff80) === 0) {\n // 1-byte\n target[at++] = value; // ASCII\n continue;\n }\n else if ((value & 0xfffff800) === 0) {\n // 2-byte\n target[at++] = ((value >> 6) & 0x1f) | 0xc0;\n }\n else if ((value & 0xffff0000) === 0) {\n // 3-byte\n target[at++] = ((value >> 12) & 0x0f) | 0xe0;\n target[at++] = ((value >> 6) & 0x3f) | 0x80;\n }\n else if ((value & 0xffe00000) === 0) {\n // 4-byte\n target[at++] = ((value >> 18) & 0x07) | 0xf0;\n target[at++] = ((value >> 12) & 0x3f) | 0x80;\n target[at++] = ((value >> 6) & 0x3f) | 0x80;\n }\n else {\n // FIXME: do we care\n continue;\n }\n target[at++] = (value & 0x3f) | 0x80;\n }\n return target.slice(0, at);\n };\n /**\n * @constructor\n * @param {string=} utfLabel\n * @param {{fatal: boolean}=} options\n */\n function FastTextDecoder(utfLabel = 'utf-8', options = { fatal: false }) {\n if (utfLabel !== 'utf-8') {\n throw new RangeError(`Failed to construct 'TextDecoder': The encoding label provided ('${utfLabel}') is invalid.`);\n }\n if (options.fatal) {\n throw new Error(`Failed to construct 'TextDecoder': the 'fatal' option is unsupported.`);\n }\n }\n Object.defineProperty(FastTextDecoder.prototype, 'encoding', {\n value: 'utf-8',\n });\n Object.defineProperty(FastTextDecoder.prototype, 'fatal', { value: false });\n Object.defineProperty(FastTextDecoder.prototype, 'ignoreBOM', {\n value: false,\n });\n /**\n * @param {(!ArrayBuffer|!ArrayBufferView)} buffer\n * @param {{stream: boolean}=} options\n */\n FastTextDecoder.prototype.decode = function (buffer, options = { stream: false }) {\n if (options['stream']) {\n throw new Error(`Failed to decode: the 'stream' option is unsupported.`);\n }\n const bytes = new Uint8Array(buffer);\n let pos = 0;\n const len = bytes.length;\n const out = [];\n while (pos < len) {\n const byte1 = bytes[pos++];\n if (byte1 === 0) {\n break; // NULL\n }\n if ((byte1 & 0x80) === 0) {\n // 1-byte\n out.push(byte1);\n }\n else if ((byte1 & 0xe0) === 0xc0) {\n // 2-byte\n const byte2 = bytes[pos++] & 0x3f;\n out.push(((byte1 & 0x1f) << 6) | byte2);\n }\n else if ((byte1 & 0xf0) === 0xe0) {\n const byte2 = bytes[pos++] & 0x3f;\n const byte3 = bytes[pos++] & 0x3f;\n out.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\n }\n else if ((byte1 & 0xf8) === 0xf0) {\n const byte2 = bytes[pos++] & 0x3f;\n const byte3 = bytes[pos++] & 0x3f;\n const byte4 = bytes[pos++] & 0x3f;\n // this can be > 0xffff, so possibly generate surrogates\n let codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\n if (codepoint > 0xffff) {\n // codepoint &= ~0x10000;\n codepoint -= 0x10000;\n out.push(((codepoint >>> 10) & 0x3ff) | 0xd800);\n codepoint = 0xdc00 | (codepoint & 0x3ff);\n }\n out.push(codepoint);\n }\n else {\n // FIXME: we're ignoring this\n }\n }\n return String.fromCharCode.apply(null, out);\n };\n scope['TextEncoder'] = FastTextEncoder;\n scope['TextDecoder'] = FastTextDecoder;\n})(typeof window !== 'undefined'\n ? window\n : typeof self !== 'undefined'\n ? self\n : this);\n//# sourceMappingURL=text-encoding-polyfill.js.map","// eslint-disable-next-line import/no-unassigned-import\nimport './text-encoding-polyfill';\nexport function decode(bytes, encoding = 'utf8') {\n const decoder = new TextDecoder(encoding);\n return decoder.decode(bytes);\n}\nconst encoder = new TextEncoder();\nexport function encode(str) {\n return encoder.encode(str);\n}\n//# sourceMappingURL=text.browser.js.map","import { decode, encode } from './text';\nconst defaultByteLength = 1024 * 8;\nconst hostBigEndian = (() => {\n const array = new Uint8Array(4);\n const view = new Uint32Array(array.buffer);\n return !((view[0] = 1) & array[0]);\n})();\nconst typedArrays = {\n int8: globalThis.Int8Array,\n uint8: globalThis.Uint8Array,\n int16: globalThis.Int16Array,\n uint16: globalThis.Uint16Array,\n int32: globalThis.Int32Array,\n uint32: globalThis.Uint32Array,\n uint64: globalThis.BigUint64Array,\n int64: globalThis.BigInt64Array,\n float32: globalThis.Float32Array,\n float64: globalThis.Float64Array,\n};\nexport class IOBuffer {\n /**\n * @param data - The data to construct the IOBuffer with.\n * If data is a number, it will be the new buffer's length
\n * If data is `undefined`, the buffer will be initialized with a default length of 8Kb
\n * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,\n * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.\n * @param options\n */\n constructor(data = defaultByteLength, options = {}) {\n let dataIsGiven = false;\n if (typeof data === 'number') {\n data = new ArrayBuffer(data);\n }\n else {\n dataIsGiven = true;\n this.lastWrittenByte = data.byteLength;\n }\n const offset = options.offset ? options.offset >>> 0 : 0;\n const byteLength = data.byteLength - offset;\n let dvOffset = offset;\n if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {\n if (data.byteLength !== data.buffer.byteLength) {\n dvOffset = data.byteOffset + offset;\n }\n data = data.buffer;\n }\n if (dataIsGiven) {\n this.lastWrittenByte = byteLength;\n }\n else {\n this.lastWrittenByte = 0;\n }\n this.buffer = data;\n this.length = byteLength;\n this.byteLength = byteLength;\n this.byteOffset = dvOffset;\n this.offset = 0;\n this.littleEndian = true;\n this._data = new DataView(this.buffer, dvOffset, byteLength);\n this._mark = 0;\n this._marks = [];\n }\n /**\n * Checks if the memory allocated to the buffer is sufficient to store more\n * bytes after the offset.\n * @param byteLength - The needed memory in bytes.\n * @returns `true` if there is sufficient space and `false` otherwise.\n */\n available(byteLength = 1) {\n return this.offset + byteLength <= this.length;\n }\n /**\n * Check if little-endian mode is used for reading and writing multi-byte\n * values.\n * @returns `true` if little-endian mode is used, `false` otherwise.\n */\n isLittleEndian() {\n return this.littleEndian;\n }\n /**\n * Set little-endian mode for reading and writing multi-byte values.\n */\n setLittleEndian() {\n this.littleEndian = true;\n return this;\n }\n /**\n * Check if big-endian mode is used for reading and writing multi-byte values.\n * @returns `true` if big-endian mode is used, `false` otherwise.\n */\n isBigEndian() {\n return !this.littleEndian;\n }\n /**\n * Switches to big-endian mode for reading and writing multi-byte values.\n */\n setBigEndian() {\n this.littleEndian = false;\n return this;\n }\n /**\n * Move the pointer n bytes forward.\n * @param n - Number of bytes to skip.\n */\n skip(n = 1) {\n this.offset += n;\n return this;\n }\n /**\n * Move the pointer n bytes backward.\n * @param n - Number of bytes to move back.\n */\n back(n = 1) {\n this.offset -= n;\n return this;\n }\n /**\n * Move the pointer to the given offset.\n * @param offset\n */\n seek(offset) {\n this.offset = offset;\n return this;\n }\n /**\n * Store the current pointer offset.\n * @see {@link IOBuffer#reset}\n */\n mark() {\n this._mark = this.offset;\n return this;\n }\n /**\n * Move the pointer back to the last pointer offset set by mark.\n * @see {@link IOBuffer#mark}\n */\n reset() {\n this.offset = this._mark;\n return this;\n }\n /**\n * Push the current pointer offset to the mark stack.\n * @see {@link IOBuffer#popMark}\n */\n pushMark() {\n this._marks.push(this.offset);\n return this;\n }\n /**\n * Pop the last pointer offset from the mark stack, and set the current\n * pointer offset to the popped value.\n * @see {@link IOBuffer#pushMark}\n */\n popMark() {\n const offset = this._marks.pop();\n if (offset === undefined) {\n throw new Error('Mark stack empty');\n }\n this.seek(offset);\n return this;\n }\n /**\n * Move the pointer offset back to 0.\n */\n rewind() {\n this.offset = 0;\n return this;\n }\n /**\n * Make sure the buffer has sufficient memory to write a given byteLength at\n * the current pointer offset.\n * If the buffer's memory is insufficient, this method will create a new\n * buffer (a copy) with a length that is twice (byteLength + current offset).\n * @param byteLength\n */\n ensureAvailable(byteLength = 1) {\n if (!this.available(byteLength)) {\n const lengthNeeded = this.offset + byteLength;\n const newLength = lengthNeeded * 2;\n const newArray = new Uint8Array(newLength);\n newArray.set(new Uint8Array(this.buffer));\n this.buffer = newArray.buffer;\n this.length = this.byteLength = newLength;\n this._data = new DataView(this.buffer);\n }\n return this;\n }\n /**\n * Read a byte and return false if the byte's value is 0, or true otherwise.\n * Moves pointer forward by one byte.\n */\n readBoolean() {\n return this.readUint8() !== 0;\n }\n /**\n * Read a signed 8-bit integer and move pointer forward by 1 byte.\n */\n readInt8() {\n return this._data.getInt8(this.offset++);\n }\n /**\n * Read an unsigned 8-bit integer and move pointer forward by 1 byte.\n */\n readUint8() {\n return this._data.getUint8(this.offset++);\n }\n /**\n * Alias for {@link IOBuffer#readUint8}.\n */\n readByte() {\n return this.readUint8();\n }\n /**\n * Read `n` bytes and move pointer forward by `n` bytes.\n */\n readBytes(n = 1) {\n return this.readArray(n, 'uint8');\n }\n /**\n * Creates an array of corresponding to the type `type` and size `size`.\n * For example type `uint8` will create a `Uint8Array`.\n * @param size - size of the resulting array\n * @param type - number type of elements to read\n */\n readArray(size, type) {\n const bytes = typedArrays[type].BYTES_PER_ELEMENT * size;\n const offset = this.byteOffset + this.offset;\n const slice = this.buffer.slice(offset, offset + bytes);\n if (this.littleEndian === hostBigEndian &&\n type !== 'uint8' &&\n type !== 'int8') {\n const slice = new Uint8Array(this.buffer.slice(offset, offset + bytes));\n slice.reverse();\n const returnArray = new typedArrays[type](slice.buffer);\n this.offset += bytes;\n returnArray.reverse();\n return returnArray;\n }\n const returnArray = new typedArrays[type](slice);\n this.offset += bytes;\n return returnArray;\n }\n /**\n * Read a 16-bit signed integer and move pointer forward by 2 bytes.\n */\n readInt16() {\n const value = this._data.getInt16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.\n */\n readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 32-bit signed integer and move pointer forward by 4 bytes.\n */\n readInt32() {\n const value = this._data.getInt32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.\n */\n readUint32() {\n const value = this._data.getUint32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit floating number and move pointer forward by 4 bytes.\n */\n readFloat32() {\n const value = this._data.getFloat32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 64-bit floating number and move pointer forward by 8 bytes.\n */\n readFloat64() {\n const value = this._data.getFloat64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n /**\n * Read a 64-bit signed integer number and move pointer forward by 8 bytes.\n */\n readBigInt64() {\n const value = this._data.getBigInt64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n /**\n * Read a 64-bit unsigned integer number and move pointer forward by 8 bytes.\n */\n readBigUint64() {\n const value = this._data.getBigUint64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n /**\n * Read a 1-byte ASCII character and move pointer forward by 1 byte.\n */\n readChar() {\n return String.fromCharCode(this.readInt8());\n }\n /**\n * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.\n */\n readChars(n = 1) {\n let result = '';\n for (let i = 0; i < n; i++) {\n result += this.readChar();\n }\n return result;\n }\n /**\n * Read the next `n` bytes, return a UTF-8 decoded string and move pointer\n * forward by `n` bytes.\n */\n readUtf8(n = 1) {\n return decode(this.readBytes(n));\n }\n /**\n * Read the next `n` bytes, return a string decoded with `encoding` and move pointer\n * forward by `n` bytes.\n * If no encoding is passed, the function is equivalent to @see {@link IOBuffer#readUtf8}\n */\n decodeText(n = 1, encoding = 'utf-8') {\n return decode(this.readBytes(n), encoding);\n }\n /**\n * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer\n * forward by 1 byte.\n */\n writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }\n /**\n * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.\n */\n writeInt8(value) {\n this.ensureAvailable(1);\n this._data.setInt8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as an 8-bit unsigned integer and move pointer forward by 1\n * byte.\n */\n writeUint8(value) {\n this.ensureAvailable(1);\n this._data.setUint8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * An alias for {@link IOBuffer#writeUint8}.\n */\n writeByte(value) {\n return this.writeUint8(value);\n }\n /**\n * Write all elements of `bytes` as uint8 values and move pointer forward by\n * `bytes.length` bytes.\n */\n writeBytes(bytes) {\n this.ensureAvailable(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n this._data.setUint8(this.offset++, bytes[i]);\n }\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit signed integer and move pointer forward by 2\n * bytes.\n */\n writeInt16(value) {\n this.ensureAvailable(2);\n this._data.setInt16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit unsigned integer and move pointer forward by 2\n * bytes.\n */\n writeUint16(value) {\n this.ensureAvailable(2);\n this._data.setUint16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit signed integer and move pointer forward by 4\n * bytes.\n */\n writeInt32(value) {\n this.ensureAvailable(4);\n this._data.setInt32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit unsigned integer and move pointer forward by 4\n * bytes.\n */\n writeUint32(value) {\n this.ensureAvailable(4);\n this._data.setUint32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit floating number and move pointer forward by 4\n * bytes.\n */\n writeFloat32(value) {\n this.ensureAvailable(4);\n this._data.setFloat32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 64-bit floating number and move pointer forward by 8\n * bytes.\n */\n writeFloat64(value) {\n this.ensureAvailable(8);\n this._data.setFloat64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 64-bit signed bigint and move pointer forward by 8\n * bytes.\n */\n writeBigInt64(value) {\n this.ensureAvailable(8);\n this._data.setBigInt64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 64-bit unsigned bigint and move pointer forward by 8\n * bytes.\n */\n writeBigUint64(value) {\n this.ensureAvailable(8);\n this._data.setBigUint64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write the charCode of `str`'s first character as an 8-bit unsigned integer\n * and move pointer forward by 1 byte.\n */\n writeChar(str) {\n return this.writeUint8(str.charCodeAt(0));\n }\n /**\n * Write the charCodes of all `str`'s characters as 8-bit unsigned integers\n * and move pointer forward by `str.length` bytes.\n */\n writeChars(str) {\n for (let i = 0; i < str.length; i++) {\n this.writeUint8(str.charCodeAt(i));\n }\n return this;\n }\n /**\n * UTF-8 encode and write `str` to the current pointer offset and move pointer\n * forward according to the encoded length.\n */\n writeUtf8(str) {\n return this.writeBytes(encode(str));\n }\n /**\n * Export a Uint8Array view of the internal buffer.\n * The view starts at the byte offset and its length\n * is calculated to stop at the last written byte or the original length.\n */\n toArray() {\n return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);\n }\n /**\n * Update the last written byte offset\n * @private\n */\n _updateLastWrittenByte() {\n if (this.offset > this.lastWrittenByte) {\n this.lastWrittenByte = this.offset;\n }\n }\n}\n//# sourceMappingURL=IOBuffer.js.map","\n/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED$1 = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN$1 = 2;\n\n/*============================================================================*/\n\n\nfunction zero$1(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES$1 = 30;\n/* number of distance codes */\n\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\n\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES$1 + 2) * 2);\nzero$1(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES$1 * 2);\nzero$1(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero$1(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1);\nzero$1(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES$1);\nzero$1(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES$1);\nzero$1(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Tracev((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Tracev((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) => {\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n\n const next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS$1; bits++) {\n code = (code + bl_count[bits - 1]) << 1;\n next_code[bits] = code;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES$1 - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES$1; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS$1; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES$1 + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES$1; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES$1; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES$1; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES$1; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.sym_next = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) => {\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let sx = 0; /* running index in sym_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.sym_next !== 0) {\n do {\n dist = s.pending_buf[s.sym_buf + sx++] & 0xff;\n dist += (s.pending_buf[s.sym_buf + sx++] & 0xff) << 8;\n lc = s.pending_buf[s.sym_buf + sx++];\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and sym_buf is ok: */\n //Assert(s->pending < s->lit_bufsize + sx, \"pendingBuf overflow\");\n\n } while (sx < s.sym_next);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) => {\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE$1;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) => {\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) => {\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"block list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"allow list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* block_mask is the bit mask of block-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let block_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"block-listed\") bytes. */\n for (n = 0; n <= 31; n++, block_mask >>>= 1) {\n if ((block_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"allow-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS$1; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"block-listed\" or \"allow-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init$1 = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n bi_windup(s); /* align on byte boundary */\n put_short(s, stored_len);\n put_short(s, ~stored_len);\n if (stored_len) {\n s.pending_buf.set(s.window.subarray(buf, buf + stored_len), s.pending);\n }\n s.pending += stored_len;\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align$1 = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and write out the encoded block.\n */\nconst _tr_flush_block$1 = (s, buf, stored_len, last) => {\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN$1) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->sym_next / 3));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block$1(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED$1 || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally$1 = (s, dist, lc) => {\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n\n s.pending_buf[s.sym_buf + s.sym_next++] = dist;\n s.pending_buf[s.sym_buf + s.sym_next++] = dist >> 8;\n s.pending_buf[s.sym_buf + s.sym_next++] = lc;\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n return (s.sym_next === s.sym_end);\n};\n\nvar _tr_init_1 = _tr_init$1;\nvar _tr_stored_block_1 = _tr_stored_block$1;\nvar _tr_flush_block_1 = _tr_flush_block$1;\nvar _tr_tally_1 = _tr_tally$1;\nvar _tr_align_1 = _tr_align$1;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let c, table = [];\n\n for (var n = 0; n < 256; n++) {\n c = n;\n for (var k = 0; k < 8; k++) {\n c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n};\n\n// Create table on load. Just 255 signed longs. Not a problem.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants$2 = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init, _tr_stored_block, _tr_flush_block, _tr_tally, _tr_align } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_PARTIAL_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$3, Z_BLOCK: Z_BLOCK$1,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_UNKNOWN,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants$2;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES = 30;\n/* number of distance codes */\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42; /* zlib header -> BUSY_STATE */\n//#ifdef GZIP\nconst GZIP_STATE = 57; /* gzip header -> BUSY_STATE | EXTRA_STATE */\n//#endif\nconst EXTRA_STATE = 69; /* gzip extra block -> NAME_STATE */\nconst NAME_STATE = 73; /* gzip file name -> COMMENT_STATE */\nconst COMMENT_STATE = 91; /* gzip comment -> HCRC_STATE */\nconst HCRC_STATE = 103; /* gzip header CRC -> BUSY_STATE */\nconst BUSY_STATE = 113; /* deflate -> FINISH_STATE */\nconst FINISH_STATE = 666; /* stream complete */\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) * 2) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n/* ===========================================================================\n * Slide the hash table when sliding the window down (could be avoided with 32\n * bit values at the expense of memory usage). We slide even when level == 0 to\n * keep the hash table consistent if we switch back to level > 0 later.\n */\nconst slide_hash = (s) => {\n let n, m;\n let p;\n let wsize = s.w_size;\n\n n = s.hash_size;\n p = n;\n do {\n m = s.head[--p];\n s.head[p] = (m >= wsize ? m - wsize : 0);\n } while (--n);\n n = wsize;\n//#ifndef FASTEST\n p = n;\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= wsize ? m - wsize : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n//#endif\n};\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output, except for\n * some deflate_stored() output, goes through this function so some\n * applications may wish to modify it to avoid allocating a large\n * strm->next_out buffer and copying into it. (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let n, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size - more), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n slide_hash(s);\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n *\n * In case deflateParams() is used to later switch to a non-zero compression\n * level, s->matches (otherwise unused when storing) keeps track of the number\n * of hash table slides to perform. If s->matches is 1, then one hash table\n * slide will be done when switching. If s->matches is 2, the maximum value\n * allowed here, then the hash table will be cleared, since two or more slides\n * is the same as a clear.\n *\n * deflate_stored() is written to minimize the number of times an input byte is\n * copied. It is most efficient with large input and output buffers, which\n * maximizes the opportunites to have a single copy from next_in to next_out.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Smallest worthy block size when not flushing or finishing. By default\n * this is 32K. This can be as small as 507 bytes for memLevel == 1. For\n * large input and output buffers, the stored block size will be larger.\n */\n let min_block = s.pending_buf_size - 5 > s.w_size ? s.w_size : s.pending_buf_size - 5;\n\n /* Copy as many min_block or larger stored blocks directly to next_out as\n * possible. If flushing, copy the remaining available input to next_out as\n * stored blocks, if there is enough space.\n */\n let len, left, have, last = 0;\n let used = s.strm.avail_in;\n do {\n /* Set len to the maximum size block that we can copy directly with the\n * available input data and output space. Set left to how much of that\n * would be copied from what's left in the window.\n */\n len = 65535/* MAX_STORED */; /* maximum deflate stored block length */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n if (s.strm.avail_out < have) { /* need room for header */\n break;\n }\n /* maximum stored block length that will fit in avail_out: */\n have = s.strm.avail_out - have;\n left = s.strstart - s.block_start; /* bytes left in window */\n if (len > left + s.strm.avail_in) {\n len = left + s.strm.avail_in; /* limit len to the input */\n }\n if (len > have) {\n len = have; /* limit len to the output */\n }\n\n /* If the stored block would be less than min_block in length, or if\n * unable to copy all of the available input when flushing, then try\n * copying to the window and the pending buffer instead. Also don't\n * write an empty block when flushing -- deflate() does that.\n */\n if (len < min_block && ((len === 0 && flush !== Z_FINISH$3) ||\n flush === Z_NO_FLUSH$2 ||\n len !== left + s.strm.avail_in)) {\n break;\n }\n\n /* Make a dummy stored block in pending to get the header bytes,\n * including any pending bits. This also updates the debugging counts.\n */\n last = flush === Z_FINISH$3 && len === left + s.strm.avail_in ? 1 : 0;\n _tr_stored_block(s, 0, 0, last);\n\n /* Replace the lengths in the dummy stored block with len. */\n s.pending_buf[s.pending - 4] = len;\n s.pending_buf[s.pending - 3] = len >> 8;\n s.pending_buf[s.pending - 2] = ~len;\n s.pending_buf[s.pending - 1] = ~len >> 8;\n\n /* Write the stored block header bytes. */\n flush_pending(s.strm);\n\n//#ifdef ZLIB_DEBUG\n// /* Update debugging counts for the data about to be copied. */\n// s->compressed_len += len << 3;\n// s->bits_sent += len << 3;\n//#endif\n\n /* Copy uncompressed bytes from the window to next_out. */\n if (left) {\n if (left > len) {\n left = len;\n }\n //zmemcpy(s->strm->next_out, s->window + s->block_start, left);\n s.strm.output.set(s.window.subarray(s.block_start, s.block_start + left), s.strm.next_out);\n s.strm.next_out += left;\n s.strm.avail_out -= left;\n s.strm.total_out += left;\n s.block_start += left;\n len -= left;\n }\n\n /* Copy uncompressed bytes directly from next_in to next_out, updating\n * the check value.\n */\n if (len) {\n read_buf(s.strm, s.strm.output, s.strm.next_out, len);\n s.strm.next_out += len;\n s.strm.avail_out -= len;\n s.strm.total_out += len;\n }\n } while (last === 0);\n\n /* Update the sliding window with the last s->w_size bytes of the copied\n * data, or append all of the copied data to the existing window if less\n * than s->w_size bytes were copied. Also update the number of bytes to\n * insert in the hash tables, in the event that deflateParams() switches to\n * a non-zero compression level.\n */\n used -= s.strm.avail_in; /* number of input bytes directly copied */\n if (used) {\n /* If any input was used, then no unused input remains in the window,\n * therefore s->block_start == s->strstart.\n */\n if (used >= s.w_size) { /* supplant the previous history */\n s.matches = 2; /* clear hash */\n //zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);\n s.window.set(s.strm.input.subarray(s.strm.next_in - s.w_size, s.strm.next_in), 0);\n s.strstart = s.w_size;\n s.insert = s.strstart;\n }\n else {\n if (s.window_size - s.strstart <= used) {\n /* Slide the window down. */\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n //zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);\n s.window.set(s.strm.input.subarray(s.strm.next_in - used, s.strm.next_in), s.strstart);\n s.strstart += used;\n s.insert += used > s.w_size - s.insert ? s.w_size - s.insert : used;\n }\n s.block_start = s.strstart;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* If the last block was written to next_out, then done. */\n if (last) {\n return BS_FINISH_DONE;\n }\n\n /* If flushing and all input has been consumed, then done. */\n if (flush !== Z_NO_FLUSH$2 && flush !== Z_FINISH$3 &&\n s.strm.avail_in === 0 && s.strstart === s.block_start) {\n return BS_BLOCK_DONE;\n }\n\n /* Fill the window with any remaining input. */\n have = s.window_size - s.strstart;\n if (s.strm.avail_in > have && s.block_start >= s.w_size) {\n /* Slide the window down. */\n s.block_start -= s.w_size;\n s.strstart -= s.w_size;\n //zmemcpy(s->window, s->window + s->w_size, s->strstart);\n s.window.set(s.window.subarray(s.w_size, s.w_size + s.strstart), 0);\n if (s.matches < 2) {\n s.matches++; /* add a pending slide_hash() */\n }\n have += s.w_size; /* more space now */\n if (s.insert > s.strstart) {\n s.insert = s.strstart;\n }\n }\n if (have > s.strm.avail_in) {\n have = s.strm.avail_in;\n }\n if (have) {\n read_buf(s.strm, s.window, s.strstart, have);\n s.strstart += have;\n s.insert += have > s.w_size - s.insert ? s.w_size - s.insert : have;\n }\n if (s.high_water < s.strstart) {\n s.high_water = s.strstart;\n }\n\n /* There was not enough avail_out to write a complete worthy or flushed\n * stored block to next_out. Write a stored block to pending instead, if we\n * have enough input for a worthy block, or if flushing and there is enough\n * room for the remaining input as a stored block in the pending buffer.\n */\n have = (s.bi_valid + 42) >> 3; /* number of header bytes */\n /* maximum stored block length that will fit in pending: */\n have = s.pending_buf_size - have > 65535/* MAX_STORED */ ? 65535/* MAX_STORED */ : s.pending_buf_size - have;\n min_block = have > s.w_size ? s.w_size : have;\n left = s.strstart - s.block_start;\n if (left >= min_block ||\n ((left || flush === Z_FINISH$3) && flush !== Z_NO_FLUSH$2 &&\n s.strm.avail_in === 0 && left <= have)) {\n len = left > have ? have : left;\n last = flush === Z_FINISH$3 && s.strm.avail_in === 0 &&\n len === left ? 1 : 0;\n _tr_stored_block(s, s.block_start, len, last);\n s.block_start += len;\n flush_pending(s.strm);\n }\n\n /* We've done all we can with the available input and output. */\n return last ? BS_FINISH_STARTED : BS_NEED_MORE;\n};\n\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH$2) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH$3) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.sym_next) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED$2; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES + 1) * 2);\n zero(this.dyn_ltree);\n zero(this.dyn_dtree);\n zero(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES + 1); /* heap used to build the Huffman trees */\n zero(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES + 1); //uch depth[2*L_CODES+1];\n zero(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.sym_buf = 0; /* buffer for distances and literals/lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.sym_next = 0; /* running index in sym_buf */\n this.sym_end = 0; /* symbol table full when sym_next reaches this */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\n/* =========================================================================\n * Check for a valid deflate stream state. Return 0 if ok, 1 if not.\n */\nconst deflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const s = strm.state;\n if (!s || s.strm !== strm || (s.status !== INIT_STATE &&\n//#ifdef GZIP\n s.status !== GZIP_STATE &&\n//#endif\n s.status !== EXTRA_STATE &&\n s.status !== NAME_STATE &&\n s.status !== COMMENT_STATE &&\n s.status !== HCRC_STATE &&\n s.status !== BUSY_STATE &&\n s.status !== FINISH_STATE)) {\n return 1;\n }\n return 0;\n};\n\n\nconst deflateResetKeep = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status =\n//#ifdef GZIP\n s.wrap === 2 ? GZIP_STATE :\n//#endif\n s.wrap ? INIT_STATE : BUSY_STATE;\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = -2;\n _tr_init(s);\n return Z_OK$3;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK$3) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (deflateStateCheck(strm) || strm.state.wrap !== 2) {\n return Z_STREAM_ERROR$2;\n }\n strm.state.gzhead = head;\n return Z_OK$3;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR$2;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION$1) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED || (windowBits === 8 && wrap !== 1)) {\n return err(strm, Z_STREAM_ERROR$2);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n s.status = INIT_STATE; /* to pass state test in deflateReset() */\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n /* We overlay pending_buf and sym_buf. This works since the average size\n * for length/distance pairs over any compressed block is assured to be 31\n * bits or less.\n *\n * Analysis: The longest fixed codes are a length code of 8 bits plus 5\n * extra bits, for lengths 131 to 257. The longest fixed distance codes are\n * 5 bits plus 13 extra bits, for distances 16385 to 32768. The longest\n * possible fixed-codes length/distance pair is then 31 bits total.\n *\n * sym_buf starts one-fourth of the way into pending_buf. So there are\n * three bytes in sym_buf for every four bytes in pending_buf. Each symbol\n * in sym_buf is three bytes -- two for the distance and one for the\n * literal/length. As each symbol is consumed, the pointer to the next\n * sym_buf value to read moves forward three bytes. From that symbol, up to\n * 31 bits are written to pending_buf. The closest the written pending_buf\n * bits gets to the next sym_buf symbol to read is just before the last\n * code is written. At that time, 31*(n-2) bits have been written, just\n * after 24*(n-2) bits have been consumed from sym_buf. sym_buf starts at\n * 8*n bits into pending_buf. (Note that the symbol buffer fills when n-1\n * symbols are written.) The closest the writing gets to what is unread is\n * then n+14 bits. Here n is lit_bufsize, which is 16384 by default, and\n * can range from 128 to 32768.\n *\n * Therefore, at a minimum, there are 142 bits of space between what is\n * written and what is read in the overlain buffers, so the symbols cannot\n * be overwritten by the compressed data. That space is actually 139 bits,\n * due to the three-bit fixed-code block header.\n *\n * That covers the case where either Z_FIXED is specified, forcing fixed\n * codes, or when the use of fixed codes is chosen, because that choice\n * results in a smaller compressed block than dynamic codes. That latter\n * condition then assures that the above analysis also covers all dynamic\n * blocks. A dynamic-code block will only be chosen to be emitted if it has\n * fewer bits than a fixed-code block would for the same set of symbols.\n * Therefore its average symbol length is assured to be less than 31. So\n * the compressed data for a dynamic block also cannot overwrite the\n * symbols from which it is being constructed.\n */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->sym_buf = s->pending_buf + s->lit_bufsize;\n s.sym_buf = s.lit_bufsize;\n\n //s->sym_end = (s->lit_bufsize - 1) * 3;\n s.sym_end = (s.lit_bufsize - 1) * 3;\n /* We avoid equality with lit_bufsize*3 because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED$2, MAX_WBITS$1, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY$1);\n};\n\n\n/* ========================================================================= */\nconst deflate$2 = (strm, flush) => {\n\n if (deflateStateCheck(strm) || flush > Z_BLOCK$1 || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (strm.avail_in !== 0 && !strm.input) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH$3)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$1 : Z_STREAM_ERROR$2);\n }\n\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK$3;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH$3) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR$1);\n }\n\n /* Write the header */\n if (s.status === INIT_STATE && s.wrap === 0) {\n s.status = BUSY_STATE;\n }\n if (s.status === INIT_STATE) {\n /* zlib header */\n let header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#ifdef GZIP\n if (s.status === GZIP_STATE) {\n /* gzip header */\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let left = (s.gzhead.extra.length & 0xffff) - s.gzindex;\n while (s.pending + left > s.pending_buf_size) {\n let copy = s.pending_buf_size - s.pending;\n // zmemcpy(s.pending_buf + s.pending,\n // s.gzhead.extra + s.gzindex, copy);\n s.pending_buf.set(s.gzhead.extra.subarray(s.gzindex, s.gzindex + copy), s.pending);\n s.pending = s.pending_buf_size;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex += copy;\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n left -= copy;\n }\n // JS specific: s.gzhead.extra may be TypedArray or Array for backward compatibility\n // TypedArray.slice and TypedArray.from don't exist in IE10-IE11\n let gzhead_extra = new Uint8Array(s.gzhead.extra);\n // zmemcpy(s->pending_buf + s->pending,\n // s->gzhead->extra + s->gzindex, left);\n s.pending_buf.set(gzhead_extra.subarray(s.gzindex, s.gzindex + left), s.pending);\n s.pending += left;\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = NAME_STATE;\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n s.gzindex = 0;\n }\n s.status = COMMENT_STATE;\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n let beg = s.pending; /* start of bytes to update crc */\n let val;\n do {\n if (s.pending === s.pending_buf_size) {\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n beg = 0;\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n //--- HCRC_UPDATE(beg) ---//\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n //---//\n }\n s.status = HCRC_STATE;\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n }\n s.status = BUSY_STATE;\n\n /* Compression must start with an empty pending buffer */\n flush_pending(strm);\n if (s.pending !== 0) {\n s.last_flush = -1;\n return Z_OK$3;\n }\n }\n//#endif\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH$2 && s.status !== FINISH_STATE)) {\n let bstate = s.level === 0 ? deflate_stored(s, flush) :\n s.strategy === Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :\n s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush);\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK$3;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align(s);\n }\n else if (flush !== Z_BLOCK$1) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH$1) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK$3;\n }\n }\n }\n\n if (flush !== Z_FINISH$3) { return Z_OK$3; }\n if (s.wrap <= 0) { return Z_STREAM_END$3; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK$3 : Z_STREAM_END$3;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const status = strm.state.status;\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$3;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (deflateStateCheck(strm)) {\n return Z_STREAM_ERROR$2;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR$2;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK$3;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2$1 = deflate$2;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateGetDictionary = deflateGetDictionary;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1$2 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2$1,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\n\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n if (typeof TextEncoder === 'function' && TextEncoder.prototype.encode) {\n return new TextEncoder().encode(str);\n }\n\n let buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n buf = new Uint8Array(buf_len);\n\n // convert\n for (i = 0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) {\n c2 = str.charCodeAt(m_pos + 1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n const len = max || buf.length;\n\n if (typeof TextDecoder === 'function' && TextDecoder.prototype.decode) {\n return new TextDecoder().decode(buf.subarray(0, max));\n }\n\n let i, out;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n return buf2binstring(utf16buf, out);\n};\n\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = (buf, max) => {\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means buffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH, Z_FINISH: Z_FINISH$2,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2,\n Z_DEFAULT_COMPRESSION,\n Z_DEFAULT_STRATEGY,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate$1(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1$2.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1$2.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1$2.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$2) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$2 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1$2.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$2) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1$2.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$2;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$2) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate$1(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|ArrayBuffer|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip$1(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_2 = deflate$1;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar constants$1 = constants$2;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD$1 = 16209; /* got a data error -- remain here until reset */\nconst TYPE$1 = 16191; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE$1;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n// let shoextra; /* extra bits table to use */\n let match; /* use base and extra for symbol >= match */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES$1 || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES$1) {\n base = extra = work; /* dummy value--not used */\n match = 20;\n\n } else if (type === LENS$1) {\n base = lbase;\n extra = lext;\n match = 257;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n match = 0;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] + 1 < match) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] >= match) {\n here_op = extra[work[sym] - match];\n here_val = base[work[sym] - match];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS$1 && used > ENOUGH_LENS$1) ||\n (type === DISTS$1 && used > ENOUGH_DISTS$1)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$1, Z_BLOCK, Z_TREES,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR: Z_MEM_ERROR$1, Z_BUF_ERROR,\n Z_DEFLATED\n} = constants$2;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 16180; /* i: waiting for magic header */\nconst FLAGS = 16181; /* i: waiting for method and flags (gzip) */\nconst TIME = 16182; /* i: waiting for modification time (gzip) */\nconst OS = 16183; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 16184; /* i: waiting for extra length (gzip) */\nconst EXTRA = 16185; /* i: waiting for extra bytes (gzip) */\nconst NAME = 16186; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 16187; /* i: waiting for end of comment (gzip) */\nconst HCRC = 16188; /* i: waiting for header crc (gzip) */\nconst DICTID = 16189; /* i: waiting for dictionary check value */\nconst DICT = 16190; /* waiting for inflateSetDictionary() call */\nconst TYPE = 16191; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 16192; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 16193; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 16194; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16195; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 16196; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 16197; /* i: waiting for code length code lengths */\nconst CODELENS = 16198; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 16199; /* i: same as LEN below, but only first time in */\nconst LEN = 16200; /* i: waiting for length/lit/eob code */\nconst LENEXT = 16201; /* i: waiting for length extra bits */\nconst DIST = 16202; /* i: waiting for distance code */\nconst DISTEXT = 16203; /* i: waiting for distance extra bits */\nconst MATCH = 16204; /* o: waiting for output space to copy string */\nconst LIT = 16205; /* o: waiting for output space to write literal */\nconst CHECK = 16206; /* i: waiting for 32-bit check value */\nconst LENGTH = 16207; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 16208; /* finished check, done -- remain here until reset */\nconst BAD = 16209; /* got a data error -- remain here until reset */\nconst MEM = 16210; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 16211; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip,\n bit 2 true to validate check value */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib), or\n -1 if raw or no header yet */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateStateCheck = (strm) => {\n\n if (!strm) {\n return 1;\n }\n const state = strm.state;\n if (!state || state.strm !== strm ||\n state.mode < HEAD || state.mode > SYNC) {\n return 1;\n }\n return 0;\n};\n\n\nconst inflateResetKeep = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.flags = -1;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$1;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.strm = strm;\n state.window = null/*Z_NULL*/;\n state.mode = HEAD; /* to pass state test in inflateReset2() */\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$1) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate$2 = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (inflateStateCheck(strm) || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$1;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n if (state.wbits === 0) {\n state.wbits = 15;\n }\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n if (len > 15 || len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n state.flags = 0; /* indicate zlib header */\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED) {\n strm.msg = 'unknown compression method';\n state.mode = BAD;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if ((state.flags & 0x0200) && (state.wrap & 4)) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT$1;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE;\n /* falls through */\n case TYPE:\n if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check =\n /*UPDATE_CHECK(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.wrap & 4) && (state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 4) && hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$1;\n break inf_leave;\n case BAD:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR$1;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&\n (state.mode < CHECK || flush !== Z_FINISH$1))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if ((state.wrap & 4) && _out) {\n strm.adler = state.check = /*UPDATE_CHECK(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) {\n ret = Z_BUF_ERROR;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (inflateStateCheck(strm)) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$1;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$1;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (inflateStateCheck(strm)) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR$1;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$1;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2$1 = inflate$2;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCodesUsed = inflateCodesUsed;\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\nmodule.exports.inflateValidate = inflateValidate;\n*/\n\nvar inflate_1$2 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2$1,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_FINISH,\n Z_OK, Z_STREAM_END, Z_NEED_DICT, Z_STREAM_ERROR, Z_DATA_ERROR, Z_MEM_ERROR\n} = constants$2;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate$1(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1$2.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1$2.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1$2.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate$1.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH : Z_NO_FLUSH;\n\n // Convert data if needed\n if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1$2.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT && dictionary) {\n status = inflate_1$2.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK) {\n status = inflate_1$2.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR) {\n // Replace code with more verbose\n status = Z_NEED_DICT;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1$2.inflateReset(strm);\n status = inflate_1$2.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR:\n case Z_DATA_ERROR:\n case Z_NEED_DICT:\n case Z_MEM_ERROR:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END) {\n status = inflate_1$2.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate$1.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate$1.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err) {\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate$1(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw$1(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array|ArrayBuffer): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1$1 = Inflate$1;\nvar inflate_2 = inflate$1;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip$1 = inflate$1;\nvar constants = constants$2;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1$1,\n\tinflate: inflate_2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip$1,\n\tconstants: constants\n};\n\nconst { Deflate, deflate, deflateRaw, gzip } = deflate_1$1;\n\nconst { Inflate, inflate, inflateRaw, ungzip } = inflate_1$1;\n\n\n\nvar Deflate_1 = Deflate;\nvar deflate_1 = deflate;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar Inflate_1 = Inflate;\nvar inflate_1 = inflate;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip_1 = ungzip;\nvar constants_1 = constants$2;\n\nvar pako = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tInflate: Inflate_1,\n\tinflate: inflate_1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport { Deflate_1 as Deflate, Inflate_1 as Inflate, constants_1 as constants, pako as default, deflate_1 as deflate, deflateRaw_1 as deflateRaw, gzip_1 as gzip, inflate_1 as inflate, inflateRaw_1 as inflateRaw, ungzip_1 as ungzip };\n","export const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];\nconst crcTable = [];\nfor (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) {\n if (c & 1) {\n c = 0xedb88320 ^ (c >>> 1);\n }\n else {\n c = c >>> 1;\n }\n }\n crcTable[n] = c;\n}\nconst initialCrc = 0xffffffff;\nfunction updateCrc(currentCrc, data, length) {\n let c = currentCrc;\n for (let n = 0; n < length; n++) {\n c = crcTable[(c ^ data[n]) & 0xff] ^ (c >>> 8);\n }\n return c;\n}\nexport function crc(data, length) {\n return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;\n}\n//# sourceMappingURL=common.js.map","export var ColorType;\n(function (ColorType) {\n ColorType[ColorType[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n ColorType[ColorType[\"GREYSCALE\"] = 0] = \"GREYSCALE\";\n ColorType[ColorType[\"TRUECOLOUR\"] = 2] = \"TRUECOLOUR\";\n ColorType[ColorType[\"INDEXED_COLOUR\"] = 3] = \"INDEXED_COLOUR\";\n ColorType[ColorType[\"GREYSCALE_ALPHA\"] = 4] = \"GREYSCALE_ALPHA\";\n ColorType[ColorType[\"TRUECOLOUR_ALPHA\"] = 6] = \"TRUECOLOUR_ALPHA\";\n})(ColorType || (ColorType = {}));\nexport var CompressionMethod;\n(function (CompressionMethod) {\n CompressionMethod[CompressionMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n CompressionMethod[CompressionMethod[\"DEFLATE\"] = 0] = \"DEFLATE\";\n})(CompressionMethod || (CompressionMethod = {}));\nexport var FilterMethod;\n(function (FilterMethod) {\n FilterMethod[FilterMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n FilterMethod[FilterMethod[\"ADAPTIVE\"] = 0] = \"ADAPTIVE\";\n})(FilterMethod || (FilterMethod = {}));\nexport var InterlaceMethod;\n(function (InterlaceMethod) {\n InterlaceMethod[InterlaceMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n InterlaceMethod[InterlaceMethod[\"NO_INTERLACE\"] = 0] = \"NO_INTERLACE\";\n InterlaceMethod[InterlaceMethod[\"ADAM7\"] = 1] = \"ADAM7\";\n})(InterlaceMethod || (InterlaceMethod = {}));\n//# sourceMappingURL=internalTypes.js.map","import { IOBuffer } from 'iobuffer';\nimport { Inflate as Inflator } from 'pako';\nimport { pngSignature, crc } from './common';\nimport { ColorType, CompressionMethod, FilterMethod, InterlaceMethod, } from './internalTypes';\nconst empty = new Uint8Array(0);\nconst NULL = '\\0';\nconst uint16 = new Uint16Array([0x00ff]);\nconst uint8 = new Uint8Array(uint16.buffer);\nconst osIsLittleEndian = uint8[0] === 0xff;\nexport default class PNGDecoder extends IOBuffer {\n constructor(data, options = {}) {\n super(data);\n const { checkCrc = false } = options;\n this._checkCrc = checkCrc;\n this._inflator = new Inflator();\n this._png = {\n width: -1,\n height: -1,\n channels: -1,\n data: new Uint8Array(0),\n depth: 1,\n text: {},\n };\n this._end = false;\n this._hasPalette = false;\n this._palette = [];\n this._compressionMethod = CompressionMethod.UNKNOWN;\n this._filterMethod = FilterMethod.UNKNOWN;\n this._interlaceMethod = InterlaceMethod.UNKNOWN;\n this._colorType = -1;\n // PNG is always big endian\n // https://www.w3.org/TR/PNG/#7Integers-and-byte-order\n this.setBigEndian();\n }\n decode() {\n this.decodeSignature();\n while (!this._end) {\n this.decodeChunk();\n }\n this.decodeImage();\n return this._png;\n }\n // https://www.w3.org/TR/PNG/#5PNG-file-signature\n decodeSignature() {\n for (let i = 0; i < pngSignature.length; i++) {\n if (this.readUint8() !== pngSignature[i]) {\n throw new Error(`wrong PNG signature. Byte at ${i} should be ${pngSignature[i]}.`);\n }\n }\n }\n // https://www.w3.org/TR/PNG/#5Chunk-layout\n decodeChunk() {\n const length = this.readUint32();\n const type = this.readChars(4);\n const offset = this.offset;\n switch (type) {\n // 11.2 Critical chunks\n case 'IHDR': // 11.2.2 IHDR Image header\n this.decodeIHDR();\n break;\n case 'PLTE': // 11.2.3 PLTE Palette\n this.decodePLTE(length);\n break;\n case 'IDAT': // 11.2.4 IDAT Image data\n this.decodeIDAT(length);\n break;\n case 'IEND': // 11.2.5 IEND Image trailer\n this._end = true;\n break;\n // 11.3 Ancillary chunks\n case 'tRNS': // 11.3.2.1 tRNS Transparency\n this.decodetRNS(length);\n break;\n case 'tEXt': // 11.3.4.3 tEXt Textual data\n this.decodetEXt(length);\n break;\n case 'pHYs': // 11.3.5.3 pHYs Physical pixel dimensions\n this.decodepHYs();\n break;\n default:\n this.skip(length);\n break;\n }\n if (this.offset - offset !== length) {\n throw new Error(`Length mismatch while decoding chunk ${type}`);\n }\n if (this._checkCrc) {\n const expectedCrc = this.readUint32();\n const crcLength = length + 4; // includes type\n const actualCrc = crc(new Uint8Array(this.buffer, this.byteOffset + this.offset - crcLength - 4, crcLength), crcLength); // \"- 4\" because we already advanced by reading the CRC\n if (actualCrc !== expectedCrc) {\n throw new Error(`CRC mismatch for chunk ${type}. Expected ${expectedCrc}, found ${actualCrc}`);\n }\n }\n else {\n this.skip(4);\n }\n }\n // https://www.w3.org/TR/PNG/#11IHDR\n decodeIHDR() {\n const image = this._png;\n image.width = this.readUint32();\n image.height = this.readUint32();\n image.depth = checkBitDepth(this.readUint8());\n const colorType = this.readUint8();\n this._colorType = colorType;\n let channels;\n switch (colorType) {\n case ColorType.GREYSCALE:\n channels = 1;\n break;\n case ColorType.TRUECOLOUR:\n channels = 3;\n break;\n case ColorType.INDEXED_COLOUR:\n channels = 1;\n break;\n case ColorType.GREYSCALE_ALPHA:\n channels = 2;\n break;\n case ColorType.TRUECOLOUR_ALPHA:\n channels = 4;\n break;\n default:\n throw new Error(`Unknown color type: ${colorType}`);\n }\n this._png.channels = channels;\n this._compressionMethod = this.readUint8();\n if (this._compressionMethod !== CompressionMethod.DEFLATE) {\n throw new Error(`Unsupported compression method: ${this._compressionMethod}`);\n }\n this._filterMethod = this.readUint8();\n this._interlaceMethod = this.readUint8();\n }\n // https://www.w3.org/TR/PNG/#11PLTE\n decodePLTE(length) {\n if (length % 3 !== 0) {\n throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`);\n }\n const l = length / 3;\n this._hasPalette = true;\n const palette = [];\n this._palette = palette;\n for (let i = 0; i < l; i++) {\n palette.push([this.readUint8(), this.readUint8(), this.readUint8()]);\n }\n }\n // https://www.w3.org/TR/PNG/#11IDAT\n decodeIDAT(length) {\n this._inflator.push(new Uint8Array(this.buffer, this.offset + this.byteOffset, length));\n this.skip(length);\n }\n // https://www.w3.org/TR/PNG/#11tRNS\n decodetRNS(length) {\n // TODO: support other color types.\n if (this._colorType === 3) {\n if (length > this._palette.length) {\n throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`);\n }\n let i = 0;\n for (; i < length; i++) {\n const alpha = this.readByte();\n this._palette[i].push(alpha);\n }\n for (; i < this._palette.length; i++) {\n this._palette[i].push(255);\n }\n }\n }\n // https://www.w3.org/TR/PNG/#11tEXt\n decodetEXt(length) {\n let keyword = '';\n let char;\n while ((char = this.readChar()) !== NULL) {\n keyword += char;\n }\n this._png.text[keyword] = this.readChars(length - keyword.length - 1);\n }\n // https://www.w3.org/TR/PNG/#11pHYs\n decodepHYs() {\n const ppuX = this.readUint32();\n const ppuY = this.readUint32();\n const unitSpecifier = this.readByte();\n this._png.resolution = { x: ppuX, y: ppuY, unit: unitSpecifier };\n }\n decodeImage() {\n if (this._inflator.err) {\n throw new Error(`Error while decompressing the data: ${this._inflator.err}`);\n }\n const data = this._inflator.result;\n if (this._filterMethod !== FilterMethod.ADAPTIVE) {\n throw new Error(`Filter method ${this._filterMethod} not supported`);\n }\n if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {\n this.decodeInterlaceNull(data);\n }\n else {\n throw new Error(`Interlace method ${this._interlaceMethod} not supported`);\n }\n }\n decodeInterlaceNull(data) {\n const height = this._png.height;\n const bytesPerPixel = (this._png.channels * this._png.depth) / 8;\n const bytesPerLine = this._png.width * bytesPerPixel;\n const newData = new Uint8Array(this._png.height * bytesPerLine);\n let prevLine = empty;\n let offset = 0;\n let currentLine;\n let newLine;\n for (let i = 0; i < height; i++) {\n currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);\n newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);\n switch (data[offset]) {\n case 0:\n unfilterNone(currentLine, newLine, bytesPerLine);\n break;\n case 1:\n unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);\n break;\n case 2:\n unfilterUp(currentLine, newLine, prevLine, bytesPerLine);\n break;\n case 3:\n unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);\n break;\n case 4:\n unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);\n break;\n default:\n throw new Error(`Unsupported filter: ${data[offset]}`);\n }\n prevLine = newLine;\n offset += bytesPerLine + 1;\n }\n if (this._hasPalette) {\n this._png.palette = this._palette;\n }\n if (this._png.depth === 16) {\n const uint16Data = new Uint16Array(newData.buffer);\n if (osIsLittleEndian) {\n for (let k = 0; k < uint16Data.length; k++) {\n // PNG is always big endian. Swap the bytes.\n uint16Data[k] = swap16(uint16Data[k]);\n }\n }\n this._png.data = uint16Data;\n }\n else {\n this._png.data = newData;\n }\n }\n}\nfunction unfilterNone(currentLine, newLine, bytesPerLine) {\n for (let i = 0; i < bytesPerLine; i++) {\n newLine[i] = currentLine[i];\n }\n}\nfunction unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n for (; i < bytesPerPixel; i++) {\n // just copy first bytes\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + newLine[i - bytesPerPixel]) & 0xff;\n }\n}\nfunction unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {\n let i = 0;\n if (prevLine.length === 0) {\n // just copy bytes for first line\n for (; i < bytesPerLine; i++) {\n newLine[i] = currentLine[i];\n }\n }\n else {\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + prevLine[i]) & 0xff;\n }\n }\n}\nfunction unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n if (prevLine.length === 0) {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + (newLine[i - bytesPerPixel] >> 1)) & 0xff;\n }\n }\n else {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = (currentLine[i] + (prevLine[i] >> 1)) & 0xff;\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] =\n (currentLine[i] + ((newLine[i - bytesPerPixel] + prevLine[i]) >> 1)) &\n 0xff;\n }\n }\n}\nfunction unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n if (prevLine.length === 0) {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + newLine[i - bytesPerPixel]) & 0xff;\n }\n }\n else {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = (currentLine[i] + prevLine[i]) & 0xff;\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] =\n (currentLine[i] +\n paethPredictor(newLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel])) &\n 0xff;\n }\n }\n}\nfunction paethPredictor(a, b, c) {\n const p = a + b - c;\n const pa = Math.abs(p - a);\n const pb = Math.abs(p - b);\n const pc = Math.abs(p - c);\n if (pa <= pb && pa <= pc)\n return a;\n else if (pb <= pc)\n return b;\n else\n return c;\n}\nfunction swap16(val) {\n return ((val & 0xff) << 8) | ((val >> 8) & 0xff);\n}\nfunction checkBitDepth(value) {\n if (value !== 1 &&\n value !== 2 &&\n value !== 4 &&\n value !== 8 &&\n value !== 16) {\n throw new Error(`invalid bit depth: ${value}`);\n }\n return value;\n}\n//# sourceMappingURL=PNGDecoder.js.map","export var ResolutionUnitSpecifier;\n(function (ResolutionUnitSpecifier) {\n /**\n * Unit is unknown\n */\n ResolutionUnitSpecifier[ResolutionUnitSpecifier[\"UNKNOWN\"] = 0] = \"UNKNOWN\";\n /**\n * Unit is the metre\n */\n ResolutionUnitSpecifier[ResolutionUnitSpecifier[\"METRE\"] = 1] = \"METRE\";\n})(ResolutionUnitSpecifier || (ResolutionUnitSpecifier = {}));\n//# sourceMappingURL=types.js.map","import PNGDecoder from './PNGDecoder';\nimport PNGEncoder from './PNGEncoder';\nexport * from './types';\nfunction decodePNG(data, options) {\n const decoder = new PNGDecoder(data, options);\n return decoder.decode();\n}\nfunction encodePNG(png, options) {\n const encoder = new PNGEncoder(png, options);\n return encoder.encode();\n}\nexport { decodePNG as decode, encodePNG as encode };\n//# sourceMappingURL=index.js.map","import { GltfObject } from './gltf_object.js';\nimport { isPowerOf2 } from './math_utils.js';\nimport { AsyncFileReader } from '../ResourceLoader/async_file_reader.js';\nimport { GL } from \"../Renderer/webgl\";\nimport { ImageMimeType } from \"./image_mime_type.js\";\nimport * as jpeg from \"jpeg-js\";\nimport * as png from 'fast-png';\n\nclass gltfImage extends GltfObject\n{\n constructor(\n uri = undefined,\n type = GL.TEXTURE_2D,\n miplevel = 0,\n bufferView = undefined,\n name = undefined,\n mimeType = ImageMimeType.JPEG,\n image = undefined)\n {\n super();\n this.uri = uri;\n this.bufferView = bufferView;\n this.mimeType = mimeType;\n this.image = image; // javascript image\n this.name = name;\n this.type = type; // nonstandard\n this.miplevel = miplevel; // nonstandard\n }\n\n resolveRelativePath(basePath)\n {\n if (typeof this.uri === 'string' || this.uri instanceof String)\n {\n if (this.uri.startsWith('./')) {\n // Remove preceding './' from URI.\n this.uri = basePath + this.uri.substr(2);\n } else if (this.uri.startsWith('http') || this.uri.startsWith('data')) {\n\n } else {\n this.uri = basePath + this.uri;\n }\n }\n }\n\n async load(gltf, additionalFiles = undefined)\n {\n if (this.image !== undefined)\n {\n if (this.mimeType !== ImageMimeType.GLTEXTURE)\n {\n console.error(\"image has already been loaded\");\n }\n return;\n }\n\n if (!await this.setImageFromBufferView(gltf) &&\n !await this.setImageFromFiles(additionalFiles, gltf) &&\n !await this.setImageFromUri(gltf))\n {\n console.error(\"Was not able to resolve image with uri '%s'\", this.uri);\n return;\n }\n\n return;\n }\n\n static loadHTMLImage(url)\n {\n return new Promise( (resolve, reject) => {\n const image = new Image();\n image.addEventListener('load', () => resolve(image) );\n image.addEventListener('error', reject);\n image.src = url;\n image.crossOrigin = \"\";\n });\n }\n\n async setImageFromUri(gltf)\n {\n if (this.uri === undefined)\n {\n return false;\n }\n\n if(this.mimeType === ImageMimeType.KTX2)\n {\n if (gltf.ktxDecoder !== undefined)\n {\n this.image = await gltf.ktxDecoder.loadKtxFromUri(this.uri);\n }\n else\n {\n console.warn('Loading of ktx images failed: KtxDecoder not initalized');\n }\n }\n else if (typeof(Image) !== 'undefined' && (this.mimeType === ImageMimeType.JPEG || this.mimeType === ImageMimeType.PNG))\n {\n this.image = await gltfImage.loadHTMLImage(this.uri).catch( (error) => {\n console.error(error);\n });\n }\n else if(this.mimeType === ImageMimeType.JPEG && this.uri instanceof ArrayBuffer)\n {\n this.image = jpeg.decode(this.uri, {useTArray: true});\n }\n else if(this.mimeType === ImageMimeType.PNG && this.uri instanceof ArrayBuffer)\n {\n this.image = png.decode(this.uri);\n }\n else\n {\n console.error(\"Unsupported image type \" + this.mimeType);\n return false;\n }\n\n return true;\n }\n\n async setImageFromBufferView(gltf)\n {\n const view = gltf.bufferViews[this.bufferView];\n if (view === undefined)\n {\n return false;\n }\n\n const buffer = gltf.buffers[view.buffer].buffer;\n const array = new Uint8Array(buffer, view.byteOffset, view.byteLength);\n if (this.mimeType === ImageMimeType.KTX2)\n {\n if (gltf.ktxDecoder !== undefined)\n {\n this.image = await gltf.ktxDecoder.loadKtxFromBuffer(array);\n }\n else\n {\n console.warn('Loading of ktx images failed: KtxDecoder not initalized');\n }\n }\n else if(typeof(Image) !== 'undefined' && (this.mimeType === ImageMimeType.JPEG || this.mimeType === ImageMimeType.PNG))\n {\n const blob = new Blob([array], { \"type\": this.mimeType });\n const objectURL = URL.createObjectURL(blob);\n this.image = await gltfImage.loadHTMLImage(objectURL).catch( () => {\n console.error(\"Could not load image from buffer view\");\n });\n }\n else if(this.mimeType === ImageMimeType.JPEG)\n {\n this.image = jpeg.decode(array, {useTArray: true});\n }\n else if(this.mimeType === ImageMimeType.PNG)\n {\n this.image = png.decode(array);\n }\n else\n {\n console.error(\"Unsupported image type \" + this.mimeType);\n return false;\n }\n\n return true;\n }\n\n async setImageFromFiles(files, gltf)\n {\n if (this.uri === undefined || files === undefined)\n {\n return false;\n }\n\n let foundFile = files.find(function(file)\n {\n const uriName = this.uri.split('\\\\').pop().split('/').pop();\n if (file.name === uriName)\n {\n return true;\n }\n }, this);\n\n if (foundFile === undefined)\n {\n return false;\n }\n\n if(this.mimeType === ImageMimeType.KTX2)\n {\n if (gltf.ktxDecoder !== undefined)\n {\n const data = new Uint8Array(await foundFile.arrayBuffer());\n this.image = await gltf.ktxDecoder.loadKtxFromBuffer(data);\n }\n else\n {\n console.warn('Loading of ktx images failed: KtxDecoder not initalized');\n }\n }\n else if (typeof(Image) !== 'undefined' && (this.mimeType === ImageMimeType.JPEG || this.mimeType === ImageMimeType.PNG))\n {\n const imageData = await AsyncFileReader.readAsDataURL(foundFile).catch( () => {\n console.error(\"Could not load image with FileReader\");\n });\n this.image = await gltfImage.loadHTMLImage(imageData).catch( () => {\n console.error(\"Could not create image from FileReader image data\");\n });\n }\n else\n {\n console.error(\"Unsupported image type \" + this.mimeType);\n return false;\n }\n\n\n return true;\n }\n}\n\nexport { gltfImage, ImageMimeType };\n\n","import { jsToGl } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\nimport { GL } from \"../Renderer/webgl\";\n\n// https://github.com/KhronosGroup/glTF/blob/khr_ktx2_ibl/extensions/2.0/Khronos/KHR_lights_image_based/schema/imageBasedLight.schema.json\n\nclass ImageBasedLight extends GltfObject\n{\n constructor()\n {\n super();\n this.rotation = jsToGl([0, 0, 0, 1]);\n this.brightnessFactor = 1;\n this.brightnessOffset = 0;\n this.specularEnvironmentTexture = undefined;\n this.diffuseEnvironmentTexture = undefined;\n this.sheenEnvironmentTexture = undefined;\n\n // non-gltf\n this.levelCount = 1;\n }\n\n fromJson(jsonIBL)\n {\n super.fromJson(jsonIBL);\n\n if(jsonIBL.extensions !== undefined)\n {\n this.fromJsonExtensions(jsonIBL.extensions);\n }\n }\n\n fromJsonExtensions(extensions)\n {\n if (extensions.KHR_materials_sheen !== undefined)\n {\n this.sheenEnvironmentTexture = extensions.KHR_materials_sheen.sheenEnvironmentTexture;\n }\n }\n\n initGl(gltf, webGlContext)\n {\n if (this.diffuseEnvironmentTexture !== undefined)\n {\n const textureObject = gltf.textures[this.diffuseEnvironmentTexture];\n textureObject.type = GL.TEXTURE_CUBE_MAP;\n }\n if (this.specularEnvironmentTexture !== undefined)\n {\n const textureObject = gltf.textures[this.specularEnvironmentTexture];\n textureObject.type = GL.TEXTURE_CUBE_MAP;\n\n const imageObject = gltf.images[textureObject.source];\n this.levelCount = imageObject.image.levelCount;\n }\n if(this.sheenEnvironmentTexture !== undefined)\n {\n const textureObject = gltf.textures[this.sheenEnvironmentTexture];\n textureObject.type = GL.TEXTURE_CUBE_MAP;\n\n const imageObject = gltf.images[textureObject.source];\n if (this.levelCount !== imageObject.image.levelCount)\n {\n console.error(\"Specular and sheen do not have same level count\");\n }\n }\n }\n}\n\nexport { ImageBasedLight };\n","import { fromKeys, initGlForMembers } from './utils.js';\nimport { GL } from '../Renderer/webgl.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfTexture extends GltfObject\n{\n constructor(sampler = undefined, source = undefined, type = GL.TEXTURE_2D)\n {\n super();\n this.sampler = sampler; // index to gltfSampler, default sampler ?\n this.source = source; // index to gltfImage\n\n // non gltf\n this.glTexture = undefined;\n this.type = type;\n this.initialized = false;\n this.mipLevelCount = 0;\n }\n\n initGl(gltf, webGlContext)\n {\n if (this.sampler === undefined)\n {\n this.sampler = gltf.samplers.length - 1;\n }\n\n initGlForMembers(this, gltf, webGlContext);\n }\n\n fromJson(jsonTexture)\n {\n super.fromJson(jsonTexture);\n if (jsonTexture.extensions !== undefined &&\n jsonTexture.extensions.KHR_texture_basisu !== undefined &&\n jsonTexture.extensions.KHR_texture_basisu.source !== undefined)\n {\n this.source = jsonTexture.extensions.KHR_texture_basisu.source;\n }\n }\n\n destroy()\n {\n if (this.glTexture !== undefined)\n {\n // TODO: this breaks the dependency direction\n WebGl.context.deleteTexture(this.glTexture);\n }\n\n this.glTexture = undefined;\n }\n}\n\nclass gltfTextureInfo\n{\n constructor(index = undefined, texCoord = 0, linear = true, samplerName = \"\", generateMips = true) // linear by default\n {\n this.index = index; // reference to gltfTexture\n this.texCoord = texCoord; // which UV set to use\n this.linear = linear;\n this.samplerName = samplerName;\n this.strength = 1.0; // occlusion\n this.scale = 1.0; // normal\n this.generateMips = generateMips;\n\n this.extensions = undefined;\n }\n\n initGl(gltf, webGlContext)\n {\n initGlForMembers(this, gltf, webGlContext);\n }\n\n fromJson(jsonTextureInfo)\n {\n fromKeys(this, jsonTextureInfo);\n }\n}\n\nexport { gltfTexture, gltfTextureInfo };\n","import { mat3, vec3, vec4 } from 'gl-matrix';\nimport { gltfTextureInfo } from './texture.js';\nimport { jsToGl, initGlForMembers } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfMaterial extends GltfObject\n{\n constructor()\n {\n super();\n this.name = undefined;\n this.pbrMetallicRoughness = undefined;\n this.normalTexture = undefined;\n this.occlusionTexture = undefined;\n this.emissiveTexture = undefined;\n this.emissiveFactor = vec3.fromValues(0, 0, 0);\n this.alphaMode = \"OPAQUE\";\n this.alphaCutoff = 0.5;\n this.doubleSided = false;\n\n // pbr next extension toggles\n this.hasClearcoat = false;\n this.hasSheen = false;\n this.hasTransmission = false;\n this.hasIOR = false;\n this.hasEmissiveStrength = false;\n this.hasVolume = false;\n this.hasIridescence = false;\n\n // non gltf properties\n this.type = \"unlit\";\n this.textures = [];\n this.properties = new Map();\n this.defines = [];\n }\n\n static createDefault()\n {\n const defaultMaterial = new gltfMaterial();\n defaultMaterial.type = \"MR\";\n defaultMaterial.name = \"Default Material\";\n defaultMaterial.defines.push(\"MATERIAL_METALLICROUGHNESS 1\");\n const baseColorFactor = vec4.fromValues(1, 1, 1, 1);\n const metallicFactor = 1;\n const roughnessFactor = 1;\n defaultMaterial.properties.set(\"u_BaseColorFactor\", baseColorFactor);\n defaultMaterial.properties.set(\"u_MetallicFactor\", metallicFactor);\n defaultMaterial.properties.set(\"u_RoughnessFactor\", roughnessFactor);\n\n return defaultMaterial;\n }\n\n getShaderIdentifier()\n {\n switch (this.type)\n {\n default:\n case \"SG\": // fall through till we sparate shaders\n case \"MR\": return \"pbr.frag\";\n //case \"SG\": return \"specular-glossiness.frag\" ;\n }\n }\n\n getDefines(renderingParameters)\n {\n const defines = Array.from(this.defines);\n\n if (this.hasClearcoat && renderingParameters.enabledExtensions.KHR_materials_clearcoat)\n {\n defines.push(\"MATERIAL_CLEARCOAT 1\");\n }\n if (this.hasSheen && renderingParameters.enabledExtensions.KHR_materials_sheen)\n {\n defines.push(\"MATERIAL_SHEEN 1\");\n }\n if (this.hasTransmission && renderingParameters.enabledExtensions.KHR_materials_transmission)\n {\n defines.push(\"MATERIAL_TRANSMISSION 1\");\n }\n if (this.hasVolume && renderingParameters.enabledExtensions.KHR_materials_volume)\n {\n defines.push(\"MATERIAL_VOLUME 1\");\n }\n if(this.hasIOR && renderingParameters.enabledExtensions.KHR_materials_ior)\n {\n defines.push(\"MATERIAL_IOR 1\");\n }\n if(this.hasSpecular && renderingParameters.enabledExtensions.KHR_materials_specular)\n {\n defines.push(\"MATERIAL_SPECULAR 1\");\n }\n if(this.hasIridescence && renderingParameters.enabledExtensions.KHR_materials_iridescence)\n {\n defines.push(\"MATERIAL_IRIDESCENCE 1\");\n }\n if(this.hasEmissiveStrength && renderingParameters.enabledExtensions.KHR_materials_emissive_strength)\n {\n defines.push(\"MATERIAL_EMISSIVE_STRENGTH 1\");\n }\n\n return defines;\n }\n\n getProperties()\n {\n return this.properties;\n }\n\n getTextures()\n {\n return this.textures;\n }\n\n parseTextureInfoExtensions(textureInfo, textureKey)\n {\n if(textureInfo.extensions === undefined)\n {\n return;\n }\n\n if(textureInfo.extensions.KHR_texture_transform !== undefined)\n {\n const uvTransform = textureInfo.extensions.KHR_texture_transform;\n\n // override uvset\n if(uvTransform.texCoord !== undefined)\n {\n textureInfo.texCoord = uvTransform.texCoord;\n }\n\n let rotation = mat3.create();\n let scale = mat3.create();\n let translation = mat3.create();\n\n if(uvTransform.rotation !== undefined)\n {\n const s = Math.sin(uvTransform.rotation);\n const c = Math.cos(uvTransform.rotation);\n\n rotation = jsToGl([\n c, -s, 0.0,\n s, c, 0.0,\n 0.0, 0.0, 1.0]);\n }\n\n if(uvTransform.scale !== undefined)\n {\n scale = jsToGl([\n uvTransform.scale[0], 0, 0, \n 0, uvTransform.scale[1], 0, \n 0, 0, 1\n ]);\n }\n\n if(uvTransform.offset !== undefined)\n {\n translation = jsToGl([\n 1, 0, 0, \n 0, 1, 0, \n uvTransform.offset[0], uvTransform.offset[1], 1\n ]);\n }\n\n let uvMatrix = mat3.create();\n mat3.multiply(uvMatrix, translation, rotation);\n mat3.multiply(uvMatrix, uvMatrix, scale);\n\n this.defines.push(\"HAS_\" + textureKey.toUpperCase() + \"_UV_TRANSFORM 1\");\n this.properties.set(\"u_\" + textureKey + \"UVTransform\", uvMatrix);\n }\n }\n\n initGl(gltf, webGlContext)\n {\n if (this.normalTexture !== undefined)\n {\n this.normalTexture.samplerName = \"u_NormalSampler\";\n this.parseTextureInfoExtensions(this.normalTexture, \"Normal\");\n this.textures.push(this.normalTexture);\n this.defines.push(\"HAS_NORMAL_MAP 1\");\n this.properties.set(\"u_NormalScale\", this.normalTexture.scale);\n this.properties.set(\"u_NormalUVSet\", this.normalTexture.texCoord);\n }\n\n if (this.occlusionTexture !== undefined)\n {\n this.occlusionTexture.samplerName = \"u_OcclusionSampler\";\n this.parseTextureInfoExtensions(this.occlusionTexture, \"Occlusion\");\n this.textures.push(this.occlusionTexture);\n this.defines.push(\"HAS_OCCLUSION_MAP 1\");\n this.properties.set(\"u_OcclusionStrength\", this.occlusionTexture.strength);\n this.properties.set(\"u_OcclusionUVSet\", this.occlusionTexture.texCoord);\n }\n\n this.properties.set(\"u_EmissiveFactor\", this.emissiveFactor);\n if (this.emissiveTexture !== undefined)\n {\n this.emissiveTexture.samplerName = \"u_EmissiveSampler\";\n this.parseTextureInfoExtensions(this.emissiveTexture, \"Emissive\");\n this.textures.push(this.emissiveTexture);\n this.defines.push(\"HAS_EMISSIVE_MAP 1\");\n this.properties.set(\"u_EmissiveUVSet\", this.emissiveTexture.texCoord);\n }\n\n if (this.baseColorTexture !== undefined)\n {\n this.baseColorTexture.samplerName = \"u_BaseColorSampler\";\n this.parseTextureInfoExtensions(this.baseColorTexture, \"BaseColor\");\n this.textures.push(this.baseColorTexture);\n this.defines.push(\"HAS_BASE_COLOR_MAP 1\");\n this.properties.set(\"u_BaseColorUVSet\", this.baseColorTexture.texCoord);\n }\n\n if (this.metallicRoughnessTexture !== undefined)\n {\n this.metallicRoughnessTexture.samplerName = \"u_MetallicRoughnessSampler\";\n this.parseTextureInfoExtensions(this.metallicRoughnessTexture, \"MetallicRoughness\");\n this.textures.push(this.metallicRoughnessTexture);\n this.defines.push(\"HAS_METALLIC_ROUGHNESS_MAP 1\");\n this.properties.set(\"u_MetallicRoughnessUVSet\", this.metallicRoughnessTexture.texCoord);\n }\n\n if (this.diffuseTexture !== undefined)\n {\n this.diffuseTexture.samplerName = \"u_DiffuseSampler\";\n this.parseTextureInfoExtensions(this.diffuseTexture, \"Diffuse\");\n this.textures.push(this.diffuseTexture);\n this.defines.push(\"HAS_DIFFUSE_MAP 1\");\n this.properties.set(\"u_DiffuseUVSet\", this.diffuseTexture.texCoord);\n }\n\n if (this.specularGlossinessTexture !== undefined)\n {\n this.specularGlossinessTexture.samplerName = \"u_SpecularGlossinessSampler\";\n this.parseTextureInfoExtensions(this.specularGlossinessTexture, \"SpecularGlossiness\");\n this.textures.push(this.specularGlossinessTexture);\n this.defines.push(\"HAS_SPECULAR_GLOSSINESS_MAP 1\");\n this.properties.set(\"u_SpecularGlossinessUVSet\", this.specularGlossinessTexture.texCoord);\n }\n\n this.defines.push(\"ALPHAMODE_OPAQUE 0\");\n this.defines.push(\"ALPHAMODE_MASK 1\");\n this.defines.push(\"ALPHAMODE_BLEND 2\");\n if(this.alphaMode === 'MASK') // only set cutoff value for mask material\n {\n this.defines.push(\"ALPHAMODE ALPHAMODE_MASK\");\n this.properties.set(\"u_AlphaCutoff\", this.alphaCutoff);\n }\n else if (this.alphaMode === 'OPAQUE')\n {\n this.defines.push(\"ALPHAMODE ALPHAMODE_OPAQUE\");\n }\n else\n {\n this.defines.push(\"ALPHAMODE ALPHAMODE_BLEND\");\n }\n\n // if we have SG, we prefer SG (best practice) but if we have neither objects we use MR default values\n if(this.type !== \"SG\" )\n {\n this.defines.push(\"MATERIAL_METALLICROUGHNESS 1\");\n this.properties.set(\"u_BaseColorFactor\", vec4.fromValues(1, 1, 1, 1));\n this.properties.set(\"u_MetallicFactor\", 1);\n this.properties.set(\"u_RoughnessFactor\", 1);\n }\n\n if (this.pbrMetallicRoughness !== undefined && this.type !== \"SG\")\n {\n if (this.pbrMetallicRoughness.baseColorFactor !== undefined)\n {\n let baseColorFactor = jsToGl(this.pbrMetallicRoughness.baseColorFactor);\n this.properties.set(\"u_BaseColorFactor\", baseColorFactor);\n }\n\n if (this.pbrMetallicRoughness.metallicFactor !== undefined)\n {\n let metallicFactor = this.pbrMetallicRoughness.metallicFactor;\n this.properties.set(\"u_MetallicFactor\", metallicFactor);\n }\n\n if (this.pbrMetallicRoughness.roughnessFactor !== undefined)\n {\n let roughnessFactor = this.pbrMetallicRoughness.roughnessFactor;\n this.properties.set(\"u_RoughnessFactor\", roughnessFactor);\n }\n\n }\n\n if (this.extensions !== undefined)\n {\n if (this.extensions.KHR_materials_unlit !== undefined)\n {\n this.defines.push(\"MATERIAL_UNLIT 1\");\n }\n\n if (this.extensions.KHR_materials_pbrSpecularGlossiness !== undefined)\n {\n this.defines.push(\"MATERIAL_SPECULARGLOSSINESS 1\");\n\n let diffuseFactor = vec4.fromValues(1, 1, 1, 1);\n let specularFactor = vec3.fromValues(1, 1, 1);\n let glossinessFactor = 1;\n\n if (this.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor !== undefined)\n {\n diffuseFactor = jsToGl(this.extensions.KHR_materials_pbrSpecularGlossiness.diffuseFactor);\n }\n\n if (this.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor !== undefined)\n {\n specularFactor = jsToGl(this.extensions.KHR_materials_pbrSpecularGlossiness.specularFactor);\n }\n\n if (this.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor !== undefined)\n {\n glossinessFactor = this.extensions.KHR_materials_pbrSpecularGlossiness.glossinessFactor;\n }\n\n this.properties.set(\"u_DiffuseFactor\", diffuseFactor);\n this.properties.set(\"u_SpecularFactor\", specularFactor);\n this.properties.set(\"u_GlossinessFactor\", glossinessFactor);\n }\n\n // Clearcoat is part of the default metallic-roughness shader\n if(this.extensions.KHR_materials_clearcoat !== undefined)\n {\n let clearcoatFactor = 0.0;\n let clearcoatRoughnessFactor = 0.0;\n\n this.hasClearcoat = true;\n\n if(this.extensions.KHR_materials_clearcoat.clearcoatFactor !== undefined)\n {\n clearcoatFactor = this.extensions.KHR_materials_clearcoat.clearcoatFactor;\n }\n if(this.extensions.KHR_materials_clearcoat.clearcoatRoughnessFactor !== undefined)\n {\n clearcoatRoughnessFactor = this.extensions.KHR_materials_clearcoat.clearcoatRoughnessFactor;\n }\n\n if (this.clearcoatTexture !== undefined)\n {\n this.clearcoatTexture.samplerName = \"u_ClearcoatSampler\";\n this.parseTextureInfoExtensions(this.clearcoatTexture, \"Clearcoat\");\n this.textures.push(this.clearcoatTexture);\n this.defines.push(\"HAS_CLEARCOAT_MAP 1\");\n this.properties.set(\"u_ClearcoatUVSet\", this.clearcoatTexture.texCoord);\n }\n if (this.clearcoatRoughnessTexture !== undefined)\n {\n this.clearcoatRoughnessTexture.samplerName = \"u_ClearcoatRoughnessSampler\";\n this.parseTextureInfoExtensions(this.clearcoatRoughnessTexture, \"ClearcoatRoughness\");\n this.textures.push(this.clearcoatRoughnessTexture);\n this.defines.push(\"HAS_CLEARCOAT_ROUGHNESS_MAP 1\");\n this.properties.set(\"u_ClearcoatRoughnessUVSet\", this.clearcoatRoughnessTexture.texCoord);\n }\n if (this.clearcoatNormalTexture !== undefined)\n {\n this.clearcoatNormalTexture.samplerName = \"u_ClearcoatNormalSampler\";\n this.parseTextureInfoExtensions(this.clearcoatNormalTexture, \"ClearcoatNormal\");\n this.textures.push(this.clearcoatNormalTexture);\n this.defines.push(\"HAS_CLEARCOAT_NORMAL_MAP 1\");\n this.properties.set(\"u_ClearcoatNormalUVSet\", this.clearcoatNormalTexture.texCoord);\n this.properties.set(\"u_ClearcoatNormalScale\", this.clearcoatNormalTexture.scale);\n\n }\n this.properties.set(\"u_ClearcoatFactor\", clearcoatFactor);\n this.properties.set(\"u_ClearcoatRoughnessFactor\", clearcoatRoughnessFactor);\n }\n\n // Sheen material extension\n // https://github.com/sebavan/glTF/tree/KHR_materials_sheen/extensions/2.0/Khronos/KHR_materials_sheen\n if(this.extensions.KHR_materials_sheen !== undefined)\n {\n let sheenRoughnessFactor = 0.0;\n let sheenColorFactor = vec3.fromValues(1.0, 1.0, 1.0);\n\n this.hasSheen = true;\n\n if(this.extensions.KHR_materials_sheen.sheenRoughnessFactor !== undefined)\n {\n sheenRoughnessFactor = this.extensions.KHR_materials_sheen.sheenRoughnessFactor;\n }\n if(this.extensions.KHR_materials_sheen.sheenColorFactor !== undefined)\n {\n sheenColorFactor = jsToGl(this.extensions.KHR_materials_sheen.sheenColorFactor);\n }\n if (this.sheenRoughnessTexture !== undefined)\n {\n this.sheenRoughnessTexture.samplerName = \"u_SheenRoughnessSampler\";\n this.parseTextureInfoExtensions(this.sheenRoughnessTexture, \"SheenRoughness\");\n this.textures.push(this.sheenRoughnessTexture);\n this.defines.push(\"HAS_SHEEN_ROUGHNESS_MAP 1\");\n this.properties.set(\"u_SheenRoughnessUVSet\", this.sheenRoughnessTexture.texCoord);\n }\n if (this.sheenColorTexture !== undefined)\n {\n this.sheenColorTexture.samplerName = \"u_SheenColorSampler\";\n this.parseTextureInfoExtensions(this.sheenColorTexture, \"SheenColor\");\n this.sheenColorTexture.linear = false;\n this.textures.push(this.sheenColorTexture);\n this.defines.push(\"HAS_SHEEN_COLOR_MAP 1\");\n this.properties.set(\"u_SheenColorUVSet\", this.sheenColorTexture.texCoord);\n }\n\n this.properties.set(\"u_SheenRoughnessFactor\", sheenRoughnessFactor);\n this.properties.set(\"u_SheenColorFactor\", sheenColorFactor);\n }\n\n // KHR Extension: Specular\n if (this.extensions.KHR_materials_specular !== undefined)\n {\n this.hasSpecular = true;\n\n if (this.specularTexture !== undefined)\n {\n this.specularTexture.samplerName = \"u_SpecularSampler\";\n this.parseTextureInfoExtensions(this.specularTexture, \"Specular\");\n this.textures.push(this.specularTexture);\n this.defines.push(\"HAS_SPECULAR_MAP 1\");\n this.properties.set(\"u_SpecularUVSet\", this.specularTexture.texCoord);\n }\n\n if (this.specularColorTexture !== undefined)\n {\n this.specularColorTexture.samplerName = \"u_SpecularColorSampler\";\n this.parseTextureInfoExtensions(this.specularColorTexture, \"SpecularColor\");\n this.specularColorTexture.linear = false;\n this.textures.push(this.specularColorTexture);\n this.defines.push(\"HAS_SPECULAR_COLOR_MAP 1\");\n this.properties.set(\"u_SpecularColorUVSet\", this.specularColorTexture.texCoord);\n }\n\n let specularColorFactor = jsToGl(this.extensions.KHR_materials_specular.specularColorFactor ?? [1.0, 1.0, 1.0]);\n let specularFactor = this.extensions.KHR_materials_specular.specularFactor ?? 1.0;\n\n this.properties.set(\"u_KHR_materials_specular_specularColorFactor\", specularColorFactor);\n this.properties.set(\"u_KHR_materials_specular_specularFactor\", specularFactor);\n }\n\n // KHR Extension: Emissive strength\n if (this.extensions.KHR_materials_emissive_strength !== undefined)\n {\n this.hasEmissiveStrength = true;\n\n let emissiveStrength = this.extensions.KHR_materials_emissive_strength.emissiveStrength ?? 1.0;\n\n this.properties.set(\"u_EmissiveStrength\", emissiveStrength);\n }\n\n // KHR Extension: Transmission\n if (this.extensions.KHR_materials_transmission !== undefined)\n {\n let transmissionFactor = 0.0;\n\n this.hasTransmission = true;\n\n if (transmissionFactor !== undefined)\n {\n transmissionFactor = this.extensions.KHR_materials_transmission.transmissionFactor;\n }\n if (this.transmissionTexture !== undefined)\n {\n this.transmissionTexture.samplerName = \"u_TransmissionSampler\";\n this.parseTextureInfoExtensions(this.transmissionTexture, \"Transmission\");\n this.textures.push(this.transmissionTexture);\n this.defines.push(\"HAS_TRANSMISSION_MAP 1\");\n this.properties.set(\"u_TransmissionUVSet\", this.transmissionTexture.texCoord);\n }\n\n this.properties.set(\"u_TransmissionFactor\", transmissionFactor);\n }\n\n // KHR Extension: IOR\n //https://github.com/DassaultSystemes-Technology/glTF/tree/KHR_materials_ior/extensions/2.0/Khronos/KHR_materials_ior\n if (this.extensions.KHR_materials_ior !== undefined)\n {\n let ior = 1.5;\n\n this.hasIOR = true;\n \n if(this.extensions.KHR_materials_ior.ior !== undefined)\n {\n ior = this.extensions.KHR_materials_ior.ior;\n }\n\n this.properties.set(\"u_Ior\", ior);\n }\n\n // KHR Extension: Volume\n if (this.extensions.KHR_materials_volume !== undefined)\n {\n this.hasVolume = true;\n\n if (this.thicknessTexture !== undefined)\n {\n this.thicknessTexture.samplerName = \"u_ThicknessSampler\";\n this.parseTextureInfoExtensions(this.thicknessTexture, \"Thickness\");\n this.textures.push(this.thicknessTexture);\n this.defines.push(\"HAS_THICKNESS_MAP 1\");\n this.properties.set(\"u_ThicknessUVSet\", this.thicknessTexture.texCoord);\n }\n\n let attenuationColor = jsToGl(this.extensions.KHR_materials_volume.attenuationColor ?? [1.0, 1.0, 1.0]);\n let attenuationDistance = this.extensions.KHR_materials_volume.attenuationDistance ?? 0.0;\n let thicknessFactor = this.extensions.KHR_materials_volume.thicknessFactor ?? 0.0;\n\n this.properties.set(\"u_AttenuationColor\", attenuationColor);\n this.properties.set(\"u_AttenuationDistance\", attenuationDistance);\n this.properties.set(\"u_ThicknessFactor\", thicknessFactor);\n }\n\n // KHR Extension: Iridescence\n // See https://github.com/ux3d/glTF/tree/extensions/KHR_materials_iridescence/extensions/2.0/Khronos/KHR_materials_iridescence\n if(this.extensions.KHR_materials_iridescence !== undefined)\n {\n this.hasIridescence = true;\n\n let factor = this.extensions.KHR_materials_iridescence.iridescenceFactor;\n let iridescenceIor = this.extensions.KHR_materials_iridescence.iridescenceIor;\n let thicknessMinimum = this.extensions.KHR_materials_iridescence.iridescenceThicknessMinimum;\n let thicknessMaximum = this.extensions.KHR_materials_iridescence.iridescenceThicknessMaximum;\n\n if (factor === undefined)\n {\n factor = 0.0;\n }\n if (iridescenceIor === undefined)\n {\n iridescenceIor = 1.3;\n }\n if (thicknessMinimum === undefined)\n {\n thicknessMinimum = 100.0;\n }\n if (thicknessMaximum === undefined)\n {\n thicknessMaximum = 400.0;\n }\n\n if (this.iridescenceTexture !== undefined)\n {\n this.iridescenceTexture.samplerName = \"u_IridescenceSampler\";\n this.parseTextureInfoExtensions(this.iridescenceTexture, \"Iridescence\");\n this.textures.push(this.iridescenceTexture);\n this.defines.push(\"HAS_IRIDESCENCE_MAP 1\");\n this.properties.set(\"u_IridescenceUVSet\", this.iridescenceTexture.texCoord);\n }\n\n if (this.iridescenceThicknessTexture !== undefined)\n {\n this.iridescenceThicknessTexture.samplerName = \"u_IridescenceThicknessSampler\";\n this.parseTextureInfoExtensions(this.iridescenceThicknessTexture, \"IridescenceThickness\");\n this.textures.push(this.iridescenceThicknessTexture);\n this.defines.push(\"HAS_IRIDESCENCE_THICKNESS_MAP 1\");\n this.properties.set(\"u_IridescenceThicknessUVSet\", this.iridescenceThicknessTexture.texCoord);\n\n // The thickness minimum is only required when there is a thickness texture present.\n // Because 1.0 is the default value for the thickness, no texture implies that only the\n // maximum thickness is ever read in the shader.\n this.properties.set(\"u_IridescenceThicknessMinimum\", thicknessMinimum);\n }\n\n this.properties.set(\"u_IridescenceFactor\", factor);\n this.properties.set(\"u_IridescenceIor\", iridescenceIor);\n this.properties.set(\"u_IridescenceThicknessMaximum\", thicknessMaximum);\n }\n }\n\n initGlForMembers(this, gltf, webGlContext);\n }\n\n fromJson(jsonMaterial)\n {\n super.fromJson(jsonMaterial);\n\n if (jsonMaterial.emissiveFactor !== undefined)\n {\n this.emissiveFactor = jsToGl(jsonMaterial.emissiveFactor);\n }\n\n if (jsonMaterial.normalTexture !== undefined)\n {\n const normalTexture = new gltfTextureInfo();\n normalTexture.fromJson(jsonMaterial.normalTexture);\n this.normalTexture = normalTexture;\n }\n\n if (jsonMaterial.occlusionTexture !== undefined)\n {\n const occlusionTexture = new gltfTextureInfo();\n occlusionTexture.fromJson(jsonMaterial.occlusionTexture);\n this.occlusionTexture = occlusionTexture;\n }\n\n if (jsonMaterial.emissiveTexture !== undefined)\n {\n const emissiveTexture = new gltfTextureInfo(undefined, 0, false);\n emissiveTexture.fromJson(jsonMaterial.emissiveTexture);\n this.emissiveTexture = emissiveTexture;\n }\n\n if(jsonMaterial.extensions !== undefined)\n {\n this.fromJsonMaterialExtensions(jsonMaterial.extensions);\n }\n\n if (jsonMaterial.pbrMetallicRoughness !== undefined && this.type !== \"SG\")\n {\n this.type = \"MR\";\n this.fromJsonMetallicRoughness(jsonMaterial.pbrMetallicRoughness);\n }\n }\n\n fromJsonMaterialExtensions(jsonExtensions)\n {\n if (jsonExtensions.KHR_materials_pbrSpecularGlossiness !== undefined)\n {\n this.type = \"SG\";\n this.fromJsonSpecularGlossiness(jsonExtensions.KHR_materials_pbrSpecularGlossiness);\n }\n\n if(jsonExtensions.KHR_materials_unlit !== undefined)\n {\n this.type = \"unlit\";\n }\n\n if(jsonExtensions.KHR_materials_clearcoat !== undefined)\n {\n this.fromJsonClearcoat(jsonExtensions.KHR_materials_clearcoat);\n }\n\n if(jsonExtensions.KHR_materials_sheen !== undefined)\n {\n this.fromJsonSheen(jsonExtensions.KHR_materials_sheen);\n }\n\n if(jsonExtensions.KHR_materials_transmission !== undefined)\n {\n this.fromJsonTransmission(jsonExtensions.KHR_materials_transmission);\n }\n\n if(jsonExtensions.KHR_materials_specular !== undefined)\n {\n this.fromJsonSpecular(jsonExtensions.KHR_materials_specular);\n }\n\n if(jsonExtensions.KHR_materials_volume !== undefined)\n {\n this.fromJsonVolume(jsonExtensions.KHR_materials_volume);\n }\n\n if(jsonExtensions.KHR_materials_iridescence !== undefined)\n {\n this.fromJsonIridescence(jsonExtensions.KHR_materials_iridescence);\n }\n }\n\n fromJsonMetallicRoughness(jsonMetallicRoughness)\n {\n if (jsonMetallicRoughness.baseColorTexture !== undefined)\n {\n const baseColorTexture = new gltfTextureInfo(undefined, 0, false);\n baseColorTexture.fromJson(jsonMetallicRoughness.baseColorTexture);\n this.baseColorTexture = baseColorTexture;\n }\n\n if (jsonMetallicRoughness.metallicRoughnessTexture !== undefined)\n {\n const metallicRoughnessTexture = new gltfTextureInfo();\n metallicRoughnessTexture.fromJson(jsonMetallicRoughness.metallicRoughnessTexture);\n this.metallicRoughnessTexture = metallicRoughnessTexture;\n }\n }\n\n fromJsonSpecularGlossiness(jsonSpecularGlossiness)\n {\n if (jsonSpecularGlossiness.diffuseTexture !== undefined)\n {\n const diffuseTexture = new gltfTextureInfo(undefined, 0, false);\n diffuseTexture.fromJson(jsonSpecularGlossiness.diffuseTexture);\n this.diffuseTexture = diffuseTexture;\n }\n\n if (jsonSpecularGlossiness.specularGlossinessTexture !== undefined)\n {\n const specularGlossinessTexture = new gltfTextureInfo(undefined, 0, false);\n specularGlossinessTexture.fromJson(jsonSpecularGlossiness.specularGlossinessTexture);\n this.specularGlossinessTexture = specularGlossinessTexture;\n }\n }\n\n fromJsonClearcoat(jsonClearcoat)\n {\n if(jsonClearcoat.clearcoatTexture !== undefined)\n {\n const clearcoatTexture = new gltfTextureInfo();\n clearcoatTexture.fromJson(jsonClearcoat.clearcoatTexture);\n this.clearcoatTexture = clearcoatTexture;\n }\n\n if(jsonClearcoat.clearcoatRoughnessTexture !== undefined)\n {\n const clearcoatRoughnessTexture = new gltfTextureInfo();\n clearcoatRoughnessTexture.fromJson(jsonClearcoat.clearcoatRoughnessTexture);\n this.clearcoatRoughnessTexture = clearcoatRoughnessTexture;\n }\n\n if(jsonClearcoat.clearcoatNormalTexture !== undefined)\n {\n const clearcoatNormalTexture = new gltfTextureInfo();\n clearcoatNormalTexture.fromJson(jsonClearcoat.clearcoatNormalTexture);\n this.clearcoatNormalTexture = clearcoatNormalTexture;\n }\n }\n\n fromJsonSheen(jsonSheen)\n {\n if(jsonSheen.sheenColorTexture !== undefined)\n {\n const sheenColorTexture = new gltfTextureInfo(undefined, 0, false);\n sheenColorTexture.fromJson(jsonSheen.sheenColorTexture);\n this.sheenColorTexture = sheenColorTexture;\n }\n if(jsonSheen.sheenRoughnessTexture !== undefined)\n {\n const sheenRoughnessTexture = new gltfTextureInfo();\n sheenRoughnessTexture.fromJson(jsonSheen.sheenRoughnessTexture);\n this.sheenRoughnessTexture = sheenRoughnessTexture;\n }\n }\n\n fromJsonTransmission(jsonTransmission)\n {\n if(jsonTransmission.transmissionTexture !== undefined)\n {\n const transmissionTexture = new gltfTextureInfo();\n transmissionTexture.fromJson(jsonTransmission.transmissionTexture);\n this.transmissionTexture = transmissionTexture;\n }\n }\n\n fromJsonSpecular(jsonSpecular)\n {\n if(jsonSpecular.specularTexture !== undefined)\n {\n const specularTexture = new gltfTextureInfo();\n specularTexture.fromJson(jsonSpecular.specularTexture);\n this.specularTexture = specularTexture;\n }\n\n if(jsonSpecular.specularColorTexture !== undefined)\n {\n const specularColorTexture = new gltfTextureInfo();\n specularColorTexture.fromJson(jsonSpecular.specularColorTexture);\n this.specularColorTexture = specularColorTexture;\n }\n }\n\n fromJsonVolume(jsonVolume)\n {\n if(jsonVolume.thicknessTexture !== undefined)\n {\n const thicknessTexture = new gltfTextureInfo();\n thicknessTexture.fromJson(jsonVolume.thicknessTexture);\n this.thicknessTexture = thicknessTexture;\n }\n }\n\n fromJsonIridescence(jsonIridescence)\n {\n if(jsonIridescence.iridescenceTexture !== undefined)\n {\n const iridescenceTexture = new gltfTextureInfo();\n iridescenceTexture.fromJson(jsonIridescence.iridescenceTexture);\n this.iridescenceTexture = iridescenceTexture;\n }\n\n if(jsonIridescence.iridescenceThicknessTexture !== undefined)\n {\n const iridescenceThicknessTexture = new gltfTextureInfo();\n iridescenceThicknessTexture.fromJson(jsonIridescence.iridescenceThicknessTexture);\n this.iridescenceThicknessTexture = iridescenceThicknessTexture;\n }\n }\n}\n\nexport { gltfMaterial };\n","import { GltfObject } from './gltf_object.js';\nimport { GL } from '../Renderer/webgl.js';\n\nclass gltfSampler extends GltfObject\n{\n constructor(\n magFilter = GL.LINEAR,\n minFilter = GL.LINEAR_MIPMAP_LINEAR,\n wrapS = GL.REPEAT,\n wrapT = GL.REPEAT)\n {\n super();\n this.magFilter = magFilter;\n this.minFilter = minFilter;\n this.wrapS = wrapS;\n this.wrapT = wrapT;\n this.name = undefined;\n }\n\n static createDefault()\n {\n return new gltfSampler();\n }\n}\n\nexport { gltfSampler };\n","class DracoDecoder {\n\n constructor(dracoLib) {\n if (!DracoDecoder.instance && dracoLib === undefined)\n {\n if (DracoDecoderModule === undefined)\n {\n console.error('Failed to initalize DracoDecoder: draco library undefined');\n return undefined;\n }\n else\n {\n dracoLib = DracoDecoderModule;\n }\n }\n if (!DracoDecoder.instance)\n {\n DracoDecoder.instance = this;\n this.module = null;\n\n this.initializingPromise = new Promise(resolve => {\n let dracoDecoderType = {};\n dracoDecoderType['onModuleLoaded'] = dracoDecoderModule => {\n this.module = dracoDecoderModule;\n resolve();\n };\n dracoLib(dracoDecoderType);\n });\n }\n return DracoDecoder.instance;\n }\n\n async ready() {\n await this.initializingPromise;\n Object.freeze(DracoDecoder.instance);\n }\n\n}\n\nexport { DracoDecoder };\n","import { initGlForMembers } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\nimport { gltfBuffer } from './buffer.js';\nimport { gltfImage } from './image.js';\nimport { ImageMimeType } from './image_mime_type.js';\nimport { gltfTexture } from './texture.js';\nimport { gltfTextureInfo } from './texture.js';\nimport { gltfSampler } from './sampler.js';\nimport { gltfBufferView } from './buffer_view.js';\nimport { DracoDecoder } from '../ResourceLoader/draco.js';\nimport { GL } from '../Renderer/webgl.js';\n\nclass gltfPrimitive extends GltfObject\n{\n constructor()\n {\n super();\n this.attributes = [];\n this.targets = [];\n this.indices = undefined;\n this.material = undefined;\n this.mode = GL.TRIANGLES;\n\n // non gltf\n this.glAttributes = [];\n this.morphTargetTextureInfo = undefined;\n this.defines = [];\n this.skip = true;\n this.hasWeights = false;\n this.hasJoints = false;\n this.hasNormals = false;\n this.hasTangents = false;\n this.hasTexcoord = false;\n this.hasColor = false;\n\n // The primitive centroid is used for depth sorting.\n this.centroid = undefined;\n }\n\n initGl(gltf, webGlContext)\n {\n // Use the default glTF material.\n if (this.material === undefined)\n {\n this.material = gltf.materials.length - 1;\n }\n\n initGlForMembers(this, gltf, webGlContext);\n\n const maxAttributes = webGlContext.getParameter(GL.MAX_VERTEX_ATTRIBS);\n\n // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes\n\n if (this.extensions !== undefined)\n {\n if (this.extensions.KHR_draco_mesh_compression !== undefined)\n {\n const dracoDecoder = new DracoDecoder();\n if (dracoDecoder !== undefined && Object.isFrozen(dracoDecoder))\n {\n let dracoGeometry = this.decodeDracoBufferToIntermediate(\n this.extensions.KHR_draco_mesh_compression, gltf);\n this.copyDataFromDecodedGeometry(gltf, dracoGeometry, this.attributes);\n }\n else\n {\n console.warn('Failed to load draco compressed mesh: DracoDecoder not initialized');\n }\n }\n }\n\n // VERTEX ATTRIBUTES\n for (const attribute of Object.keys(this.attributes))\n {\n if(this.glAttributes.length >= maxAttributes)\n {\n console.error(\"To many vertex attributes for this primitive, skipping \" + attribute);\n break;\n }\n\n const idx = this.attributes[attribute];\n this.glAttributes.push({ attribute: attribute, name: \"a_\" + attribute.toLowerCase(), accessor: idx });\n this.defines.push(`HAS_${attribute}_${gltf.accessors[idx].type} 1`);\n switch (attribute)\n {\n case \"POSITION\":\n this.skip = false;\n break;\n case \"NORMAL\":\n this.hasNormals = true;\n break;\n case \"TANGENT\":\n this.hasTangents = true;\n break;\n case \"TEXCOORD_0\":\n this.hasTexcoord = true;\n break;\n case \"TEXCOORD_1\":\n this.hasTexcoord = true;\n break;\n case \"COLOR_0\":\n this.hasColor = true;\n break;\n case \"JOINTS_0\":\n this.hasJoints = true;\n break;\n case \"WEIGHTS_0\":\n this.hasWeights = true;\n break;\n case \"JOINTS_1\":\n this.hasJoints = true;\n break;\n case \"WEIGHTS_1\":\n this.hasWeights = true;\n break;\n default:\n console.log(\"Unknown attribute: \" + attribute);\n }\n }\n\n // MORPH TARGETS\n if (this.targets !== undefined && this.targets.length > 0)\n {\n const max2DTextureSize = Math.pow(webGlContext.getParameter(GL.MAX_TEXTURE_SIZE), 2);\n const maxTextureArraySize = webGlContext.getParameter(GL.MAX_ARRAY_TEXTURE_LAYERS);\n // Check which attributes are affected by morph targets and \n // define offsets for the attributes in the morph target texture.\n const attributeOffsets = {};\n let attributeOffset = 0;\n\n // Gather used attributes from all targets (some targets might\n // use more attributes than others)\n const attributes = Array.from(this.targets.reduce((acc, target) => {\n Object.keys(target).map(val => acc.add(val));\n return acc;\n }, new Set()));\n\n const vertexCount = gltf.accessors[this.attributes[attributes[0]]].count;\n this.defines.push(`NUM_VERTICIES ${vertexCount}`);\n let targetCount = this.targets.length;\n if (targetCount * attributes.length > maxTextureArraySize)\n {\n targetCount = Math.floor(maxTextureArraySize / attributes.length);\n console.warn(`Morph targets exceed texture size limit. Only ${targetCount} of ${this.targets.length} are used.`);\n }\n\n for (const attribute of attributes)\n {\n // Add morph target defines\n this.defines.push(`HAS_MORPH_TARGET_${attribute} 1`);\n this.defines.push(`MORPH_TARGET_${attribute}_OFFSET ${attributeOffset}`);\n // Store the attribute offset so that later the \n // morph target texture can be assembled.\n attributeOffsets[attribute] = attributeOffset;\n attributeOffset += targetCount;\n }\n this.defines.push(\"HAS_MORPH_TARGETS 1\");\n\n if (vertexCount <= max2DTextureSize) {\n // Allocate the texture buffer. Note that all target attributes must be vec3 types and\n // all must have the same vertex count as the primitives other attributes.\n const width = Math.ceil(Math.sqrt(vertexCount));\n const singleTextureSize = Math.pow(width, 2) * 4;\n const morphTargetTextureArray = new Float32Array(singleTextureSize * targetCount * attributes.length);\n\n // Now assemble the texture from the accessors.\n for (let i = 0; i < targetCount; ++i)\n {\n let target = this.targets[i];\n for (let [attributeName, offsetRef] of Object.entries(attributeOffsets)){\n if (target[attributeName] != undefined) {\n const accessor = gltf.accessors[target[attributeName]];\n const offset = offsetRef * singleTextureSize;\n if (accessor.componentType != GL.FLOAT && accessor.normalized == false){\n console.warn(\"Unsupported component type for morph targets\");\n attributeOffsets[attributeName] = offsetRef + 1;\n continue;\n }\n const data = accessor.getNormalizedDeinterlacedView(gltf);\n switch(accessor.type)\n {\n case \"VEC2\":\n case \"VEC3\":\n {\n // Add padding to fit vec2/vec3 into rgba\n let paddingOffset = 0;\n let accessorOffset = 0;\n const componentCount = accessor.getComponentCount(accessor.type);\n for (let j = 0; j < accessor.count; ++j) {\n morphTargetTextureArray.set(data.subarray(accessorOffset, accessorOffset + componentCount), offset + paddingOffset);\n paddingOffset += 4;\n accessorOffset += componentCount;\n }\n break;\n }\n case \"VEC4\":\n morphTargetTextureArray.set(data, offset);\n break;\n default:\n console.warn(\"Unsupported attribute type for morph targets\");\n break;\n }\n }\n attributeOffsets[attributeName] = offsetRef + 1;\n }\n }\n\n\n // Add the morph target texture.\n // We have to create a WebGL2 texture as the format of the\n // morph target texture has to be explicitly specified \n // (gltf image would assume uint8).\n let texture = webGlContext.createTexture();\n webGlContext.bindTexture( webGlContext.TEXTURE_2D_ARRAY, texture);\n // Set texture format and upload data.\n let internalFormat = webGlContext.RGBA32F;\n let format = webGlContext.RGBA;\n let type = webGlContext.FLOAT;\n let data = morphTargetTextureArray;\n webGlContext.texImage3D(\n webGlContext.TEXTURE_2D_ARRAY,\n 0, //level\n internalFormat,\n width,\n width,\n targetCount * attributes.length, //Layer count\n 0, //border\n format,\n type,\n data);\n // Ensure mipmapping is disabled and the sampler is configured correctly.\n webGlContext.texParameteri( GL.TEXTURE_2D_ARRAY, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE);\n webGlContext.texParameteri( GL.TEXTURE_2D_ARRAY, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE);\n webGlContext.texParameteri( GL.TEXTURE_2D_ARRAY, GL.TEXTURE_MIN_FILTER, GL.NEAREST);\n webGlContext.texParameteri( GL.TEXTURE_2D_ARRAY, GL.TEXTURE_MAG_FILTER, GL.NEAREST);\n \n // Now we add the morph target texture as a gltf texture info resource, so that \n // we can just call webGl.setTexture(..., gltfTextureInfo, ...) in the renderer.\n const morphTargetImage = new gltfImage(\n undefined, // uri\n GL.TEXTURE_2D_ARRAY, // type\n 0, // mip level\n undefined, // buffer view\n undefined, // name\n ImageMimeType.GLTEXTURE, // mimeType\n texture // image\n );\n gltf.images.push(morphTargetImage);\n\n gltf.samplers.push(new gltfSampler(GL.NEAREST, GL.NEAREST, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, undefined));\n\n const morphTargetTexture = new gltfTexture(\n gltf.samplers.length - 1,\n gltf.images.length - 1,\n GL.TEXTURE_2D_ARRAY);\n // The webgl texture is already initialized -> this flag informs\n // webgl.setTexture about this.\n morphTargetTexture.initialized = true;\n\n gltf.textures.push(morphTargetTexture);\n\n this.morphTargetTextureInfo = new gltfTextureInfo(gltf.textures.length - 1, 0, true);\n this.morphTargetTextureInfo.samplerName = \"u_MorphTargetsSampler\";\n this.morphTargetTextureInfo.generateMips = false;\n } else {\n console.warn(\"Mesh of Morph targets too big. Cannot apply morphing.\");\n } \n }\n\n this.computeCentroid(gltf);\n }\n\n computeCentroid(gltf)\n {\n const positionsAccessor = gltf.accessors[this.attributes.POSITION];\n const positions = positionsAccessor.getNormalizedTypedView(gltf);\n\n if(this.indices !== undefined)\n {\n // Primitive has indices.\n\n const indicesAccessor = gltf.accessors[this.indices];\n\n const indices = indicesAccessor.getTypedView(gltf);\n\n const acc = new Float32Array(3);\n\n for(let i = 0; i < indices.length; i++) {\n const offset = 3 * indices[i];\n acc[0] += positions[offset];\n acc[1] += positions[offset + 1];\n acc[2] += positions[offset + 2];\n }\n\n const centroid = new Float32Array([\n acc[0] / indices.length,\n acc[1] / indices.length,\n acc[2] / indices.length,\n ]);\n\n this.centroid = centroid;\n }\n else\n {\n // Primitive does not have indices.\n\n const acc = new Float32Array(3);\n\n for(let i = 0; i < positions.length; i += 3) {\n acc[0] += positions[i];\n acc[1] += positions[i + 1];\n acc[2] += positions[i + 2];\n }\n\n const positionVectors = positions.length / 3;\n\n const centroid = new Float32Array([\n acc[0] / positionVectors,\n acc[1] / positionVectors,\n acc[2] / positionVectors,\n ]);\n\n this.centroid = centroid;\n }\n }\n\n getShaderIdentifier()\n {\n return \"primitive.vert\";\n }\n\n getDefines()\n {\n return this.defines;\n }\n\n fromJson(jsonPrimitive)\n {\n super.fromJson(jsonPrimitive);\n\n if(jsonPrimitive.extensions !== undefined)\n {\n this.fromJsonPrimitiveExtensions(jsonPrimitive.extensions);\n }\n }\n\n fromJsonPrimitiveExtensions(jsonExtensions)\n {\n if(jsonExtensions.KHR_materials_variants !== undefined)\n {\n this.fromJsonVariants(jsonExtensions.KHR_materials_variants);\n }\n }\n\n fromJsonVariants(jsonVariants)\n {\n if(jsonVariants.mappings !== undefined)\n {\n this.mappings = jsonVariants.mappings;\n }\n }\n\n copyDataFromDecodedGeometry(gltf, dracoGeometry, primitiveAttributes)\n {\n // indices\n let indexBuffer = dracoGeometry.index.array;\n if (this.indices !== undefined){\n this.loadBufferIntoGltf(indexBuffer, gltf, this.indices, 34963,\n \"index buffer view\");\n }\n\n // Position\n if(dracoGeometry.attributes.POSITION !== undefined)\n {\n let positionBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.POSITION.array,\n dracoGeometry.attributes.POSITION.componentType);\n this.loadBufferIntoGltf(positionBuffer, gltf, primitiveAttributes[\"POSITION\"], 34962,\n \"position buffer view\");\n }\n\n // Normal\n if(dracoGeometry.attributes.NORMAL !== undefined)\n {\n let normalBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.NORMAL.array,\n dracoGeometry.attributes.NORMAL.componentType);\n this.loadBufferIntoGltf(normalBuffer, gltf, primitiveAttributes[\"NORMAL\"], 34962,\n \"normal buffer view\");\n }\n\n // TEXCOORD_0\n if(dracoGeometry.attributes.TEXCOORD_0 !== undefined)\n {\n let uvBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.TEXCOORD_0.array,\n dracoGeometry.attributes.TEXCOORD_0.componentType);\n this.loadBufferIntoGltf(uvBuffer, gltf, primitiveAttributes[\"TEXCOORD_0\"], 34962,\n \"TEXCOORD_0 buffer view\");\n }\n\n // TEXCOORD_1\n if(dracoGeometry.attributes.TEXCOORD_1 !== undefined)\n {\n let uvBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.TEXCOORD_1.array,\n dracoGeometry.attributes.TEXCOORD_1.componentType);\n this.loadBufferIntoGltf(uvBuffer, gltf, primitiveAttributes[\"TEXCOORD_1\"], 34962,\n \"TEXCOORD_1 buffer view\");\n }\n\n // Tangent\n if(dracoGeometry.attributes.TANGENT !== undefined)\n {\n let tangentBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.TANGENT.array,\n dracoGeometry.attributes.TANGENT.componentType);\n this.loadBufferIntoGltf(tangentBuffer, gltf, primitiveAttributes[\"TANGENT\"], 34962,\n \"Tangent buffer view\");\n }\n\n // Color\n if(dracoGeometry.attributes.COLOR_0 !== undefined)\n {\n let colorBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.COLOR_0.array,\n dracoGeometry.attributes.COLOR_0.componentType);\n this.loadBufferIntoGltf(colorBuffer, gltf, primitiveAttributes[\"COLOR_0\"], 34962,\n \"color buffer view\");\n }\n\n // JOINTS_0\n if(dracoGeometry.attributes.JOINTS_0 !== undefined)\n {\n let jointsBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.JOINTS_0.array,\n dracoGeometry.attributes.JOINTS_0.componentType);\n this.loadBufferIntoGltf(jointsBuffer, gltf, primitiveAttributes[\"JOINTS_0\"], 34963,\n \"JOINTS_0 buffer view\");\n }\n\n // WEIGHTS_0\n if(dracoGeometry.attributes.WEIGHTS_0 !== undefined)\n {\n let weightsBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.WEIGHTS_0.array,\n dracoGeometry.attributes.WEIGHTS_0.componentType);\n this.loadBufferIntoGltf(weightsBuffer, gltf, primitiveAttributes[\"WEIGHTS_0\"], 34963,\n \"WEIGHTS_0 buffer view\");\n }\n\n // JOINTS_1\n if(dracoGeometry.attributes.JOINTS_1 !== undefined)\n {\n let jointsBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.JOINTS_1.array,\n dracoGeometry.attributes.JOINTS_1.componentType);\n this.loadBufferIntoGltf(jointsBuffer, gltf, primitiveAttributes[\"JOINTS_1\"], 34963,\n \"JOINTS_1 buffer view\");\n }\n\n // WEIGHTS_1\n if(dracoGeometry.attributes.WEIGHTS_1 !== undefined)\n {\n let weightsBuffer = this.loadArrayIntoArrayBuffer(dracoGeometry.attributes.WEIGHTS_1.array,\n dracoGeometry.attributes.WEIGHTS_1.componentType);\n this.loadBufferIntoGltf(weightsBuffer, gltf, primitiveAttributes[\"WEIGHTS_1\"], 34963,\n \"WEIGHTS_1 buffer view\");\n }\n }\n\n loadBufferIntoGltf(buffer, gltf, gltfAccessorIndex, gltfBufferViewTarget, gltfBufferViewName)\n {\n const gltfBufferObj = new gltfBuffer();\n gltfBufferObj.byteLength = buffer.byteLength;\n gltfBufferObj.buffer = buffer;\n gltf.buffers.push(gltfBufferObj);\n\n const gltfBufferViewObj = new gltfBufferView();\n gltfBufferViewObj.buffer = gltf.buffers.length - 1;\n gltfBufferViewObj.byteLength = buffer.byteLength;\n if(gltfBufferViewName !== undefined)\n {\n gltfBufferViewObj.name = gltfBufferViewName;\n }\n gltfBufferViewObj.target = gltfBufferViewTarget;\n gltf.bufferViews.push(gltfBufferViewObj);\n\n gltf.accessors[gltfAccessorIndex].byteOffset = 0;\n gltf.accessors[gltfAccessorIndex].bufferView = gltf.bufferViews.length - 1;\n }\n\n loadArrayIntoArrayBuffer(arrayData, componentType)\n {\n let arrayBuffer;\n switch (componentType)\n {\n case \"Int8Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length);\n let int8Array = new Int8Array(arrayBuffer);\n int8Array.set(arrayData);\n break;\n case \"Uint8Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length);\n let uint8Array = new Uint8Array(arrayBuffer);\n uint8Array.set(arrayData);\n break;\n case \"Int16Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length * 2);\n let int16Array = new Int16Array(arrayBuffer);\n int16Array.set(arrayData);\n break;\n case \"Uint16Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length * 2);\n let uint16Array = new Uint16Array(arrayBuffer);\n uint16Array.set(arrayData);\n break;\n case \"Int32Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length * 4);\n let int32Array = new Int32Array(arrayBuffer);\n int32Array.set(arrayData);\n break;\n case \"Uint32Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length * 4);\n let uint32Array = new Uint32Array(arrayBuffer);\n uint32Array.set(arrayData);\n break;\n default:\n case \"Float32Array\":\n arrayBuffer = new ArrayBuffer(arrayData.length * 4);\n let floatArray = new Float32Array(arrayBuffer);\n floatArray.set(arrayData);\n break;\n }\n\n\n return arrayBuffer;\n }\n\n decodeDracoBufferToIntermediate(dracoExtension, gltf)\n {\n let dracoBufferViewIDX = dracoExtension.bufferView;\n\n const origGltfDrBufViewObj = gltf.bufferViews[dracoBufferViewIDX];\n const origGltfDracoBuffer = gltf.buffers[origGltfDrBufViewObj.buffer];\n\n const totalBuffer = new Int8Array( origGltfDracoBuffer.buffer );\n const actualBuffer = totalBuffer.slice(origGltfDrBufViewObj.byteOffset,\n origGltfDrBufViewObj.byteOffset + origGltfDrBufViewObj.byteLength);\n\n // decode draco buffer to geometry intermediate\n let dracoDecoder = new DracoDecoder();\n let draco = dracoDecoder.module;\n let decoder = new draco.Decoder();\n let decoderBuffer = new draco.DecoderBuffer();\n decoderBuffer.Init(actualBuffer, origGltfDrBufViewObj.byteLength);\n let geometry = this.decodeGeometry( draco, decoder, decoderBuffer, dracoExtension.attributes, gltf );\n\n draco.destroy( decoderBuffer );\n\n return geometry;\n }\n\n getDracoArrayTypeFromComponentType(componentType)\n {\n switch (componentType)\n {\n case GL.BYTE:\n return \"Int8Array\";\n case GL.UNSIGNED_BYTE:\n return \"Uint8Array\";\n case GL.SHORT:\n return \"Int16Array\";\n case GL.UNSIGNED_SHORT:\n return \"Uint16Array\";\n case GL.INT:\n return \"Int32Array\";\n case GL.UNSIGNED_INT:\n return \"Uint32Array\";\n case GL.FLOAT:\n return \"Float32Array\";\n default:\n return \"Float32Array\";\n }\n }\n\n decodeGeometry(draco, decoder, decoderBuffer, gltfDracoAttributes, gltf) {\n let dracoGeometry;\n let decodingStatus;\n\n // decode mesh in draco decoder\n let geometryType = decoder.GetEncodedGeometryType( decoderBuffer );\n if ( geometryType === draco.TRIANGULAR_MESH ) {\n dracoGeometry = new draco.Mesh();\n decodingStatus = decoder.DecodeBufferToMesh( decoderBuffer, dracoGeometry );\n }\n else\n {\n throw new Error( 'DRACOLoader: Unexpected geometry type.' );\n }\n\n if ( ! decodingStatus.ok() || dracoGeometry.ptr === 0 ) {\n throw new Error( 'DRACOLoader: Decoding failed: ' + decodingStatus.error_msg() );\n }\n\n let geometry = { index: null, attributes: {} };\n let vertexCount = dracoGeometry.num_points();\n\n // Gather all vertex attributes.\n for(let dracoAttr in gltfDracoAttributes)\n {\n let componentType = GL.BYTE;\n let accessotVertexCount;\n // find gltf accessor for this draco attribute\n for (const [key, value] of Object.entries(this.attributes))\n {\n if(key === dracoAttr)\n {\n componentType = gltf.accessors[value].componentType;\n accessotVertexCount = gltf.accessors[value].count;\n break;\n }\n }\n\n // check if vertex count matches\n if(vertexCount !== accessotVertexCount)\n {\n throw new Error(`DRACOLoader: Accessor vertex count ${accessotVertexCount} does not match draco decoder vertex count ${vertexCount}`);\n }\n componentType = this.getDracoArrayTypeFromComponentType(componentType);\n\n let dracoAttribute = decoder.GetAttributeByUniqueId( dracoGeometry, gltfDracoAttributes[dracoAttr]);\n var tmpObj = this.decodeAttribute( draco, decoder,\n dracoGeometry, dracoAttr, dracoAttribute, componentType);\n geometry.attributes[tmpObj.name] = tmpObj;\n }\n\n // Add index buffer\n if ( geometryType === draco.TRIANGULAR_MESH ) {\n\n // Generate mesh faces.\n let numFaces = dracoGeometry.num_faces();\n let numIndices = numFaces * 3;\n let dataSize = numIndices * 4;\n let ptr = draco._malloc( dataSize );\n decoder.GetTrianglesUInt32Array( dracoGeometry, dataSize, ptr );\n let index = new Uint32Array( draco.HEAPU32.buffer, ptr, numIndices ).slice();\n draco._free( ptr );\n\n geometry.index = { array: index, itemSize: 1 };\n\n }\n\n draco.destroy( dracoGeometry );\n return geometry;\n }\n\n decodeAttribute( draco, decoder, dracoGeometry, attributeName, attribute, attributeType) {\n let numComponents = attribute.num_components();\n let numPoints = dracoGeometry.num_points();\n let numValues = numPoints * numComponents;\n\n let ptr;\n let array;\n\n let dataSize;\n switch ( attributeType ) {\n case \"Float32Array\":\n dataSize = numValues * 4;\n ptr = draco._malloc( dataSize );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_FLOAT32, dataSize, ptr );\n array = new Float32Array( draco.HEAPF32.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Int8Array\":\n ptr = draco._malloc( numValues );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_INT8, numValues, ptr );\n array = new Int8Array( draco.HEAP8.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Int16Array\":\n dataSize = numValues * 2;\n ptr = draco._malloc( dataSize );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_INT16, dataSize, ptr );\n array = new Int16Array( draco.HEAP16.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Int32Array\":\n dataSize = numValues * 4;\n ptr = draco._malloc( dataSize );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_INT32, dataSize, ptr );\n array = new Int32Array( draco.HEAP32.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Uint8Array\":\n ptr = draco._malloc( numValues );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_UINT8, numValues, ptr );\n array = new Uint8Array( draco.HEAPU8.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Uint16Array\":\n dataSize = numValues * 2;\n ptr = draco._malloc( dataSize );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_UINT16, dataSize, ptr );\n array = new Uint16Array( draco.HEAPU16.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n case \"Uint32Array\":\n dataSize = numValues * 4;\n ptr = draco._malloc( dataSize );\n decoder.GetAttributeDataArrayForAllPoints( dracoGeometry, attribute, draco.DT_UINT32, dataSize, ptr );\n array = new Uint32Array( draco.HEAPU32.buffer, ptr, numValues ).slice();\n draco._free( ptr );\n break;\n\n default:\n throw new Error( 'DRACOLoader: Unexpected attribute type.' );\n }\n\n return {\n name: attributeName,\n array: array,\n itemSize: numComponents,\n componentType: attributeType\n };\n\n }\n}\n\nexport { gltfPrimitive };\n\n","import { gltfPrimitive } from './primitive.js';\nimport { objectsFromJsons } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\nclass gltfMesh extends GltfObject\n{\n constructor()\n {\n super();\n this.primitives = [];\n this.name = undefined;\n this.weights = [];\n\n // non gltf\n this.weightsAnimated = undefined;\n }\n\n fromJson(jsonMesh)\n {\n super.fromJson(jsonMesh);\n\n if (jsonMesh.name !== undefined)\n {\n this.name = jsonMesh.name;\n }\n\n this.primitives = objectsFromJsons(jsonMesh.primitives, gltfPrimitive);\n\n if(jsonMesh.weights !== undefined)\n {\n this.weights = jsonMesh.weights;\n }\n }\n\n getWeightsAnimated()\n {\n return this.weightsAnimated !== undefined ? this.weightsAnimated : this.weights;\n }\n}\n\nexport { gltfMesh };\n","import { mat4, quat } from 'gl-matrix';\nimport { jsToGl } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\n\n// contain:\n// transform\n// child indices (reference to scene array of nodes)\n\nclass gltfNode extends GltfObject\n{\n constructor()\n {\n super();\n this.camera = undefined;\n this.children = [];\n this.matrix = undefined;\n this.rotation = jsToGl([0, 0, 0, 1]);\n this.scale = jsToGl([1, 1, 1]);\n this.translation = jsToGl([0, 0, 0]);\n this.name = undefined;\n this.mesh = undefined;\n this.skin = undefined;\n\n // non gltf\n this.worldTransform = mat4.create();\n this.inverseWorldTransform = mat4.create();\n this.normalMatrix = mat4.create();\n this.light = undefined;\n this.changed = true;\n\n this.animationRotation = undefined;\n this.animationTranslation = undefined;\n this.animationScale = undefined;\n }\n\n initGl()\n {\n if (this.matrix !== undefined)\n {\n this.applyMatrix(this.matrix);\n }\n else\n {\n if (this.scale !== undefined)\n {\n this.scale = jsToGl(this.scale);\n }\n\n if (this.rotation !== undefined)\n {\n this.rotation = jsToGl(this.rotation);\n }\n\n if (this.translation !== undefined)\n {\n this.translation = jsToGl(this.translation);\n }\n }\n this.changed = true;\n }\n\n applyMatrix(matrixData)\n {\n this.matrix = jsToGl(matrixData);\n\n mat4.getScaling(this.scale, this.matrix);\n\n // To extract a correct rotation, the scaling component must be eliminated.\n const mn = mat4.create();\n for(const col of [0, 1, 2])\n {\n mn[col] = this.matrix[col] / this.scale[0];\n mn[col + 4] = this.matrix[col + 4] / this.scale[1];\n mn[col + 8] = this.matrix[col + 8] / this.scale[2];\n }\n mat4.getRotation(this.rotation, mn);\n quat.normalize(this.rotation, this.rotation);\n\n mat4.getTranslation(this.translation, this.matrix);\n\n this.changed = true;\n }\n\n // vec3\n applyTranslationAnimation(translation)\n {\n this.animationTranslation = translation;\n this.changed = true;\n }\n\n // quat\n applyRotationAnimation(rotation)\n {\n this.animationRotation = rotation;\n this.changed = true;\n }\n\n // vec3\n applyScaleAnimation(scale)\n {\n this.animationScale = scale;\n this.changed = true;\n }\n\n resetTransform()\n {\n this.rotation = jsToGl([0, 0, 0, 1]);\n this.scale = jsToGl([1, 1, 1]);\n this.translation = jsToGl([0, 0, 0]);\n this.changed = true;\n }\n\n getLocalTransform()\n {\n if(this.transform === undefined || this.changed)\n {\n // if no animation is applied and the transform matrix is present use it directly\n if(this.animationTranslation === undefined && this.animationRotation === undefined && this.animationScale === undefined && this.matrix !== undefined) {\n this.transform = mat4.clone(this.matrix);\n } else {\n this.transform = mat4.create();\n const translation = this.animationTranslation !== undefined ? this.animationTranslation : this.translation;\n const rotation = this.animationRotation !== undefined ? this.animationRotation : this.rotation;\n const scale = this.animationScale !== undefined ? this.animationScale : this.scale;\n mat4.fromRotationTranslationScale(this.transform, rotation, translation, scale);\n }\n this.changed = false;\n }\n\n return mat4.clone(this.transform);\n }\n}\n\nexport { gltfNode };\n","import { mat4 } from 'gl-matrix';\nimport { GltfObject } from './gltf_object';\n\nclass gltfScene extends GltfObject\n{\n constructor(nodes = [], name = undefined)\n {\n super();\n this.nodes = nodes;\n this.name = name;\n\n // non gltf\n this.imageBasedLight = undefined;\n }\n\n initGl(gltf, webGlContext)\n {\n super.initGl(gltf, webGlContext);\n\n if (this.extensions !== undefined &&\n this.extensions.KHR_lights_image_based !== undefined)\n {\n const index = this.extensions.KHR_lights_image_based.imageBasedLight;\n this.imageBasedLight = gltf.imageBasedLights[index];\n }\n }\n\n applyTransformHierarchy(gltf, rootTransform = mat4.create())\n {\n function applyTransform(gltf, node, parentTransform)\n {\n mat4.multiply(node.worldTransform, parentTransform, node.getLocalTransform());\n mat4.invert(node.inverseWorldTransform, node.worldTransform);\n mat4.transpose(node.normalMatrix, node.inverseWorldTransform);\n\n for (const child of node.children)\n {\n applyTransform(gltf, gltf.nodes[child], node.worldTransform);\n }\n }\n\n for (const node of this.nodes)\n {\n applyTransform(gltf, gltf.nodes[node], rootTransform);\n }\n }\n\n gatherNodes(gltf)\n {\n const nodes = [];\n\n function gatherNode(nodeIndex)\n {\n const node = gltf.nodes[nodeIndex];\n nodes.push(node);\n\n // recurse into children\n for(const child of node.children)\n {\n gatherNode(child);\n }\n }\n\n for (const node of this.nodes)\n {\n gatherNode(node);\n }\n\n return nodes;\n }\n\n includesNode(gltf, nodeIndex)\n {\n let children = [...this.nodes];\n while(children.length > 0)\n {\n const childIndex = children.pop();\n\n if (childIndex === nodeIndex)\n {\n return true;\n }\n\n children = children.concat(gltf.nodes[childIndex].children);\n }\n\n return false;\n }\n}\n\nexport { gltfScene };\n","import { GltfObject } from \"./gltf_object\";\n\nclass gltfAsset extends GltfObject\n{\n constructor()\n {\n super();\n this.copyright = undefined;\n this.generator = undefined;\n this.version = undefined;\n this.minVersion = undefined;\n }\n}\n\nexport { gltfAsset as gltfAsset };\n","import { GltfObject } from './gltf_object.js';\n\nclass gltfAnimationChannel extends GltfObject\n{\n constructor()\n {\n super();\n this.target = {node: undefined, path: undefined};\n this.sampler = undefined;\n }\n}\n\nconst InterpolationPath =\n{\n TRANSLATION: \"translation\",\n ROTATION: \"rotation\",\n SCALE: \"scale\",\n WEIGHTS: \"weights\"\n};\n\nexport { gltfAnimationChannel, InterpolationPath };\n","import { GltfObject } from './gltf_object.js';\n\nclass gltfAnimationSampler extends GltfObject\n{\n constructor()\n {\n super();\n this.input = undefined;\n this.interpolation = undefined;\n this.output = undefined;\n }\n}\n\nconst InterpolationModes =\n{\n LINEAR: \"LINEAR\",\n STEP: \"STEP\",\n CUBICSPLINE: \"CUBICSPLINE\"\n};\n\nexport { gltfAnimationSampler, InterpolationModes };\n","import { InterpolationModes } from './animation_sampler.js';\nimport { InterpolationPath } from './channel.js';\nimport { clamp, jsToGlSlice } from './utils.js';\nimport { quat, glMatrix } from 'gl-matrix';\n\nclass gltfInterpolator\n{\n constructor()\n {\n this.prevKey = 0;\n this.prevT = 0.0;\n }\n\n slerpQuat(q1, q2, t)\n {\n const qn1 = quat.create();\n const qn2 = quat.create();\n\n quat.normalize(qn1, q1);\n quat.normalize(qn2, q2);\n\n const quatResult = quat.create();\n\n quat.slerp(quatResult, qn1, qn2, t);\n quat.normalize(quatResult, quatResult);\n\n return quatResult;\n }\n\n step(prevKey, output, stride)\n {\n const result = new glMatrix.ARRAY_TYPE(stride);\n\n for(let i = 0; i < stride; ++i)\n {\n result[i] = output[prevKey * stride + i];\n }\n\n return result;\n }\n\n linear(prevKey, nextKey, output, t, stride)\n {\n const result = new glMatrix.ARRAY_TYPE(stride);\n\n for(let i = 0; i < stride; ++i)\n {\n result[i] = output[prevKey * stride + i] * (1-t) + output[nextKey * stride + i] * t;\n }\n\n return result;\n }\n\n cubicSpline(prevKey, nextKey, output, keyDelta, t, stride)\n {\n // stride: Count of components (4 in a quaternion).\n // Scale by 3, because each output entry consist of two tangents and one data-point.\n const prevIndex = prevKey * stride * 3;\n const nextIndex = nextKey * stride * 3;\n const A = 0;\n const V = 1 * stride;\n const B = 2 * stride;\n\n const result = new glMatrix.ARRAY_TYPE(stride);\n const tSq = t ** 2;\n const tCub = t ** 3;\n\n // We assume that the components in output are laid out like this: in-tangent, point, out-tangent.\n // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#appendix-c-spline-interpolation\n for(let i = 0; i < stride; ++i)\n {\n const v0 = output[prevIndex + i + V];\n const a = keyDelta * output[nextIndex + i + A];\n const b = keyDelta * output[prevIndex + i + B];\n const v1 = output[nextIndex + i + V];\n\n result[i] = ((2*tCub - 3*tSq + 1) * v0) + ((tCub - 2*tSq + t) * b) + ((-2*tCub + 3*tSq) * v1) + ((tCub - tSq) * a);\n }\n\n return result;\n }\n\n resetKey()\n {\n this.prevKey = 0;\n }\n\n interpolate(gltf, channel, sampler, t, stride, maxTime)\n {\n if(t === undefined)\n {\n return undefined;\n }\n\n const input = gltf.accessors[sampler.input].getNormalizedDeinterlacedView(gltf);\n const output = gltf.accessors[sampler.output].getNormalizedDeinterlacedView(gltf);\n\n if(output.length === stride) // no interpolation for single keyFrame animations\n {\n return jsToGlSlice(output, 0, stride);\n }\n\n // Wrap t around, so the animation loops.\n // Make sure that t is never earlier than the first keyframe and never later then the last keyframe.\n t = t % maxTime;\n t = clamp(t, input[0], input[input.length - 1]);\n\n if (this.prevT > t)\n {\n this.prevKey = 0;\n }\n\n this.prevT = t;\n\n // Find next keyframe: min{ t of input | t > prevKey }\n let nextKey = null;\n for (let i = this.prevKey; i < input.length; ++i)\n {\n if (t <= input[i])\n {\n nextKey = clamp(i, 1, input.length - 1);\n break;\n }\n }\n this.prevKey = clamp(nextKey - 1, 0, nextKey);\n\n const keyDelta = input[nextKey] - input[this.prevKey];\n\n // Normalize t: [t0, t1] -> [0, 1]\n const tn = (t - input[this.prevKey]) / keyDelta;\n\n if(channel.target.path === InterpolationPath.ROTATION)\n {\n\n if(InterpolationModes.CUBICSPLINE === sampler.interpolation)\n {\n // GLTF requires cubic spline interpolation for quaternions.\n // https://github.com/KhronosGroup/glTF/issues/1386\n const result = this.cubicSpline(this.prevKey, nextKey, output, keyDelta, tn, 4);\n quat.normalize(result, result);\n return result;\n }\n else if(sampler.interpolation === InterpolationModes.LINEAR)\n {\n const q0 = this.getQuat(output, this.prevKey);\n const q1 = this.getQuat(output, nextKey);\n return this.slerpQuat(q0, q1, tn);\n }\n else if(sampler.interpolation === InterpolationModes.STEP)\n {\n return this.getQuat(output, this.prevKey);\n }\n\n }\n\n switch(sampler.interpolation)\n {\n case InterpolationModes.STEP:\n return this.step(this.prevKey, output, stride);\n case InterpolationModes.CUBICSPLINE:\n return this.cubicSpline(this.prevKey, nextKey, output, keyDelta, tn, stride);\n default:\n return this.linear(this.prevKey, nextKey, output, tn, stride);\n }\n }\n\n getQuat(output, index)\n {\n const x = output[4 * index];\n const y = output[4 * index + 1];\n const z = output[4 * index + 2];\n const w = output[4 * index + 3];\n return quat.fromValues(x, y, z, w);\n }\n}\n\nexport { gltfInterpolator };\n","import { GltfObject } from './gltf_object.js';\nimport { objectsFromJsons } from './utils.js';\nimport { gltfAnimationChannel, InterpolationPath } from './channel.js';\nimport { gltfAnimationSampler } from './animation_sampler.js';\nimport { gltfInterpolator } from './interpolator.js';\n\nclass gltfAnimation extends GltfObject\n{\n constructor()\n {\n super();\n this.channels = [];\n this.samplers = [];\n this.name = '';\n\n // not gltf\n this.interpolators = [];\n this.maxTime = 0;\n this.disjointAnimations = [];\n }\n\n fromJson(jsonAnimation)\n {\n super.fromJson(jsonAnimation);\n\n this.channels = objectsFromJsons(jsonAnimation.channels, gltfAnimationChannel);\n this.samplers = objectsFromJsons(jsonAnimation.samplers, gltfAnimationSampler);\n this.name = jsonAnimation.name;\n\n if(this.channels === undefined)\n {\n console.error(\"No channel data found for skin\");\n return;\n }\n\n for(let i = 0; i < this.channels.length; ++i)\n {\n this.interpolators.push(new gltfInterpolator());\n }\n }\n\n // advance the animation, if totalTime is undefined, the animation is deactivated\n advance(gltf, totalTime)\n {\n if(this.channels === undefined)\n {\n return;\n }\n\n if(this.maxTime == 0)\n {\n for(let i = 0; i < this.channels.length; ++i)\n {\n const channel = this.channels[i];\n const sampler = this.samplers[channel.sampler];\n const input = gltf.accessors[sampler.input].getDeinterlacedView(gltf);\n const max = input[input.length - 1];\n if(max > this.maxTime)\n {\n this.maxTime = max;\n }\n }\n }\n\n for(let i = 0; i < this.interpolators.length; ++i)\n {\n const channel = this.channels[i];\n const sampler = this.samplers[channel.sampler];\n const interpolator = this.interpolators[i];\n\n const node = gltf.nodes[channel.target.node];\n\n switch(channel.target.path)\n {\n case InterpolationPath.TRANSLATION:\n node.applyTranslationAnimation(interpolator.interpolate(gltf, channel, sampler, totalTime, 3, this.maxTime));\n break;\n case InterpolationPath.ROTATION:\n node.applyRotationAnimation(interpolator.interpolate(gltf, channel, sampler, totalTime, 4, this.maxTime));\n break;\n case InterpolationPath.SCALE:\n node.applyScaleAnimation(interpolator.interpolate(gltf, channel, sampler, totalTime, 3, this.maxTime));\n break;\n case InterpolationPath.WEIGHTS:\n {\n const mesh = gltf.meshes[node.mesh];\n mesh.weightsAnimated = interpolator.interpolate(gltf, channel, sampler, totalTime, mesh.weights.length, this.maxTime);\n break;\n }\n }\n }\n }\n}\n\nexport { gltfAnimation };\n","import { jsToGlSlice } from './utils.js';\nimport { GltfObject } from './gltf_object.js';\nimport { mat4 } from 'gl-matrix';\nimport { GL } from '../Renderer/webgl.js';\nimport { gltfImage } from './image.js';\nimport { ImageMimeType } from './image_mime_type.js';\nimport { gltfTexture } from './texture.js';\nimport { gltfTextureInfo } from './texture.js';\nimport { gltfSampler } from './sampler.js';\n\nclass gltfSkin extends GltfObject\n{\n constructor()\n {\n super();\n\n this.name = \"\";\n this.inverseBindMatrices = undefined;\n this.joints = [];\n this.skeleton = undefined;\n\n // not gltf\n this.jointTextureInfo = undefined;\n this.jointWebGlTexture = undefined;\n }\n\n initGl(gltf, webGlContext)\n {\n this.jointWebGlTexture = webGlContext.createTexture();\n webGlContext.bindTexture( webGlContext.TEXTURE_2D, this.jointWebGlTexture);\n\n // Ensure mipmapping is disabled and the sampler is configured correctly.\n webGlContext.texParameteri( GL.TEXTURE_2D, GL.TEXTURE_WRAP_S, GL.CLAMP_TO_EDGE);\n webGlContext.texParameteri( GL.TEXTURE_2D, GL.TEXTURE_WRAP_T, GL.CLAMP_TO_EDGE);\n webGlContext.texParameteri( GL.TEXTURE_2D, GL.TEXTURE_WRAP_R, GL.CLAMP_TO_EDGE);\n webGlContext.texParameteri( GL.TEXTURE_2D, GL.TEXTURE_MIN_FILTER, GL.NEAREST);\n webGlContext.texParameteri( GL.TEXTURE_2D, GL.TEXTURE_MAG_FILTER, GL.NEAREST);\n \n // Now we add the joints texture as a gltf texture info resource, so that \n // we can just call webGl.setTexture(..., gltfTextureInfo, ...) in the renderer.\n const jointsImage = new gltfImage(\n undefined, // uri\n GL.TEXTURE_2D, // type\n 0, // mip level\n undefined, // buffer view\n undefined, // name\n ImageMimeType.GLTEXTURE, // mimeType\n this.jointWebGlTexture // image\n );\n gltf.images.push(jointsImage);\n\n gltf.samplers.push(new gltfSampler(GL.NEAREST, GL.NEAREST, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, undefined));\n\n const jointsTexture = new gltfTexture(\n gltf.samplers.length - 1,\n gltf.images.length - 1,\n GL.TEXTURE_2D);\n // The webgl texture is already initialized -> this flag informs\n // webgl.setTexture about this.\n jointsTexture.initialized = true;\n\n gltf.textures.push(jointsTexture);\n\n this.jointTextureInfo = new gltfTextureInfo(gltf.textures.length - 1, 0, true);\n this.jointTextureInfo.samplerName = \"u_jointsSampler\";\n this.jointTextureInfo.generateMips = false;\n }\n\n computeJoints(gltf, parentNode, webGlContext)\n {\n let ibmAccessor = null;\n if (this.inverseBindMatrices !== undefined) {\n ibmAccessor = gltf.accessors[this.inverseBindMatrices].getDeinterlacedView(gltf);\n }\n\n this.jointMatrices = [];\n this.jointNormalMatrices = [];\n\n const width = Math.ceil(Math.sqrt(this.joints.length * 8));\n let textureData = new Float32Array(Math.pow(width, 2) * 4);\n\n let i = 0;\n for(const joint of this.joints)\n {\n const node = gltf.nodes[joint];\n\n let jointMatrix = mat4.clone(node.worldTransform);\n\n if (ibmAccessor !== null) {\n let ibm = jsToGlSlice(ibmAccessor, i * 16, 16);\n mat4.mul(jointMatrix, jointMatrix, ibm);\n mat4.mul(jointMatrix, parentNode.inverseWorldTransform, jointMatrix);\n }\n\n let normalMatrix = mat4.create();\n mat4.invert(normalMatrix, jointMatrix);\n mat4.transpose(normalMatrix, normalMatrix);\n \n textureData.set(jointMatrix, i * 32);\n textureData.set(normalMatrix, i * 32 + 16);\n ++i;\n }\n\n webGlContext.bindTexture( webGlContext.TEXTURE_2D, this.jointWebGlTexture);\n // Set texture format and upload data.\n let internalFormat = webGlContext.RGBA32F;\n let format = webGlContext.RGBA;\n let type = webGlContext.FLOAT;\n let data = textureData;\n webGlContext.texImage2D(\n webGlContext.TEXTURE_2D,\n 0, //level\n internalFormat,\n width,\n width,\n 0, //border\n format,\n type,\n data);\n }\n}\n\nexport { gltfSkin };\n","import { GltfObject } from './gltf_object.js';\n\nclass gltfVariant extends GltfObject\n{\n constructor()\n {\n super();\n this.name = undefined;\n }\n\n fromJson(jsonVariant)\n {\n if(jsonVariant.name !== undefined)\n {\n this.name = jsonVariant.name;\n }\n }\n}\n\nexport { gltfVariant as gltfVariant };\n","import { gltfAccessor } from './accessor.js';\nimport { gltfBuffer } from './buffer.js';\nimport { gltfBufferView } from './buffer_view.js';\nimport { gltfCamera } from './camera.js';\nimport { gltfImage } from './image.js';\nimport { gltfLight } from './light.js';\nimport { ImageBasedLight } from './image_based_light.js';\nimport { gltfMaterial } from './material.js';\nimport { gltfMesh } from './mesh.js';\nimport { gltfNode } from './node.js';\nimport { gltfSampler } from './sampler.js';\nimport { gltfScene } from './scene.js';\nimport { gltfTexture } from './texture.js';\nimport { initGlForMembers, objectsFromJsons, objectFromJson } from './utils';\nimport { gltfAsset } from './asset.js';\nimport { GltfObject } from './gltf_object.js';\nimport { gltfAnimation } from './animation.js';\nimport { gltfSkin } from './skin.js';\nimport { gltfVariant } from './variant.js';\n\nclass glTF extends GltfObject\n{\n constructor(file)\n {\n super();\n this.asset = undefined;\n this.accessors = [];\n this.nodes = [];\n this.scene = undefined; // the default scene to show.\n this.scenes = [];\n this.cameras = [];\n this.lights = [];\n this.imageBasedLights = [];\n this.textures = [];\n this.images = [];\n this.samplers = [];\n this.meshes = [];\n this.buffers = [];\n this.bufferViews = [];\n this.materials = [];\n this.animations = [];\n this.skins = [];\n this.path = file;\n }\n\n initGl(webGlContext)\n {\n initGlForMembers(this, this, webGlContext);\n }\n\n fromJson(json, customProperties = {})\n {\n super.fromJson(json);\n\n this.asset = objectFromJson(customProperties.asset ? customProperties.asset : json.asset, gltfAsset);\n this.cameras = objectsFromJsons(customProperties.cameras ? customProperties.cameras : json.cameras, gltfCamera);\n this.accessors = objectsFromJsons(customProperties.accessors ? customProperties.accessors : json.accessors, gltfAccessor);\n this.meshes = objectsFromJsons(customProperties.meshes ? customProperties.meshes : json.meshes, gltfMesh);\n this.samplers = objectsFromJsons(customProperties.samplers ? customProperties.samplers : json.samplers, gltfSampler);\n this.materials = objectsFromJsons(customProperties.materials ? customProperties.materials : json.materials, gltfMaterial);\n this.buffers = objectsFromJsons(customProperties.buffers ? customProperties.buffers : json.buffers, gltfBuffer);\n this.bufferViews = objectsFromJsons(customProperties.bufferViews ? customProperties.bufferViews : json.bufferViews, gltfBufferView);\n this.scenes = objectsFromJsons(customProperties.scenes ? customProperties.scenes : json.scenes, gltfScene);\n this.textures = objectsFromJsons(customProperties.textures ? customProperties.textures : json.textures, gltfTexture);\n this.nodes = objectsFromJsons(customProperties.nodes ? customProperties.nodes : json.nodes, gltfNode);\n this.lights = objectsFromJsons(getJsonLightsFromExtensions(customProperties.extensions ? customProperties.extensions : json.extensions), gltfLight);\n this.imageBasedLights = objectsFromJsons(getJsonIBLsFromExtensions(customProperties.extensions ? customProperties.extensions : json.extensions), ImageBasedLight);\n this.images = objectsFromJsons(customProperties.images ? customProperties.images : json.images, gltfImage);\n this.animations = objectsFromJsons(customProperties.animations ? customProperties.animations : json.animations, gltfAnimation);\n this.skins = objectsFromJsons(customProperties.skins ? customProperties.skins : json.skins, gltfSkin);\n this.variants = objectsFromJsons(getJsonVariantsFromExtension(customProperties.extensions ? customProperties.extensions : json.extensions), gltfVariant);\n this.variants = enforceVariantsUniqueness(this.variants);\n\n this.materials.push(gltfMaterial.createDefault());\n this.samplers.push(gltfSampler.createDefault());\n\n if (json.scenes !== undefined)\n {\n if (json.scene === undefined && json.scenes.length > 0)\n {\n this.scene = 0;\n }\n else\n {\n this.scene = json.scene;\n }\n }\n\n this.computeDisjointAnimations();\n }\n\n // Computes indices of animations which are disjoint and can be played simultaneously.\n computeDisjointAnimations()\n {\n for (let i = 0; i < this.animations.length; i++)\n {\n this.animations[i].disjointAnimations = [];\n\n for (let k = 0; k < this.animations.length; k++)\n {\n if (i == k)\n {\n continue;\n }\n\n let isDisjoint = true;\n\n for (const iChannel of this.animations[i].channels)\n {\n for (const kChannel of this.animations[k].channels)\n {\n if (iChannel.target.node === kChannel.target.node\n && iChannel.target.path === kChannel.target.path)\n {\n isDisjoint = false;\n break;\n }\n }\n }\n\n if (isDisjoint)\n {\n this.animations[i].disjointAnimations.push(k);\n }\n }\n }\n }\n\n nonDisjointAnimations(animationIndices)\n {\n const animations = this.animations;\n const nonDisjointAnimations = [];\n\n for (let i = 0; i < animations.length; i++)\n {\n let isDisjoint = true;\n for (const k of animationIndices)\n {\n if (i == k)\n {\n continue;\n }\n\n if (!animations[k].disjointAnimations.includes(i))\n {\n isDisjoint = false;\n }\n }\n\n if (!isDisjoint)\n {\n nonDisjointAnimations.push(i);\n }\n }\n\n return nonDisjointAnimations;\n }\n}\n\nfunction getJsonLightsFromExtensions(extensions)\n{\n if (extensions === undefined)\n {\n return [];\n }\n if (extensions.KHR_lights_punctual === undefined)\n {\n return [];\n }\n return extensions.KHR_lights_punctual.lights;\n}\n\nfunction getJsonIBLsFromExtensions(extensions)\n{\n if (extensions === undefined)\n {\n return [];\n }\n if (extensions.KHR_lights_image_based === undefined)\n {\n return [];\n }\n return extensions.KHR_lights_image_based.imageBasedLights;\n}\n\nfunction getJsonVariantsFromExtension(extensions)\n{\n if (extensions === undefined)\n {\n return [];\n }\n if (extensions.KHR_materials_variants === undefined)\n {\n return [];\n }\n return extensions.KHR_materials_variants.variants;\n}\n\nfunction enforceVariantsUniqueness(variants)\n{\n for(let i=0;i gltf.initGl(webGlContext));\n }\n\n static unload(gltf)\n {\n for (let image of gltf.images)\n {\n image.image = undefined;\n }\n gltf.images = [];\n\n for (let texture of gltf.textures)\n {\n texture.destroy();\n }\n gltf.textures = [];\n\n for (let accessor of gltf.accessors)\n {\n accessor.destroy();\n }\n gltf.accessors = [];\n }\n\n static getBuffers(appendix)\n {\n return gltfLoader.getTypedAppendix(appendix, ArrayBuffer);\n }\n\n static getAdditionalFiles(appendix)\n {\n if(typeof(File) !== 'undefined')\n {\n return gltfLoader.getTypedAppendix(appendix, File);\n }\n else\n {\n return;\n }\n }\n\n static getTypedAppendix(appendix, Type)\n {\n if (appendix && appendix.length > 0)\n {\n if (appendix[0] instanceof Type)\n {\n return appendix;\n }\n }\n }\n\n static loadBuffers(gltf, buffers, additionalFiles)\n {\n const promises = [];\n\n if (buffers !== undefined && buffers[0] !== undefined) //GLB\n {\n //There is only one buffer for the glb binary data \n //see https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#glb-file-format-specification\n if (buffers.length > 1)\n {\n console.warn(\"Too many buffer chunks in GLB file. Only one or zero allowed\");\n }\n\n gltf.buffers[0].buffer = buffers[0];\n for (let i = 1; i < gltf.buffers.length; ++i)\n {\n promises.push(gltf.buffers[i].load(gltf, additionalFiles));\n }\n }\n else\n {\n for (const buffer of gltf.buffers)\n {\n promises.push(buffer.load(gltf, additionalFiles));\n }\n }\n return Promise.all(promises);\n }\n\n static loadImages(gltf, additionalFiles)\n {\n const imagePromises = [];\n for (let image of gltf.images)\n {\n imagePromises.push(image.load(gltf, additionalFiles));\n }\n return Promise.all(imagePromises);\n }\n}\n\nexport { gltfLoader };\n","import { ShaderCache } from './Renderer/shader_cache.js';\nimport iblFiltering from './shaders/ibl_filtering.frag';\nimport panoramaToCubeMap from './shaders/panorama_to_cubemap.frag';\nimport debugOutput from './shaders/debug.frag';\nimport fullscreenShader from './shaders/fullscreen.vert';\n\nclass iblSampler\n{\n constructor(view)\n {\n this.gl = view.context;\n\n this.textureSize = 256;\n this.ggxSampleCount = 1024;\n this.lambertianSampleCount = 2048;\n this.sheenSamplCount = 64;\n this.lodBias = 0.0;\n this.lowestMipLevel = 4;\n this.lutResolution = 1024;\n\n this.mipmapCount = undefined;\n\n this.lambertianTextureID = undefined;\n this.ggxTextureID = undefined;\n this.sheenTextureID = undefined;\n\n this.ggxLutTextureID = undefined;\n this.charlieLutTextureID = undefined;\n\n this.inputTextureID = undefined;\n this.cubemapTextureID = undefined;\n this.framebuffer = undefined;\n\n const shaderSources = new Map();\n\n shaderSources.set(\"fullscreen.vert\", fullscreenShader);\n shaderSources.set(\"panorama_to_cubemap.frag\", panoramaToCubeMap);\n shaderSources.set(\"ibl_filtering.frag\", iblFiltering);\n shaderSources.set(\"debug.frag\", debugOutput);\n\n this.shaderCache = new ShaderCache(shaderSources, view.renderer.webGl);\n }\n\n loadTextureHDR(image)\n {\n const texture = this.gl.createTexture();\n this.gl.bindTexture(this.gl.TEXTURE_2D, texture);\n\n let internalFormat = this.gl.RGB32F;\n let format = this.gl.RGB;\n let type = this.gl.FLOAT;\n let data = undefined;\n\n if (image.dataFloat instanceof Float32Array && typeof(this.gl.RGB32F) !== 'undefined')\n {\n internalFormat = this.gl.RGB32F;\n format = this.gl.RGB;\n type = this.gl.FLOAT;\n data = image.dataFloat;\n }\n else if (image.dataFloat instanceof Float32Array)\n {\n // workaround for node-gles not supporting RGB32F\n internalFormat = this.gl.RGBA32F;\n format = this.gl.RGBA;\n type = this.gl.FLOAT;\n\n const numPixels = image.dataFloat.length / 3;\n data = new Float32Array(numPixels * 4);\n for(let i = 0, src = 0, dst = 0; i < numPixels; ++i, src += 3, dst += 4)\n {\n // copy the pixels and pad the alpha channel\n data[dst] = image.dataFloat[src];\n data[dst+1] = image.dataFloat[src+1];\n data[dst+2] = image.dataFloat[src+2];\n data[dst+3] = 0;\n }\n }\n else if (typeof(Image) !== 'undefined' && image instanceof Image)\n {\n internalFormat = this.gl.RGBA;\n format = this.gl.RGBA;\n type = this.gl.UNSIGNED_BYTE;\n data = image;\n }\n else\n {\n console.error(\"loadTextureHDR failed, unsupported HDR image\");\n return;\n }\n\n this.gl.texImage2D(\n this.gl.TEXTURE_2D,\n 0,\n internalFormat,\n image.width,\n image.height,\n 0,\n format,\n type,\n data\n );\n\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.MIRRORED_REPEAT);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.MIRRORED_REPEAT);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);\n\n return texture;\n }\n\n internalFormat()\n {\n return this.use8bit ? this.gl.RGBA8 : this.gl.RGBA32F;\n }\n\n type()\n {\n return this.use8bit ? this.gl.UNSIGNED_BYTE : this.gl.FLOAT;\n }\n\n createCubemapTexture(withMipmaps)\n {\n const targetTexture = this.gl.createTexture();\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, targetTexture);\n\n for(let i = 0; i < 6; ++i)\n {\n this.gl.texImage2D(\n this.gl.TEXTURE_CUBE_MAP_POSITIVE_X + i,\n 0,\n this.internalFormat(),\n this.textureSize,\n this.textureSize,\n 0,\n this.gl.RGBA,\n this.type(),\n null\n );\n }\n\n if(withMipmaps)\n {\n this.gl.texParameteri(this.gl.TEXTURE_CUBE_MAP, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR_MIPMAP_LINEAR);\n }\n else\n {\n this.gl.texParameteri(this.gl.TEXTURE_CUBE_MAP, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);\n }\n\n this.gl.texParameteri(this.gl.TEXTURE_CUBE_MAP, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);\n this.gl.texParameteri(this.gl.TEXTURE_CUBE_MAP, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);\n this.gl.texParameteri(this.gl.TEXTURE_CUBE_MAP, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);\n\n return targetTexture;\n }\n\n createLutTexture()\n {\n const targetTexture = this.gl.createTexture();\n this.gl.bindTexture(this.gl.TEXTURE_2D, targetTexture);\n\n this.gl.texImage2D(\n this.gl.TEXTURE_2D,\n 0,\n this.internalFormat(),\n this.lutResolution,\n this.lutResolution,\n 0,\n this.gl.RGBA,\n this.type(),\n null\n );\n\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE);\n this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE);\n\n return targetTexture;\n }\n\n init(panoramaImage)\n {\n if (!this.gl.getExtension(\"EXT_color_buffer_float\") || !this.gl.getExtension(\"OES_texture_float_linear\"))\n {\n console.warn(\"Floating point textures are not supported\");\n this.use8bit = true;\n }\n\n this.inputTextureID = this.loadTextureHDR(panoramaImage);\n\n this.cubemapTextureID = this.createCubemapTexture(true);\n\n this.framebuffer = this.gl.createFramebuffer();\n\n this.lambertianTextureID = this.createCubemapTexture(false);\n this.ggxTextureID = this.createCubemapTexture(true);\n this.sheenTextureID = this.createCubemapTexture(true);\n\n\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.ggxTextureID);\n this.gl.generateMipmap(this.gl.TEXTURE_CUBE_MAP);\n\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.sheenTextureID);\n this.gl.generateMipmap(this.gl.TEXTURE_CUBE_MAP);\n\n this.mipmapLevels = Math.floor(Math.log2(this.textureSize))+1 - this.lowestMipLevel;\n }\n\n filterAll()\n {\n this.panoramaToCubeMap();\n this.cubeMapToLambertian();\n this.cubeMapToGGX();\n this.cubeMapToSheen();\n\n this.sampleGGXLut();\n this.sampleCharlieLut();\n\n this.gl.bindFramebuffer( this.gl.FRAMEBUFFER, null);\n }\n\n panoramaToCubeMap()\n {\n for(let i = 0; i < 6; ++i)\n {\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.framebuffer);\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, this.cubemapTextureID, 0);\n\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.cubemapTextureID);\n\n this.gl.viewport(0, 0, this.textureSize, this.textureSize);\n\n this.gl.clearColor(1.0, 0.0, 0.0, 0.0);\n this.gl.clear(this.gl.COLOR_BUFFER_BIT| this.gl.DEPTH_BUFFER_BIT);\n\n const vertexHash = this.shaderCache.selectShader(\"fullscreen.vert\", []);\n const fragmentHash = this.shaderCache.selectShader(\"panorama_to_cubemap.frag\", []);\n\n const shader = this.shaderCache.getShaderProgram(fragmentHash, vertexHash);\n this.gl.useProgram(shader.program);\n\n // TEXTURE0 = active.\n this.gl.activeTexture(this.gl.TEXTURE0+0);\n\n // Bind texture ID to active texture\n this.gl.bindTexture(this.gl.TEXTURE_2D, this.inputTextureID);\n\n // map shader uniform to texture unit (TEXTURE0)\n const location = this.gl.getUniformLocation(shader.program,\"u_panorama\");\n this.gl.uniform1i(location, 0); // texture unit 0 (TEXTURE0)\n\n shader.updateUniform(\"u_currentFace\", i);\n\n //fullscreen triangle\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 3);\n }\n\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.cubemapTextureID);\n this.gl.generateMipmap(this.gl.TEXTURE_CUBE_MAP);\n\n }\n\n\n applyFilter(\n distribution,\n roughness,\n targetMipLevel,\n targetTexture,\n sampleCount,\n lodBias = 0.0)\n {\n const currentTextureSize = this.textureSize >> targetMipLevel;\n\n for(let i = 0; i < 6; ++i)\n {\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.framebuffer);\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, targetTexture, targetMipLevel);\n\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, targetTexture);\n\n this.gl.viewport(0, 0, currentTextureSize, currentTextureSize);\n\n this.gl.clearColor(1.0, 0.0, 0.0, 0.0);\n this.gl.clear(this.gl.COLOR_BUFFER_BIT| this.gl.DEPTH_BUFFER_BIT);\n\n const vertexHash = this.shaderCache.selectShader(\"fullscreen.vert\", []);\n const fragmentHash = this.shaderCache.selectShader(\"ibl_filtering.frag\", []);\n\n const shader = this.shaderCache.getShaderProgram(fragmentHash, vertexHash);\n this.gl.useProgram(shader.program);\n\n // TEXTURE0 = active.\n this.gl.activeTexture(this.gl.TEXTURE0);\n\n // Bind texture ID to active texture\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.cubemapTextureID);\n\n // map shader uniform to texture unit (TEXTURE0)\n const location = this.gl.getUniformLocation(shader.program,\"u_cubemapTexture\");\n this.gl.uniform1i(location, 0); // texture unit 0\n\n shader.updateUniform(\"u_roughness\", roughness);\n shader.updateUniform(\"u_sampleCount\", sampleCount);\n shader.updateUniform(\"u_width\", this.textureSize);\n shader.updateUniform(\"u_lodBias\", lodBias);\n shader.updateUniform(\"u_distribution\", distribution);\n shader.updateUniform(\"u_currentFace\", i);\n shader.updateUniform(\"u_isGeneratingLUT\", 0);\n\n //fullscreen triangle\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 3);\n }\n\n }\n\n cubeMapToLambertian()\n {\n this.applyFilter(\n 0,\n 0.0,\n 0,\n this.lambertianTextureID,\n this.lambertianSampleCount);\n }\n\n\n cubeMapToGGX()\n {\n for(let currentMipLevel = 0; currentMipLevel <= this.mipmapLevels; ++currentMipLevel)\n {\n const roughness = (currentMipLevel) / (this.mipmapLevels - 1);\n this.applyFilter(\n 1,\n roughness,\n currentMipLevel,\n this.ggxTextureID,\n this.ggxSampleCount);\n }\n }\n\n cubeMapToSheen()\n {\n for(let currentMipLevel = 0; currentMipLevel <= this.mipmapLevels; ++currentMipLevel)\n {\n const roughness = (currentMipLevel) / (this.mipmapLevels - 1);\n this.applyFilter(\n 2,\n roughness,\n currentMipLevel,\n this.sheenTextureID,\n this.sheenSamplCount);\n }\n }\n\n sampleLut(distribution, targetTexture, currentTextureSize)\n {\n this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.framebuffer);\n this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_2D, targetTexture, 0);\n\n this.gl.bindTexture(this.gl.TEXTURE_2D, targetTexture);\n\n this.gl.viewport(0, 0, currentTextureSize, currentTextureSize);\n\n this.gl.clearColor(1.0, 0.0, 0.0, 0.0);\n this.gl.clear(this.gl.COLOR_BUFFER_BIT| this.gl.DEPTH_BUFFER_BIT);\n\n const vertexHash = this.shaderCache.selectShader(\"fullscreen.vert\", []);\n const fragmentHash = this.shaderCache.selectShader(\"ibl_filtering.frag\", []);\n\n const shader = this.shaderCache.getShaderProgram(fragmentHash, vertexHash);\n this.gl.useProgram(shader.program);\n\n\n // TEXTURE0 = active.\n this.gl.activeTexture(this.gl.TEXTURE0+0);\n\n // Bind texture ID to active texture\n this.gl.bindTexture(this.gl.TEXTURE_CUBE_MAP, this.cubemapTextureID);\n\n // map shader uniform to texture unit (TEXTURE0)\n const location = this.gl.getUniformLocation(shader.program,\"u_cubemapTexture\");\n this.gl.uniform1i(location, 0); // texture unit 0\n\n\n shader.updateUniform(\"u_roughness\", 0.0);\n shader.updateUniform(\"u_sampleCount\", 512);\n shader.updateUniform(\"u_width\", 0.0);\n shader.updateUniform(\"u_lodBias\", 0.0);\n shader.updateUniform(\"u_distribution\", distribution);\n shader.updateUniform(\"u_currentFace\", 0);\n shader.updateUniform(\"u_isGeneratingLUT\", 1);\n\n //fullscreen triangle\n this.gl.drawArrays(this.gl.TRIANGLES, 0, 3);\n }\n\n sampleGGXLut()\n {\n this.ggxLutTextureID = this.createLutTexture();\n this.sampleLut(1, this.ggxLutTextureID, this.lutResolution);\n }\n\n sampleCharlieLut()\n {\n this.charlieLutTextureID = this.createLutTexture();\n this.sampleLut(2, this.charlieLutTextureID, this.lutResolution);\n }\n\n destroy()\n {\n this.shaderCache.destroy();\n }\n}\n\nexport { iblSampler };\n","class KtxDecoder {\n\n constructor (context, externalKtxlib) {\n this.gl = context;\n this.libktx = null;\n if (context !== undefined)\n {\n if (externalKtxlib === undefined && LIBKTX !== undefined)\n {\n externalKtxlib = LIBKTX;\n }\n if (externalKtxlib !== undefined)\n {\n this.initializied = this.init(context, externalKtxlib);\n }\n else\n {\n console.error('Failed to initalize KTXDecoder: ktx library undefined');\n return undefined;\n }\n }\n else\n {\n console.error('Failed to initalize KTXDecoder: WebGL context undefined');\n return undefined;\n }\n }\n\n async init(context, externalKtxlib) {\n this.libktx = await externalKtxlib({preinitializedWebGLContext: context});\n this.libktx.GL.makeContextCurrent(this.libktx.GL.createContext(null, { majorVersion: 2.0, antialias: true }));\n }\n\n transcode(ktexture) {\n if (ktexture.needsTranscoding) {\n let format;\n\n let astcSupported = false;\n let etcSupported = false;\n let dxtSupported = false;\n let bptcSupported = false;\n let pvrtcSupported = false;\n\n astcSupported = !!this.gl.getExtension('WEBGL_compressed_texture_astc');\n etcSupported = !!this.gl.getExtension('WEBGL_compressed_texture_etc1');\n dxtSupported = !!this.gl.getExtension('WEBGL_compressed_texture_s3tc');\n bptcSupported = !!this.gl.getExtension('EXT_texture_compression_bptc');\n\n pvrtcSupported = !!(this.gl.getExtension('WEBGL_compressed_texture_pvrtc')) || !!(this.gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'));\n\n if (astcSupported) {\n format = this.libktx.TranscodeTarget.ASTC_4x4_RGBA;\n } else if (bptcSupported) {\n format = this.libktx.TranscodeTarget.BC7_RGBA;\n } else if (dxtSupported) {\n format = this.libktx.TranscodeTarget.BC1_OR_3;\n } else if (pvrtcSupported) {\n format = this.libktx.TranscodeTarget.PVRTC1_4_RGBA;\n } else if (etcSupported) {\n format = this.libktx.TranscodeTarget.ETC;\n } else {\n format = this.libktx.TranscodeTarget.RGBA8888;\n }\n if (ktexture.transcodeBasis(format, 0) != this.libktx.ErrorCode.SUCCESS) {\n console.warn('Texture transcode failed. See console for details.');\n }\n }\n }\n\n async loadKtxFromUri(uri) {\n await this.initializied;\n const response = await fetch(uri);\n const data = new Uint8Array(await response.arrayBuffer());\n const texture = new this.libktx.ktxTexture(data);\n this.transcode(texture);\n let uploadResult = texture.glUpload();\n if (uploadResult.texture == null)\n {\n console.error(\"Could not load KTX data\");\n return undefined;\n }\n uploadResult.texture.levels = Math.log2(texture.baseWidth);\n return uploadResult.texture;\n }\n\n async loadKtxFromBuffer(data) {\n await this.initializied;\n const texture = new this.libktx.ktxTexture(data);\n this.transcode(texture);\n const uploadResult = texture.glUpload();\n if (uploadResult.texture == null)\n {\n console.error(\"Could not load KTX data\");\n return undefined;\n }\n return uploadResult.texture;\n }\n}\n\nexport { KtxDecoder };\n","/**\n * hdrpng.js - Original code from Enki https://enkimute.github.io/hdrpng.js/\n *\n * Refactored and simplified.\n */\n\nimport { gltfImage } from \"../gltf/image\";\n\nfunction _rgbeToFloat(buffer)\n{\n const length = buffer.byteLength >> 2;\n const result = new Float32Array(length * 3);\n\n for (let i = 0; i < length; i++)\n {\n const s = Math.pow(2, buffer[i * 4 + 3] - (128 + 8));\n\n result[i * 3] = buffer[i * 4] * s;\n result[i * 3 + 1] = buffer[i * 4 + 1] * s;\n result[i * 3 + 2] = buffer[i * 4 + 2] * s;\n }\n return result;\n}\n\nasync function loadHDR(buffer)\n{\n let header = '';\n let pos = 0;\n const d8 = buffer;\n let format = undefined;\n // read header.\n while (!header.match(/\\n\\n[^\\n]+\\n/g)) header += String.fromCharCode(d8[pos++]);\n // check format.\n format = header.match(/FORMAT=(.*)$/m);\n if (format.length < 2)\n {\n return undefined;\n }\n format = format[1];\n if (format != '32-bit_rle_rgbe') return console.warn('unknown format : ' + format), this.onerror();\n // parse resolution\n let rez = header.split(/\\n/).reverse();\n if (rez.length < 2)\n {\n return undefined;\n }\n rez = rez[1].split(' ');\n if (rez.length < 4)\n {\n return undefined;\n }\n const width = rez[3] * 1, height = rez[1] * 1;\n // Create image.\n const img = new Uint8Array(width * height * 4);\n let ipos = 0;\n // Read all scanlines\n for (let j = 0; j < height; j++)\n {\n const scanline = [];\n\n let rgbe = d8.slice(pos, pos += 4);\n const isNewRLE = (rgbe[0] == 2 && rgbe[1] == 2 && rgbe[2] == ((width >> 8) & 0xFF) && rgbe[3] == (width & 0xFF));\n\n if (isNewRLE && (width >= 8) && (width < 32768))\n {\n for (let i = 0; i < 4; i++)\n {\n let ptr = i * width;\n const ptr_end = (i + 1) * width;\n let buf = undefined;\n let count = undefined;\n while (ptr < ptr_end)\n {\n buf = d8.slice(pos, pos += 2);\n if (buf[0] > 128)\n {\n count = buf[0] - 128;\n while (count-- > 0) scanline[ptr++] = buf[1];\n }\n else\n {\n count = buf[0] - 1;\n scanline[ptr++] = buf[1];\n while (count-- > 0) scanline[ptr++] = d8[pos++];\n }\n }\n }\n\n for (let i = 0; i < width; i++)\n {\n img[ipos++] = scanline[i + 0 * width];\n img[ipos++] = scanline[i + 1 * width];\n img[ipos++] = scanline[i + 2 * width];\n img[ipos++] = scanline[i + 3 * width];\n }\n }\n else\n {\n pos -= 4;\n\n for (let i = 0; i < width; i++)\n {\n rgbe = d8.slice(pos, pos += 4);\n\n img[ipos++] = rgbe[0];\n img[ipos++] = rgbe[1];\n img[ipos++] = rgbe[2];\n img[ipos++] = rgbe[3];\n }\n }\n }\n\n const imageFloatBuffer = _rgbeToFloat(img);\n\n return {\n dataFloat: imageFloatBuffer,\n width: width,\n height: height\n };\n}\n\nexport { loadHDR };\n","\nimport axios from 'axios';\nimport {glTF, gltfMaterial} from '../gltf/gltf.js';\nimport {getIsGlb, getContainingFolder, objectsFromJsons} from '../gltf/utils.js';\nimport { GlbParser } from './glb_parser.js';\nimport { gltfLoader } from \"./loader.js\";\nimport { gltfImage, ImageMimeType } from \"../gltf/image.js\";\nimport { gltfTexture, gltfTextureInfo } from '../gltf/texture.js';\nimport { gltfSampler } from '../gltf/sampler.js';\nimport { GL } from '../Renderer/webgl.js';\nimport { iblSampler } from '../ibl_sampler.js';\n\n\nimport { AsyncFileReader } from './async_file_reader.js';\n\nimport { DracoDecoder } from './draco.js';\nimport { KtxDecoder } from './ktx.js';\n\nimport { loadHDR } from '../libs/hdrpng.js';\n\n/**\n * ResourceLoader can be used to load resources for the GltfState\n * that are then used to display the loaded data with GltfView\n */\nclass ResourceLoader\n{\n /**\n * ResourceLoader class that provides an interface to load resources into\n * the view. Typically this is created with GltfView.createResourceLoader()\n * You cannot share resource loaders between GltfViews as some of the resources\n * are allocated directly on the WebGl2 Context\n * @param {Object} view the GltfView for which the resources are loaded\n */\n constructor(view)\n {\n this.view = view;\n }\n\n /**\n * loadGltf asynchroneously and create resources for rendering\n * @param {(String | ArrayBuffer | File)} gltfFile the .gltf or .glb file either as path or as preloaded resource. In node.js environments, only ArrayBuffer types are accepted.\n * @param {File[]} [externalFiles] additional files containing resources that are referenced in the gltf\n * @returns {Promise} a promise that fulfills when the gltf file was loaded\n */\n async loadGltf(gltfFile, externalFiles, customProperties = {})\n {\n let isGlb = undefined;\n let buffers = undefined;\n let json = undefined;\n let data = undefined;\n let filename = \"\";\n\n if (typeof gltfFile === \"string\")\n {\n isGlb = getIsGlb(gltfFile);\n let response = await axios.get(gltfFile, { responseType: isGlb ? \"arraybuffer\" : \"json\" });\n json = response.data;\n data = response.data;\n filename = gltfFile;\n }\n else if (gltfFile instanceof ArrayBuffer)\n {\n isGlb = externalFiles === undefined;\n if (isGlb)\n {\n data = gltfFile;\n }\n else\n {\n console.error(\"Only .glb files can be loaded from an array buffer\");\n }\n }\n else if (typeof (File) !== 'undefined' && gltfFile instanceof File)\n {\n let fileContent = gltfFile;\n filename = gltfFile.name;\n isGlb = getIsGlb(filename);\n if (isGlb)\n {\n data = await AsyncFileReader.readAsArrayBuffer(fileContent);\n }\n else\n {\n data = await AsyncFileReader.readAsText(fileContent);\n json = JSON.parse(data);\n buffers = externalFiles;\n }\n }\n else\n {\n console.error(\"Passed invalid type to loadGltf \" + typeof (gltfFile));\n }\n\n if (isGlb)\n {\n const glbParser = new GlbParser(data);\n const glb = glbParser.extractGlbData();\n json = glb.json;\n buffers = glb.buffers;\n }\n\n const gltf = new glTF(filename);\n gltf.ktxDecoder = this.view.ktxDecoder;\n //Make sure draco decoder instance is ready\n gltf.fromJson(json, customProperties);\n\n // because the gltf image paths are not relative\n // to the gltf, we have to resolve all image paths before that\n for (const image of gltf.images)\n {\n image.resolveRelativePath(getContainingFolder(gltf.path));\n }\n\n await gltfLoader.load(gltf, this.view.context, buffers);\n\n return gltf;\n }\n\n /**\n * loadEnvironment asynchroneously, run IBL sampling and create resources for rendering\n * @param {(String | ArrayBuffer | File)} environmentFile the .hdr file either as path or resource\n * @param {Object} [lutFiles] object containing paths or resources for the environment look up textures. Keys are lut_ggx_file, lut_charlie_file and lut_sheen_E_file\n * @returns {Promise} a promise that fulfills when the environment file was loaded\n */\n async loadEnvironment(environmentFile, lutFiles)\n {\n let image = undefined;\n if (typeof environmentFile === \"string\")\n {\n let response = await axios.get(environmentFile, { responseType: \"arraybuffer\" });\n\n image = await loadHDR(new Uint8Array(response.data));\n }\n else if (environmentFile instanceof ArrayBuffer)\n {\n image = await loadHDR(new Uint8Array(environmentFile));\n }\n else if (typeof (File) !== 'undefined' && environmentFile instanceof File)\n {\n const imageData = await AsyncFileReader.readAsArrayBuffer(environmentFile).catch(() =>\n {\n console.error(\"Could not load image with FileReader\");\n });\n image = await loadHDR(new Uint8Array(imageData));\n }\n else\n {\n console.error(\"Passed invalid type to loadEnvironment \" + typeof (gltfFile));\n }\n if (image === undefined)\n {\n return undefined;\n }\n return _loadEnvironmentFromPanorama(image, this.view, lutFiles);\n }\n\n /**\n * initKtxLib must be called before loading gltf files with ktx2 assets\n * @param {Object} [externalKtxLib] external ktx library (for example from a CDN)\n */\n initKtxLib(externalKtxLib)\n {\n this.view.ktxDecoder = new KtxDecoder(this.view.context, externalKtxLib);\n }\n\n /**\n * initDracoLib must be called before loading gltf files with draco meshes\n * @param {*} [externalDracoLib] external draco library (for example from a CDN)\n */\n async initDracoLib(externalDracoLib)\n {\n const dracoDecoder = new DracoDecoder(externalDracoLib);\n if (dracoDecoder !== undefined)\n {\n await dracoDecoder.ready();\n }\n }\n}\n\nasync function _loadEnvironmentFromPanorama(imageHDR, view, luts)\n{\n // The environment uses the same type of samplers, textures and images as used in the glTF class\n // so we just use it as a template\n const environment = new glTF();\n\n //\n // Prepare samplers.\n //\n\n let samplerIdx = environment.samplers.length;\n\n environment.samplers.push(new gltfSampler(GL.LINEAR, GL.LINEAR, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, \"DiffuseCubeMapSampler\"));\n const diffuseCubeSamplerIdx = samplerIdx++;\n\n environment.samplers.push(new gltfSampler(GL.LINEAR, GL.LINEAR_MIPMAP_LINEAR, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, \"SpecularCubeMapSampler\"));\n const specularCubeSamplerIdx = samplerIdx++;\n\n environment.samplers.push(new gltfSampler(GL.LINEAR, GL.LINEAR_MIPMAP_LINEAR, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, \"SheenCubeMapSampler\"));\n const sheenCubeSamplerIdx = samplerIdx++;\n\n environment.samplers.push(new gltfSampler(GL.LINEAR, GL.LINEAR, GL.CLAMP_TO_EDGE, GL.CLAMP_TO_EDGE, \"LUTSampler\"));\n const lutSamplerIdx = samplerIdx++;\n\n //\n // Prepare images and textures.\n //\n\n let imageIdx = environment.images.length;\n\n let environmentFiltering = new iblSampler(view);\n\n environmentFiltering.init(imageHDR);\n environmentFiltering.filterAll();\n\n // Diffuse\n\n const diffuseGltfImage = new gltfImage(\n undefined,\n GL.TEXTURE_CUBE_MAP,\n 0,\n undefined,\n \"Diffuse\",\n ImageMimeType.GLTEXTURE,\n environmentFiltering.lambertianTextureID\n );\n\n environment.images.push(diffuseGltfImage);\n\n const diffuseTexture = new gltfTexture(\n diffuseCubeSamplerIdx,\n [imageIdx++],\n GL.TEXTURE_CUBE_MAP);\n diffuseTexture.initialized = true; // iblsampler has already initialized the texture\n\n environment.textures.push(diffuseTexture);\n\n environment.diffuseEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.diffuseEnvMap.generateMips = false;\n\n\n\n // Specular\n const specularGltfImage = new gltfImage(\n undefined,\n GL.TEXTURE_CUBE_MAP,\n 0,\n undefined,\n \"Specular\",\n ImageMimeType.GLTEXTURE,\n environmentFiltering.ggxTextureID\n );\n\n environment.images.push(specularGltfImage);\n\n const specularTexture = new gltfTexture(\n specularCubeSamplerIdx,\n [imageIdx++],\n GL.TEXTURE_CUBE_MAP);\n specularTexture.initialized = true; // iblsampler has already initialized the texture\n\n environment.textures.push(specularTexture);\n\n environment.specularEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.specularEnvMap.generateMips = false;\n\n\n // Sheen\n const sheenGltfImage = new gltfImage(\n undefined,\n GL.TEXTURE_CUBE_MAP,\n 0,\n undefined,\n \"Sheen\",\n ImageMimeType.GLTEXTURE,\n environmentFiltering.sheenTextureID\n );\n\n environment.images.push(sheenGltfImage);\n\n const sheenTexture = new gltfTexture(\n sheenCubeSamplerIdx,\n [imageIdx++],\n GL.TEXTURE_CUBE_MAP);\n sheenTexture.initialized = true; // iblsampler has already initialized the texture\n\n environment.textures.push(sheenTexture);\n\n environment.sheenEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.sheenEnvMap.generateMips = false;\n\n /*\n // Diffuse\n\n const lambertian = new gltfImage(filteredEnvironmentsDirectoryPath + \"/lambertian/diffuse.ktx2\", GL.TEXTURE_CUBE_MAP);\n lambertian.mimeType = ImageMimeType.KTX2;\n environment.images.push(lambertian);\n environment.textures.push(new gltfTexture(diffuseCubeSamplerIdx, [imageIdx++], GL.TEXTURE_CUBE_MAP));\n environment.diffuseEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.diffuseEnvMap.generateMips = false;\n\n // Specular\n\n const specular = new gltfImage(filteredEnvironmentsDirectoryPath + \"/ggx/specular.ktx2\", GL.TEXTURE_CUBE_MAP);\n specular.mimeType = ImageMimeType.KTX2;\n environment.images.push(specular);\n environment.textures.push(new gltfTexture(specularCubeSamplerIdx, [imageIdx++], GL.TEXTURE_CUBE_MAP));\n environment.specularEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.specularEnvMap.generateMips = false;\n\n const specularImage = environment.images[environment.textures[environment.textures.length - 1].source];\n\n // Sheen\n\n const sheen = new gltfImage(filteredEnvironmentsDirectoryPath + \"/charlie/sheen.ktx2\", GL.TEXTURE_CUBE_MAP);\n sheen.mimeType = ImageMimeType.KTX2;\n environment.images.push(sheen);\n environment.textures.push(new gltfTexture(sheenCubeSamplerIdx, [imageIdx++], GL.TEXTURE_CUBE_MAP));\n environment.sheenEnvMap = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.sheenEnvMap.generateMips = false;*/\n\n //\n // Look Up Tables.\n //\n\n // GGX\n\n if (luts === undefined)\n {\n luts = {\n lut_sheen_E_file: \"assets/images/lut_sheen_E.png\",\n };\n }\n\n environment.images.push(new gltfImage(\n undefined, \n GL.TEXTURE_2D, \n 0, \n undefined, \n undefined, \n ImageMimeType.GLTEXTURE, \n environmentFiltering.ggxLutTextureID));\n const lutTexture = new gltfTexture(lutSamplerIdx, [imageIdx++], GL.TEXTURE_2D);\n lutTexture.initialized = true; // iblsampler has already initialized the texture\n environment.textures.push(lutTexture);\n\n environment.lut = new gltfTextureInfo(environment.textures.length - 1, 0 , true);\n environment.lut.generateMips = false;\n\n // Sheen\n // Charlie\n environment.images.push(new gltfImage(\n undefined, \n GL.TEXTURE_2D, \n 0, \n undefined, \n undefined, \n ImageMimeType.GLTEXTURE, \n environmentFiltering.charlieLutTextureID));\n const charlieLut = new gltfTexture(lutSamplerIdx, [imageIdx++], GL.TEXTURE_2D);\n charlieLut.initialized = true; // iblsampler has already initialized the texture\n environment.textures.push(charlieLut);\n\n environment.sheenLUT = new gltfTextureInfo(environment.textures.length - 1, 0, true);\n environment.sheenLUT.generateMips = false;\n\n // Sheen E LUT\n\n environment.images.push(new gltfImage(luts.lut_sheen_E_file, GL.TEXTURE_2D, 0, undefined, undefined, ImageMimeType.PNG));\n const sheenELut = new gltfTexture(lutSamplerIdx, [imageIdx++], GL.TEXTURE_2D);\n sheenELut.initialized = true; // iblsampler has already initialized the texture\n environment.textures.push(sheenELut);\n\n environment.sheenELUT = new gltfTextureInfo(environment.textures.length - 1);\n environment.sheenELUT.generateMips = false;\n\n await gltfLoader.loadImages(environment);\n\n environment.initGl(view.context);\n\n environment.mipCount = environmentFiltering.mipmapLevels;\n\n return environment;\n}\n\nexport { ResourceLoader };\n","import { GltfState } from '../GltfState/gltf_state.js';\nimport { gltfRenderer } from '../Renderer/renderer.js';\nimport { GL } from '../Renderer/webgl.js';\nimport { ResourceLoader } from '../ResourceLoader/resource_loader.js';\n\n/**\n * GltfView represents a view on a gltf, e.g. in a canvas\n */\nclass GltfView\n{\n /**\n * GltfView representing one WebGl 2.0 context or in other words one\n * 3D rendering of the Gltf.\n * You can create multiple views for example when multiple canvases should\n * be shown on the same webpage.\n * @param {*} context WebGl 2.0 context. Get it from a canvas with `canvas.getContext(\"webgl2\")`\n */\n constructor(context)\n {\n this.context = context;\n this.renderer = new gltfRenderer(this.context);\n }\n\n /**\n * createState constructs a new GltfState for the GltfView. The resources\n * referenced in a gltf state can directly be stored as resources on the WebGL\n * context of GltfView, therefore GltfStates cannot not be shared between\n * GltfViews.\n * @returns {GltfState} GltfState\n */\n createState()\n {\n return new GltfState(this);\n }\n\n /**\n * createResourceLoader creates a resource loader with which glTFs and\n * environments can be loaded for the view\n * @param {Object} [externalDracoLib] optional object of an external Draco library, e.g. from a CDN\n * @param {Object} [externalKtxLib] optional object of an external KTX library, e.g. from a CDN\n * @returns {ResourceLoader} ResourceLoader\n */\n createResourceLoader(externalDracoLib = undefined, externalKtxLib = undefined)\n {\n let resourceLoader = new ResourceLoader(this);\n resourceLoader.initKtxLib(externalKtxLib);\n resourceLoader.initDracoLib(externalDracoLib);\n return resourceLoader;\n }\n\n /**\n * renderFrame to the context's default frame buffer\n * Call this function in the javascript animation update loop for continuous rendering to a canvas\n * @param {*} state GltfState that is be used for rendering\n * @param {*} width of the viewport\n * @param {*} height of the viewport\n */\n renderFrame(state, width, height)\n {\n this.renderer.init(state);\n this._animate(state);\n\n this.renderer.resize(width, height);\n\n this.renderer.clearFrame(state.renderingParameters.clearColor);\n\n if(state.gltf === undefined)\n {\n return;\n }\n\n const scene = state.gltf.scenes[state.sceneIndex];\n\n if(scene === undefined)\n {\n return;\n }\n\n scene.applyTransformHierarchy(state.gltf);\n\n this.renderer.drawScene(state, scene);\n }\n\n /**\n * gatherStatistics collects information about the GltfState such as the number of\n * rendered meshes or triangles\n * @param {*} state GltfState about which the statistics should be collected\n * @returns {Object} an object containing statistics information\n */\n gatherStatistics(state)\n {\n if(state.gltf === undefined)\n {\n return;\n }\n\n // gather information from the active scene\n const scene = state.gltf.scenes[state.sceneIndex];\n if (scene === undefined)\n {\n return {\n meshCount: 0,\n faceCount: 0,\n opaqueMaterialsCount: 0,\n transparentMaterialsCount: 0};\n }\n const nodes = scene.gatherNodes(state.gltf);\n const activeMeshes = nodes.filter(node => node.mesh !== undefined).map(node => state.gltf.meshes[node.mesh]);\n const activePrimitives = activeMeshes\n .reduce((acc, mesh) => acc.concat(mesh.primitives), [])\n .filter(primitive => primitive.material !== undefined);\n const activeMaterials = [... new Set(activePrimitives.map(primitive => state.gltf.materials[primitive.material]))];\n const opaqueMaterials = activeMaterials.filter(material => material.alphaMode !== \"BLEND\");\n const transparentMaterials = activeMaterials.filter(material => material.alphaMode === \"BLEND\");\n const faceCount = activePrimitives\n .map(primitive => {\n let verticesCount = 0;\n if(primitive.indices !== undefined)\n {\n verticesCount = state.gltf.accessors[primitive.indices].count;\n }\n if (verticesCount === 0)\n {\n return 0;\n }\n\n // convert vertex count to point, line or triangle count\n switch (primitive.mode) {\n case GL.POINTS:\n return verticesCount;\n case GL.LINES:\n return verticesCount / 2;\n case GL.LINE_LOOP:\n return verticesCount;\n case GL.LINE_STRIP:\n return verticesCount - 1;\n case GL.TRIANGLES:\n return verticesCount / 3;\n case GL.TRIANGLE_STRIP:\n case GL.TRIANGLE_FAN:\n return verticesCount - 2;\n }\n })\n .reduce((acc, faceCount) => acc += faceCount);\n\n // assemble statistics object\n return {\n meshCount: activeMeshes.length,\n faceCount: faceCount,\n opaqueMaterialsCount: opaqueMaterials.length,\n transparentMaterialsCount: transparentMaterials.length\n };\n }\n\n _animate(state)\n {\n if(state.gltf === undefined)\n {\n return;\n }\n\n if(state.gltf.animations !== undefined && state.animationIndices !== undefined)\n {\n const disabledAnimations = state.gltf.animations.filter( (anim, index) => {\n return false === state.animationIndices.includes(index);\n });\n\n for(const disabledAnimation of disabledAnimations)\n {\n disabledAnimation.advance(state.gltf, undefined);\n }\n\n const t = state.animationTimer.elapsedSec();\n\n const animations = state.animationIndices.map(index => {\n return state.gltf.animations[index];\n }).filter(animation => animation !== undefined);\n\n for(const animation of animations)\n {\n animation.advance(state.gltf, t);\n }\n }\n }\n}\n\nexport { GltfView };\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isFunction(x) {\n return typeof x === 'function';\n}\n//# sourceMappingURL=isFunction.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar _enable_super_gross_mode_that_will_cause_bad_things = false;\nexport var config = {\n Promise: undefined,\n set useDeprecatedSynchronousErrorHandling(value) {\n if (value) {\n var error = /*@__PURE__*/ new Error();\n /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n }\n else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n /*@__PURE__*/ console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n//# sourceMappingURL=config.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function hostReportError(err) {\n setTimeout(function () { throw err; }, 0);\n}\n//# sourceMappingURL=hostReportError.js.map\n","/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nexport var empty = {\n closed: true,\n next: function (value) { },\n error: function (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n },\n complete: function () { }\n};\n//# sourceMappingURL=Observer.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();\n//# sourceMappingURL=isArray.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isObject(x) {\n return x !== null && typeof x === 'object';\n}\n//# sourceMappingURL=isObject.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {\n function UnsubscriptionErrorImpl(errors) {\n Error.call(this);\n this.message = errors ?\n errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ') : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n return UnsubscriptionErrorImpl;\n})();\nexport var UnsubscriptionError = UnsubscriptionErrorImpl;\n//# sourceMappingURL=UnsubscriptionError.js.map\n","/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */\nimport { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nvar Subscription = /*@__PURE__*/ (function () {\n function Subscription(unsubscribe) {\n this.closed = false;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (unsubscribe) {\n this._ctorUnsubscribe = true;\n this._unsubscribe = unsubscribe;\n }\n }\n Subscription.prototype.unsubscribe = function () {\n var errors;\n if (this.closed) {\n return;\n }\n var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;\n this.closed = true;\n this._parentOrParents = null;\n this._subscriptions = null;\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n }\n else if (_parentOrParents !== null) {\n for (var index = 0; index < _parentOrParents.length; ++index) {\n var parent_1 = _parentOrParents[index];\n parent_1.remove(this);\n }\n }\n if (isFunction(_unsubscribe)) {\n if (_ctorUnsubscribe) {\n this._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n if (isArray(_subscriptions)) {\n var index = -1;\n var len = _subscriptions.length;\n while (++index < len) {\n var sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n }\n catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n }\n else {\n errors.push(e);\n }\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n };\n Subscription.prototype.add = function (teardown) {\n var subscription = teardown;\n if (!teardown) {\n return Subscription.EMPTY;\n }\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n return subscription;\n }\n else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n }\n else if (!(subscription instanceof Subscription)) {\n var tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n var _parentOrParents = subscription._parentOrParents;\n if (_parentOrParents === null) {\n subscription._parentOrParents = this;\n }\n else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n return subscription;\n }\n subscription._parentOrParents = [_parentOrParents, this];\n }\n else if (_parentOrParents.indexOf(this) === -1) {\n _parentOrParents.push(this);\n }\n else {\n return subscription;\n }\n var subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n }\n else {\n subscriptions.push(subscription);\n }\n return subscription;\n };\n Subscription.prototype.remove = function (subscription) {\n var subscriptions = this._subscriptions;\n if (subscriptions) {\n var subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n };\n Subscription.EMPTY = (function (empty) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n return Subscription;\n}());\nexport { Subscription };\nfunction flattenUnsubscriptionErrors(errors) {\n return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []);\n}\n//# sourceMappingURL=Subscription.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var rxSubscriber = /*@__PURE__*/ (function () {\n return typeof Symbol === 'function'\n ? /*@__PURE__*/ Symbol('rxSubscriber')\n : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();\n})();\nexport var $$rxSubscriber = rxSubscriber;\n//# sourceMappingURL=rxSubscriber.js.map\n","/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\nvar Subscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(Subscriber, _super);\n function Subscriber(destinationOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this.syncErrorValue = null;\n _this.syncErrorThrown = false;\n _this.syncErrorThrowable = false;\n _this.isStopped = false;\n switch (arguments.length) {\n case 0:\n _this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n _this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n _this.destination = destinationOrNext;\n destinationOrNext.add(_this);\n }\n else {\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext);\n }\n break;\n }\n default:\n _this.syncErrorThrowable = true;\n _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);\n break;\n }\n return _this;\n }\n Subscriber.prototype[rxSubscriberSymbol] = function () { return this; };\n Subscriber.create = function (next, error, complete) {\n var subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n };\n Subscriber.prototype.next = function (value) {\n if (!this.isStopped) {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n this.destination.error(err);\n this.unsubscribe();\n };\n Subscriber.prototype._complete = function () {\n this.destination.complete();\n this.unsubscribe();\n };\n Subscriber.prototype._unsubscribeAndRecycle = function () {\n var _parentOrParents = this._parentOrParents;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar SafeSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SafeSubscriber, _super);\n function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n _this._parentSubscriber = _parentSubscriber;\n var next;\n var context = _this;\n if (isFunction(observerOrNext)) {\n next = observerOrNext;\n }\n else if (observerOrNext) {\n next = observerOrNext.next;\n error = observerOrNext.error;\n complete = observerOrNext.complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n _this.add(context.unsubscribe.bind(context));\n }\n context.unsubscribe = _this.unsubscribe.bind(_this);\n }\n }\n _this._context = context;\n _this._next = next;\n _this._error = error;\n _this._complete = complete;\n return _this;\n }\n SafeSubscriber.prototype.next = function (value) {\n if (!this.isStopped && this._next) {\n var _parentSubscriber = this._parentSubscriber;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n }\n else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.error = function (err) {\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n }\n else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n }\n else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n }\n else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.complete = function () {\n var _this = this;\n if (!this.isStopped) {\n var _parentSubscriber = this._parentSubscriber;\n if (this._complete) {\n var wrappedComplete = function () { return _this._complete.call(_this._context); };\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n }\n else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n }\n else {\n this.unsubscribe();\n }\n }\n };\n SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n else {\n hostReportError(err);\n }\n }\n };\n SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n }\n else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n };\n SafeSubscriber.prototype._unsubscribe = function () {\n var _parentSubscriber = this._parentSubscriber;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n };\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\n//# sourceMappingURL=Subscriber.js.map\n","/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */\nimport { Subscriber } from '../Subscriber';\nexport function canReportError(observer) {\n while (observer) {\n var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;\n if (closed_1 || isStopped) {\n return false;\n }\n else if (destination && destination instanceof Subscriber) {\n observer = destination;\n }\n else {\n observer = null;\n }\n }\n return true;\n}\n//# sourceMappingURL=canReportError.js.map\n","/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */\nimport { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nexport function toSubscriber(nextOrObserver, error, complete) {\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return nextOrObserver;\n }\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n return new Subscriber(nextOrObserver, error, complete);\n}\n//# sourceMappingURL=toSubscriber.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();\n//# sourceMappingURL=observable.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map\n","/** PURE_IMPORTS_START _identity PURE_IMPORTS_END */\nimport { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map\n","/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nvar Observable = /*@__PURE__*/ (function () {\n function Observable(subscribe) {\n this._isScalar = false;\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var operator = this.operator;\n var sink = toSubscriber(observerOrNext, error, complete);\n if (operator) {\n sink.add(operator.call(sink, this.source));\n }\n else {\n sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink));\n }\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n return sink;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n }\n else {\n console.warn(err);\n }\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscription;\n subscription = _this.subscribe(function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var source = this.source;\n return source && source.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n if (operations.length === 0) {\n return this;\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n return promiseCtor;\n}\n//# sourceMappingURL=Observable.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nvar ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () {\n function ObjectUnsubscribedErrorImpl() {\n Error.call(this);\n this.message = 'object unsubscribed';\n this.name = 'ObjectUnsubscribedError';\n return this;\n }\n ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);\n return ObjectUnsubscribedErrorImpl;\n})();\nexport var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;\n//# sourceMappingURL=ObjectUnsubscribedError.js.map\n","/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscription } from './Subscription';\nvar SubjectSubscription = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SubjectSubscription, _super);\n function SubjectSubscription(subject, subscriber) {\n var _this = _super.call(this) || this;\n _this.subject = subject;\n _this.subscriber = subscriber;\n _this.closed = false;\n return _this;\n }\n SubjectSubscription.prototype.unsubscribe = function () {\n if (this.closed) {\n return;\n }\n this.closed = true;\n var subject = this.subject;\n var observers = subject.observers;\n this.subject = null;\n if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n return;\n }\n var subscriberIndex = observers.indexOf(this.subscriber);\n if (subscriberIndex !== -1) {\n observers.splice(subscriberIndex, 1);\n }\n };\n return SubjectSubscription;\n}(Subscription));\nexport { SubjectSubscription };\n//# sourceMappingURL=SubjectSubscription.js.map\n","/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nvar SubjectSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SubjectSubscriber, _super);\n function SubjectSubscriber(destination) {\n var _this = _super.call(this, destination) || this;\n _this.destination = destination;\n return _this;\n }\n return SubjectSubscriber;\n}(Subscriber));\nexport { SubjectSubscriber };\nvar Subject = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(Subject, _super);\n function Subject() {\n var _this = _super.call(this) || this;\n _this.observers = [];\n _this.closed = false;\n _this.isStopped = false;\n _this.hasError = false;\n _this.thrownError = null;\n return _this;\n }\n Subject.prototype[rxSubscriberSymbol] = function () {\n return new SubjectSubscriber(this);\n };\n Subject.prototype.lift = function (operator) {\n var subject = new AnonymousSubject(this, this);\n subject.operator = operator;\n return subject;\n };\n Subject.prototype.next = function (value) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n if (!this.isStopped) {\n var observers = this.observers;\n var len = observers.length;\n var copy = observers.slice();\n for (var i = 0; i < len; i++) {\n copy[i].next(value);\n }\n }\n };\n Subject.prototype.error = function (err) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.hasError = true;\n this.thrownError = err;\n this.isStopped = true;\n var observers = this.observers;\n var len = observers.length;\n var copy = observers.slice();\n for (var i = 0; i < len; i++) {\n copy[i].error(err);\n }\n this.observers.length = 0;\n };\n Subject.prototype.complete = function () {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.isStopped = true;\n var observers = this.observers;\n var len = observers.length;\n var copy = observers.slice();\n for (var i = 0; i < len; i++) {\n copy[i].complete();\n }\n this.observers.length = 0;\n };\n Subject.prototype.unsubscribe = function () {\n this.isStopped = true;\n this.closed = true;\n this.observers = null;\n };\n Subject.prototype._trySubscribe = function (subscriber) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n else {\n return _super.prototype._trySubscribe.call(this, subscriber);\n }\n };\n Subject.prototype._subscribe = function (subscriber) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n else if (this.hasError) {\n subscriber.error(this.thrownError);\n return Subscription.EMPTY;\n }\n else if (this.isStopped) {\n subscriber.complete();\n return Subscription.EMPTY;\n }\n else {\n this.observers.push(subscriber);\n return new SubjectSubscription(this, subscriber);\n }\n };\n Subject.prototype.asObservable = function () {\n var observable = new Observable();\n observable.source = this;\n return observable;\n };\n Subject.create = function (destination, source) {\n return new AnonymousSubject(destination, source);\n };\n return Subject;\n}(Observable));\nexport { Subject };\nvar AnonymousSubject = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(AnonymousSubject, _super);\n function AnonymousSubject(destination, source) {\n var _this = _super.call(this) || this;\n _this.destination = destination;\n _this.source = source;\n return _this;\n }\n AnonymousSubject.prototype.next = function (value) {\n var destination = this.destination;\n if (destination && destination.next) {\n destination.next(value);\n }\n };\n AnonymousSubject.prototype.error = function (err) {\n var destination = this.destination;\n if (destination && destination.error) {\n this.destination.error(err);\n }\n };\n AnonymousSubject.prototype.complete = function () {\n var destination = this.destination;\n if (destination && destination.complete) {\n this.destination.complete();\n }\n };\n AnonymousSubject.prototype._subscribe = function (subscriber) {\n var source = this.source;\n if (source) {\n return this.source.subscribe(subscriber);\n }\n else {\n return Subscription.EMPTY;\n }\n };\n return AnonymousSubject;\n}(Subject));\nexport { AnonymousSubject };\n//# sourceMappingURL=Subject.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function refCount() {\n return function refCountOperatorFunction(source) {\n return source.lift(new RefCountOperator(source));\n };\n}\nvar RefCountOperator = /*@__PURE__*/ (function () {\n function RefCountOperator(connectable) {\n this.connectable = connectable;\n }\n RefCountOperator.prototype.call = function (subscriber, source) {\n var connectable = this.connectable;\n connectable._refCount++;\n var refCounter = new RefCountSubscriber(subscriber, connectable);\n var subscription = source.subscribe(refCounter);\n if (!refCounter.closed) {\n refCounter.connection = connectable.connect();\n }\n return subscription;\n };\n return RefCountOperator;\n}());\nvar RefCountSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(RefCountSubscriber, _super);\n function RefCountSubscriber(destination, connectable) {\n var _this = _super.call(this, destination) || this;\n _this.connectable = connectable;\n return _this;\n }\n RefCountSubscriber.prototype._unsubscribe = function () {\n var connectable = this.connectable;\n if (!connectable) {\n this.connection = null;\n return;\n }\n this.connectable = null;\n var refCount = connectable._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n connectable._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n var connection = this.connection;\n var sharedConnection = connectable._connection;\n this.connection = null;\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n };\n return RefCountSubscriber;\n}(Subscriber));\n//# sourceMappingURL=refCount.js.map\n","/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { SubjectSubscriber } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nvar ConnectableObservable = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(ConnectableObservable, _super);\n function ConnectableObservable(source, subjectFactory) {\n var _this = _super.call(this) || this;\n _this.source = source;\n _this.subjectFactory = subjectFactory;\n _this._refCount = 0;\n _this._isComplete = false;\n return _this;\n }\n ConnectableObservable.prototype._subscribe = function (subscriber) {\n return this.getSubject().subscribe(subscriber);\n };\n ConnectableObservable.prototype.getSubject = function () {\n var subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject;\n };\n ConnectableObservable.prototype.connect = function () {\n var connection = this._connection;\n if (!connection) {\n this._isComplete = false;\n connection = this._connection = new Subscription();\n connection.add(this.source\n .subscribe(new ConnectableSubscriber(this.getSubject(), this)));\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n };\n ConnectableObservable.prototype.refCount = function () {\n return higherOrderRefCount()(this);\n };\n return ConnectableObservable;\n}(Observable));\nexport { ConnectableObservable };\nexport var connectableObservableDescriptor = /*@__PURE__*/ (function () {\n var connectableProto = ConnectableObservable.prototype;\n return {\n operator: { value: null },\n _refCount: { value: 0, writable: true },\n _subject: { value: null, writable: true },\n _connection: { value: null, writable: true },\n _subscribe: { value: connectableProto._subscribe },\n _isComplete: { value: connectableProto._isComplete, writable: true },\n getSubject: { value: connectableProto.getSubject },\n connect: { value: connectableProto.connect },\n refCount: { value: connectableProto.refCount }\n };\n})();\nvar ConnectableSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(ConnectableSubscriber, _super);\n function ConnectableSubscriber(destination, connectable) {\n var _this = _super.call(this, destination) || this;\n _this.connectable = connectable;\n return _this;\n }\n ConnectableSubscriber.prototype._error = function (err) {\n this._unsubscribe();\n _super.prototype._error.call(this, err);\n };\n ConnectableSubscriber.prototype._complete = function () {\n this.connectable._isComplete = true;\n this._unsubscribe();\n _super.prototype._complete.call(this);\n };\n ConnectableSubscriber.prototype._unsubscribe = function () {\n var connectable = this.connectable;\n if (connectable) {\n this.connectable = null;\n var connection = connectable._connection;\n connectable._refCount = 0;\n connectable._subject = null;\n connectable._connection = null;\n if (connection) {\n connection.unsubscribe();\n }\n }\n };\n return ConnectableSubscriber;\n}(SubjectSubscriber));\nvar RefCountOperator = /*@__PURE__*/ (function () {\n function RefCountOperator(connectable) {\n this.connectable = connectable;\n }\n RefCountOperator.prototype.call = function (subscriber, source) {\n var connectable = this.connectable;\n connectable._refCount++;\n var refCounter = new RefCountSubscriber(subscriber, connectable);\n var subscription = source.subscribe(refCounter);\n if (!refCounter.closed) {\n refCounter.connection = connectable.connect();\n }\n return subscription;\n };\n return RefCountOperator;\n}());\nvar RefCountSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(RefCountSubscriber, _super);\n function RefCountSubscriber(destination, connectable) {\n var _this = _super.call(this, destination) || this;\n _this.connectable = connectable;\n return _this;\n }\n RefCountSubscriber.prototype._unsubscribe = function () {\n var connectable = this.connectable;\n if (!connectable) {\n this.connection = null;\n return;\n }\n this.connectable = null;\n var refCount = connectable._refCount;\n if (refCount <= 0) {\n this.connection = null;\n return;\n }\n connectable._refCount = refCount - 1;\n if (refCount > 1) {\n this.connection = null;\n return;\n }\n var connection = this.connection;\n var sharedConnection = connectable._connection;\n this.connection = null;\n if (sharedConnection && (!connection || sharedConnection === connection)) {\n sharedConnection.unsubscribe();\n }\n };\n return RefCountSubscriber;\n}(Subscriber));\n//# sourceMappingURL=ConnectableObservable.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isScheduler(value) {\n return value && typeof value.schedule === 'function';\n}\n//# sourceMappingURL=isScheduler.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var subscribeToArray = function (array) {\n return function (subscriber) {\n for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n };\n};\n//# sourceMappingURL=subscribeToArray.js.map\n","/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nexport function scheduleArray(input, scheduler) {\n return new Observable(function (subscriber) {\n var sub = new Subscription();\n var i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n//# sourceMappingURL=scheduleArray.js.map\n","/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { subscribeToArray } from '../util/subscribeToArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\nexport function fromArray(input, scheduler) {\n if (!scheduler) {\n return new Observable(subscribeToArray(input));\n }\n else {\n return scheduleArray(input, scheduler);\n }\n}\n//# sourceMappingURL=fromArray.js.map\n","/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */\nimport { isScheduler } from '../util/isScheduler';\nimport { fromArray } from './fromArray';\nimport { scheduleArray } from '../scheduled/scheduleArray';\nexport function of() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var scheduler = args[args.length - 1];\n if (isScheduler(scheduler)) {\n args.pop();\n return scheduleArray(args, scheduler);\n }\n else {\n return fromArray(args);\n }\n}\n//# sourceMappingURL=of.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function noop() { }\n//# sourceMappingURL=noop.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function map(project, thisArg) {\n return function mapOperation(source) {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\nvar MapOperator = /*@__PURE__*/ (function () {\n function MapOperator(project, thisArg) {\n this.project = project;\n this.thisArg = thisArg;\n }\n MapOperator.prototype.call = function (subscriber, source) {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n };\n return MapOperator;\n}());\nexport { MapOperator };\nvar MapSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(MapSubscriber, _super);\n function MapSubscriber(destination, project, thisArg) {\n var _this = _super.call(this, destination) || this;\n _this.project = project;\n _this.count = 0;\n _this.thisArg = thisArg || _this;\n return _this;\n }\n MapSubscriber.prototype._next = function (value) {\n var result;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n }\n catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n };\n return MapSubscriber;\n}(Subscriber));\n//# sourceMappingURL=map.js.map\n","/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */\nimport { hostReportError } from './hostReportError';\nexport var subscribeToPromise = function (promise) {\n return function (subscriber) {\n promise.then(function (value) {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, function (err) { return subscriber.error(err); })\n .then(null, hostReportError);\n return subscriber;\n };\n};\n//# sourceMappingURL=subscribeToPromise.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport var iterator = /*@__PURE__*/ getSymbolIterator();\nexport var $$iterator = iterator;\n//# sourceMappingURL=iterator.js.map\n","/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nexport var subscribeToIterable = function (iterable) {\n return function (subscriber) {\n var iterator = iterable[Symbol_iterator]();\n do {\n var item = void 0;\n try {\n item = iterator.next();\n }\n catch (err) {\n subscriber.error(err);\n return subscriber;\n }\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n if (typeof iterator.return === 'function') {\n subscriber.add(function () {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n return subscriber;\n };\n};\n//# sourceMappingURL=subscribeToIterable.js.map\n","/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport var subscribeToObservable = function (obj) {\n return function (subscriber) {\n var obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n }\n else {\n return obs.subscribe(subscriber);\n }\n };\n};\n//# sourceMappingURL=subscribeToObservable.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n//# sourceMappingURL=isArrayLike.js.map\n","/** PURE_IMPORTS_START PURE_IMPORTS_END */\nexport function isPromise(value) {\n return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';\n}\n//# sourceMappingURL=isPromise.js.map\n","/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport var subscribeTo = function (result) {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result);\n }\n else if (isArrayLike(result)) {\n return subscribeToArray(result);\n }\n else if (isPromise(result)) {\n return subscribeToPromise(result);\n }\n else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result);\n }\n else {\n var value = isObject(result) ? 'an invalid object' : \"'\" + result + \"'\";\n var msg = \"You provided \" + value + \" where a stream was expected.\"\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n//# sourceMappingURL=subscribeTo.js.map\n","/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function scheduleObservable(input, scheduler) {\n return new Observable(function (subscriber) {\n var sub = new Subscription();\n sub.add(scheduler.schedule(function () {\n var observable = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },\n error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },\n complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },\n }));\n }));\n return sub;\n });\n}\n//# sourceMappingURL=scheduleObservable.js.map\n","/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nexport function schedulePromise(input, scheduler) {\n return new Observable(function (subscriber) {\n var sub = new Subscription();\n sub.add(scheduler.schedule(function () {\n return input.then(function (value) {\n sub.add(scheduler.schedule(function () {\n subscriber.next(value);\n sub.add(scheduler.schedule(function () { return subscriber.complete(); }));\n }));\n }, function (err) {\n sub.add(scheduler.schedule(function () { return subscriber.error(err); }));\n });\n }));\n return sub;\n });\n}\n//# sourceMappingURL=schedulePromise.js.map\n","/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nexport function scheduleIterable(input, scheduler) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(function (subscriber) {\n var sub = new Subscription();\n var iterator;\n sub.add(function () {\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(function () {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n var value;\n var done;\n try {\n var result = iterator.next();\n value = result.value;\n done = result.done;\n }\n catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n }\n else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n//# sourceMappingURL=scheduleIterable.js.map\n","/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function isInteropObservable(input) {\n return input && typeof input[Symbol_observable] === 'function';\n}\n//# sourceMappingURL=isInteropObservable.js.map\n","/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nexport function isIterable(input) {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n//# sourceMappingURL=isIterable.js.map\n","/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */\nimport { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nexport function scheduled(input, scheduler) {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n//# sourceMappingURL=scheduled.js.map\n","/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { scheduled } from '../scheduled/scheduled';\nexport function from(input, scheduler) {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable(subscribeTo(input));\n }\n else {\n return scheduled(input, scheduler);\n }\n}\n//# sourceMappingURL=from.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\nvar SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SimpleInnerSubscriber, _super);\n function SimpleInnerSubscriber(parent) {\n var _this = _super.call(this) || this;\n _this.parent = parent;\n return _this;\n }\n SimpleInnerSubscriber.prototype._next = function (value) {\n this.parent.notifyNext(value);\n };\n SimpleInnerSubscriber.prototype._error = function (error) {\n this.parent.notifyError(error);\n this.unsubscribe();\n };\n SimpleInnerSubscriber.prototype._complete = function () {\n this.parent.notifyComplete();\n this.unsubscribe();\n };\n return SimpleInnerSubscriber;\n}(Subscriber));\nexport { SimpleInnerSubscriber };\nvar ComplexInnerSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(ComplexInnerSubscriber, _super);\n function ComplexInnerSubscriber(parent, outerValue, outerIndex) {\n var _this = _super.call(this) || this;\n _this.parent = parent;\n _this.outerValue = outerValue;\n _this.outerIndex = outerIndex;\n return _this;\n }\n ComplexInnerSubscriber.prototype._next = function (value) {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n };\n ComplexInnerSubscriber.prototype._error = function (error) {\n this.parent.notifyError(error);\n this.unsubscribe();\n };\n ComplexInnerSubscriber.prototype._complete = function () {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n };\n return ComplexInnerSubscriber;\n}(Subscriber));\nexport { ComplexInnerSubscriber };\nvar SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(SimpleOuterSubscriber, _super);\n function SimpleOuterSubscriber() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) {\n this.destination.next(innerValue);\n };\n SimpleOuterSubscriber.prototype.notifyError = function (err) {\n this.destination.error(err);\n };\n SimpleOuterSubscriber.prototype.notifyComplete = function () {\n this.destination.complete();\n };\n return SimpleOuterSubscriber;\n}(Subscriber));\nexport { SimpleOuterSubscriber };\nvar ComplexOuterSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(ComplexOuterSubscriber, _super);\n function ComplexOuterSubscriber() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n ComplexOuterSubscriber.prototype.notifyNext = function (_outerValue, innerValue, _outerIndex, _innerSub) {\n this.destination.next(innerValue);\n };\n ComplexOuterSubscriber.prototype.notifyError = function (error) {\n this.destination.error(error);\n };\n ComplexOuterSubscriber.prototype.notifyComplete = function (_innerSub) {\n this.destination.complete();\n };\n return ComplexOuterSubscriber;\n}(Subscriber));\nexport { ComplexOuterSubscriber };\nexport function innerSubscribe(result, innerSubscriber) {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n var subscription;\n try {\n subscription = subscribeTo(result)(innerSubscriber);\n }\n catch (error) {\n innerSubscriber.error(error);\n }\n return subscription;\n}\n//# sourceMappingURL=innerSubscribe.js.map\n","/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\nexport function mergeMap(project, resultSelector, concurrent) {\n if (concurrent === void 0) {\n concurrent = Number.POSITIVE_INFINITY;\n }\n if (typeof resultSelector === 'function') {\n return function (source) { return source.pipe(mergeMap(function (a, i) { return from(project(a, i)).pipe(map(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };\n }\n else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };\n}\nvar MergeMapOperator = /*@__PURE__*/ (function () {\n function MergeMapOperator(project, concurrent) {\n if (concurrent === void 0) {\n concurrent = Number.POSITIVE_INFINITY;\n }\n this.project = project;\n this.concurrent = concurrent;\n }\n MergeMapOperator.prototype.call = function (observer, source) {\n return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));\n };\n return MergeMapOperator;\n}());\nexport { MergeMapOperator };\nvar MergeMapSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(MergeMapSubscriber, _super);\n function MergeMapSubscriber(destination, project, concurrent) {\n if (concurrent === void 0) {\n concurrent = Number.POSITIVE_INFINITY;\n }\n var _this = _super.call(this, destination) || this;\n _this.project = project;\n _this.concurrent = concurrent;\n _this.hasCompleted = false;\n _this.buffer = [];\n _this.active = 0;\n _this.index = 0;\n return _this;\n }\n MergeMapSubscriber.prototype._next = function (value) {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n }\n else {\n this.buffer.push(value);\n }\n };\n MergeMapSubscriber.prototype._tryNext = function (value) {\n var result;\n var index = this.index++;\n try {\n result = this.project(value, index);\n }\n catch (err) {\n this.destination.error(err);\n return;\n }\n this.active++;\n this._innerSub(result);\n };\n MergeMapSubscriber.prototype._innerSub = function (ish) {\n var innerSubscriber = new SimpleInnerSubscriber(this);\n var destination = this.destination;\n destination.add(innerSubscriber);\n var innerSubscription = innerSubscribe(ish, innerSubscriber);\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n };\n MergeMapSubscriber.prototype._complete = function () {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete();\n }\n this.unsubscribe();\n };\n MergeMapSubscriber.prototype.notifyNext = function (innerValue) {\n this.destination.next(innerValue);\n };\n MergeMapSubscriber.prototype.notifyComplete = function () {\n var buffer = this.buffer;\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift());\n }\n else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete();\n }\n };\n return MergeMapSubscriber;\n}(SimpleOuterSubscriber));\nexport { MergeMapSubscriber };\nexport var flatMap = mergeMap;\n//# sourceMappingURL=mergeMap.js.map\n","/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */\nimport { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nexport function mergeAll(concurrent) {\n if (concurrent === void 0) {\n concurrent = Number.POSITIVE_INFINITY;\n }\n return mergeMap(identity, concurrent);\n}\n//# sourceMappingURL=mergeAll.js.map\n","/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */\nimport { mergeAll } from './mergeAll';\nexport function concatAll() {\n return mergeAll(1);\n}\n//# sourceMappingURL=concatAll.js.map\n","/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */\nimport { of } from './of';\nimport { concatAll } from '../operators/concatAll';\nexport function concat() {\n var observables = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n observables[_i] = arguments[_i];\n }\n return concatAll()(of.apply(void 0, observables));\n}\n//# sourceMappingURL=concat.js.map\n","/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { isArray } from '../util/isArray';\nimport { isFunction } from '../util/isFunction';\nimport { map } from '../operators/map';\nvar toString = /*@__PURE__*/ (function () { return Object.prototype.toString; })();\nexport function fromEvent(target, eventName, options, resultSelector) {\n if (isFunction(options)) {\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n return fromEvent(target, eventName, options).pipe(map(function (args) { return isArray(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));\n }\n return new Observable(function (subscriber) {\n function handler(e) {\n if (arguments.length > 1) {\n subscriber.next(Array.prototype.slice.call(arguments));\n }\n else {\n subscriber.next(e);\n }\n }\n setupSubscription(target, eventName, handler, subscriber, options);\n });\n}\nfunction setupSubscription(sourceObj, eventName, handler, subscriber, options) {\n var unsubscribe;\n if (isEventTarget(sourceObj)) {\n var source_1 = sourceObj;\n sourceObj.addEventListener(eventName, handler, options);\n unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };\n }\n else if (isJQueryStyleEventEmitter(sourceObj)) {\n var source_2 = sourceObj;\n sourceObj.on(eventName, handler);\n unsubscribe = function () { return source_2.off(eventName, handler); };\n }\n else if (isNodeStyleEventEmitter(sourceObj)) {\n var source_3 = sourceObj;\n sourceObj.addListener(eventName, handler);\n unsubscribe = function () { return source_3.removeListener(eventName, handler); };\n }\n else if (sourceObj && sourceObj.length) {\n for (var i = 0, len = sourceObj.length; i < len; i++) {\n setupSubscription(sourceObj[i], eventName, handler, subscriber, options);\n }\n }\n else {\n throw new TypeError('Invalid event target');\n }\n subscriber.add(unsubscribe);\n}\nfunction isNodeStyleEventEmitter(sourceObj) {\n return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';\n}\nfunction isJQueryStyleEventEmitter(sourceObj) {\n return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';\n}\nfunction isEventTarget(sourceObj) {\n return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';\n}\n//# sourceMappingURL=fromEvent.js.map\n","/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { isScheduler } from '../util/isScheduler';\nimport { mergeAll } from '../operators/mergeAll';\nimport { fromArray } from './fromArray';\nexport function merge() {\n var observables = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n observables[_i] = arguments[_i];\n }\n var concurrent = Number.POSITIVE_INFINITY;\n var scheduler = null;\n var last = observables[observables.length - 1];\n if (isScheduler(last)) {\n scheduler = observables.pop();\n if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {\n concurrent = observables.pop();\n }\n }\n else if (typeof last === 'number') {\n concurrent = observables.pop();\n }\n if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) {\n return observables[0];\n }\n return mergeAll(concurrent)(fromArray(observables, scheduler));\n}\n//# sourceMappingURL=merge.js.map\n","/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */\nimport { Observable } from '../Observable';\nimport { noop } from '../util/noop';\nexport var NEVER = /*@__PURE__*/ new Observable(noop);\nexport function never() {\n return NEVER;\n}\n//# sourceMappingURL=never.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function filter(predicate, thisArg) {\n return function filterOperatorFunction(source) {\n return source.lift(new FilterOperator(predicate, thisArg));\n };\n}\nvar FilterOperator = /*@__PURE__*/ (function () {\n function FilterOperator(predicate, thisArg) {\n this.predicate = predicate;\n this.thisArg = thisArg;\n }\n FilterOperator.prototype.call = function (subscriber, source) {\n return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));\n };\n return FilterOperator;\n}());\nvar FilterSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(FilterSubscriber, _super);\n function FilterSubscriber(destination, predicate, thisArg) {\n var _this = _super.call(this, destination) || this;\n _this.predicate = predicate;\n _this.thisArg = thisArg;\n _this.count = 0;\n return _this;\n }\n FilterSubscriber.prototype._next = function (value) {\n var result;\n try {\n result = this.predicate.call(this.thisArg, value, this.count++);\n }\n catch (err) {\n this.destination.error(err);\n return;\n }\n if (result) {\n this.destination.next(value);\n }\n };\n return FilterSubscriber;\n}(Subscriber));\n//# sourceMappingURL=filter.js.map\n","/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */\nimport { connectableObservableDescriptor } from '../observable/ConnectableObservable';\nexport function multicast(subjectOrSubjectFactory, selector) {\n return function multicastOperatorFunction(source) {\n var subjectFactory;\n if (typeof subjectOrSubjectFactory === 'function') {\n subjectFactory = subjectOrSubjectFactory;\n }\n else {\n subjectFactory = function subjectFactory() {\n return subjectOrSubjectFactory;\n };\n }\n if (typeof selector === 'function') {\n return source.lift(new MulticastOperator(subjectFactory, selector));\n }\n var connectable = Object.create(source, connectableObservableDescriptor);\n connectable.source = source;\n connectable.subjectFactory = subjectFactory;\n return connectable;\n };\n}\nvar MulticastOperator = /*@__PURE__*/ (function () {\n function MulticastOperator(subjectFactory, selector) {\n this.subjectFactory = subjectFactory;\n this.selector = selector;\n }\n MulticastOperator.prototype.call = function (subscriber, source) {\n var selector = this.selector;\n var subject = this.subjectFactory();\n var subscription = selector(subject).subscribe(subscriber);\n subscription.add(source.subscribe(subject));\n return subscription;\n };\n return MulticastOperator;\n}());\nexport { MulticastOperator };\n//# sourceMappingURL=multicast.js.map\n","/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function pairwise() {\n return function (source) { return source.lift(new PairwiseOperator()); };\n}\nvar PairwiseOperator = /*@__PURE__*/ (function () {\n function PairwiseOperator() {\n }\n PairwiseOperator.prototype.call = function (subscriber, source) {\n return source.subscribe(new PairwiseSubscriber(subscriber));\n };\n return PairwiseOperator;\n}());\nvar PairwiseSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(PairwiseSubscriber, _super);\n function PairwiseSubscriber(destination) {\n var _this = _super.call(this, destination) || this;\n _this.hasPrev = false;\n return _this;\n }\n PairwiseSubscriber.prototype._next = function (value) {\n var pair;\n if (this.hasPrev) {\n pair = [this.prev, value];\n }\n else {\n this.hasPrev = true;\n }\n this.prev = value;\n if (pair) {\n this.destination.next(pair);\n }\n };\n return PairwiseSubscriber;\n}(Subscriber));\n//# sourceMappingURL=pairwise.js.map\n","/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */\nimport { multicast } from './multicast';\nimport { refCount } from './refCount';\nimport { Subject } from '../Subject';\nfunction shareSubjectFactory() {\n return new Subject();\n}\nexport function share() {\n return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); };\n}\n//# sourceMappingURL=share.js.map\n","/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */\nimport { concat } from '../observable/concat';\nimport { isScheduler } from '../util/isScheduler';\nexport function startWith() {\n var array = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n array[_i] = arguments[_i];\n }\n var scheduler = array[array.length - 1];\n if (isScheduler(scheduler)) {\n array.pop();\n return function (source) { return concat(array, source, scheduler); };\n }\n else {\n return function (source) { return concat(array, source); };\n }\n}\n//# sourceMappingURL=startWith.js.map\n","/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */\nimport * as tslib_1 from \"tslib\";\nimport { innerSubscribe, SimpleInnerSubscriber, SimpleOuterSubscriber } from '../innerSubscribe';\nexport function takeUntil(notifier) {\n return function (source) { return source.lift(new TakeUntilOperator(notifier)); };\n}\nvar TakeUntilOperator = /*@__PURE__*/ (function () {\n function TakeUntilOperator(notifier) {\n this.notifier = notifier;\n }\n TakeUntilOperator.prototype.call = function (subscriber, source) {\n var takeUntilSubscriber = new TakeUntilSubscriber(subscriber);\n var notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber));\n if (notifierSubscription && !takeUntilSubscriber.seenValue) {\n takeUntilSubscriber.add(notifierSubscription);\n return source.subscribe(takeUntilSubscriber);\n }\n return takeUntilSubscriber;\n };\n return TakeUntilOperator;\n}());\nvar TakeUntilSubscriber = /*@__PURE__*/ (function (_super) {\n tslib_1.__extends(TakeUntilSubscriber, _super);\n function TakeUntilSubscriber(destination) {\n var _this = _super.call(this, destination) || this;\n _this.seenValue = false;\n return _this;\n }\n TakeUntilSubscriber.prototype.notifyNext = function () {\n this.seenValue = true;\n this.complete();\n };\n TakeUntilSubscriber.prototype.notifyComplete = function () {\n };\n return TakeUntilSubscriber;\n}(SimpleOuterSubscriber));\n//# sourceMappingURL=takeUntil.js.map\n","var e=[0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,0,0,16,17,18,18,19,19,20,20,20,20,21,21,21,21,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29];function t(){var e=this;function t(e,t){var n=0;do{n|=1&e,e>>>=1,n<<=1}while(--t>0);return n>>>1}e.build_tree=function(n){var i,r,a,o=e.dyn_tree,s=e.stat_desc.static_tree,l=e.stat_desc.elems,f=-1;for(n.heap_len=0,n.heap_max=573,i=0;i=1;i--)n.pqdownheap(o,i);a=l;do{i=n.heap[1],n.heap[1]=n.heap[n.heap_len--],n.pqdownheap(o,1),r=n.heap[1],n.heap[--n.heap_max]=i,n.heap[--n.heap_max]=r,o[2*a]=o[2*i]+o[2*r],n.depth[a]=Math.max(n.depth[i],n.depth[r])+1,o[2*i+1]=o[2*r+1]=a,n.heap[1]=a++,n.pqdownheap(o,1)}while(n.heap_len>=2);n.heap[--n.heap_max]=n.heap[1],function(t){var n,i,r,a,o,s,l=e.dyn_tree,f=e.stat_desc.static_tree,u=e.stat_desc.extra_bits,d=e.stat_desc.extra_base,c=e.stat_desc.max_length,_=0;for(a=0;a<=15;a++)t.bl_count[a]=0;for(l[2*t.heap[t.heap_max]+1]=0,n=t.heap_max+1;n<573;n++)(a=l[2*l[2*(i=t.heap[n])+1]+1]+1)>c&&(a=c,_++),l[2*i+1]=a,i>e.max_code||(t.bl_count[a]++,o=0,i>=d&&(o=u[i-d]),t.opt_len+=(s=l[2*i])*(a+o),f&&(t.static_len+=s*(f[2*i+1]+o)));if(0!==_){do{for(a=c-1;0===t.bl_count[a];)a--;t.bl_count[a]--,t.bl_count[a+1]+=2,t.bl_count[c]--,_-=2}while(_>0);for(a=c;0!==a;a--)for(i=t.bl_count[a];0!==i;)(r=t.heap[--n])>e.max_code||(l[2*r+1]!=a&&(t.opt_len+=(a-l[2*r+1])*l[2*r],l[2*r+1]=a),i--)}}(n),function(e,n,i){var r,a,o,s=[],l=0;for(r=1;r<=15;r++)s[r]=l=l+i[r-1]<<1;for(a=0;a<=n;a++)0!==(o=e[2*a+1])&&(e[2*a]=t(s[o]++,o))}(o,e.max_code,n.bl_count)}}function n(e,t,n,i,r){var a=this;a.static_tree=e,a.extra_bits=t,a.extra_base=n,a.elems=i,a.max_length=r}function i(e,t,n,i,r){var a=this;a.good_length=e,a.max_lazy=t,a.nice_length=n,a.max_chain=i,a.func=r}t._length_code=[0,1,2,3,4,5,6,7,8,8,9,9,10,10,11,11,12,12,12,12,13,13,13,13,14,14,14,14,15,15,15,15,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28],t.base_length=[0,1,2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128,160,192,224,0],t.base_dist=[0,1,2,3,4,6,8,12,16,24,32,48,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096,6144,8192,12288,16384,24576],t.d_code=function(t){return t<256?e[t]:e[256+(t>>>7)]},t.extra_lbits=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],t.extra_dbits=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],t.extra_blbits=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],t.bl_order=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],n.static_ltree=[12,8,140,8,76,8,204,8,44,8,172,8,108,8,236,8,28,8,156,8,92,8,220,8,60,8,188,8,124,8,252,8,2,8,130,8,66,8,194,8,34,8,162,8,98,8,226,8,18,8,146,8,82,8,210,8,50,8,178,8,114,8,242,8,10,8,138,8,74,8,202,8,42,8,170,8,106,8,234,8,26,8,154,8,90,8,218,8,58,8,186,8,122,8,250,8,6,8,134,8,70,8,198,8,38,8,166,8,102,8,230,8,22,8,150,8,86,8,214,8,54,8,182,8,118,8,246,8,14,8,142,8,78,8,206,8,46,8,174,8,110,8,238,8,30,8,158,8,94,8,222,8,62,8,190,8,126,8,254,8,1,8,129,8,65,8,193,8,33,8,161,8,97,8,225,8,17,8,145,8,81,8,209,8,49,8,177,8,113,8,241,8,9,8,137,8,73,8,201,8,41,8,169,8,105,8,233,8,25,8,153,8,89,8,217,8,57,8,185,8,121,8,249,8,5,8,133,8,69,8,197,8,37,8,165,8,101,8,229,8,21,8,149,8,85,8,213,8,53,8,181,8,117,8,245,8,13,8,141,8,77,8,205,8,45,8,173,8,109,8,237,8,29,8,157,8,93,8,221,8,61,8,189,8,125,8,253,8,19,9,275,9,147,9,403,9,83,9,339,9,211,9,467,9,51,9,307,9,179,9,435,9,115,9,371,9,243,9,499,9,11,9,267,9,139,9,395,9,75,9,331,9,203,9,459,9,43,9,299,9,171,9,427,9,107,9,363,9,235,9,491,9,27,9,283,9,155,9,411,9,91,9,347,9,219,9,475,9,59,9,315,9,187,9,443,9,123,9,379,9,251,9,507,9,7,9,263,9,135,9,391,9,71,9,327,9,199,9,455,9,39,9,295,9,167,9,423,9,103,9,359,9,231,9,487,9,23,9,279,9,151,9,407,9,87,9,343,9,215,9,471,9,55,9,311,9,183,9,439,9,119,9,375,9,247,9,503,9,15,9,271,9,143,9,399,9,79,9,335,9,207,9,463,9,47,9,303,9,175,9,431,9,111,9,367,9,239,9,495,9,31,9,287,9,159,9,415,9,95,9,351,9,223,9,479,9,63,9,319,9,191,9,447,9,127,9,383,9,255,9,511,9,0,7,64,7,32,7,96,7,16,7,80,7,48,7,112,7,8,7,72,7,40,7,104,7,24,7,88,7,56,7,120,7,4,7,68,7,36,7,100,7,20,7,84,7,52,7,116,7,3,8,131,8,67,8,195,8,35,8,163,8,99,8,227,8],n.static_dtree=[0,5,16,5,8,5,24,5,4,5,20,5,12,5,28,5,2,5,18,5,10,5,26,5,6,5,22,5,14,5,30,5,1,5,17,5,9,5,25,5,5,5,21,5,13,5,29,5,3,5,19,5,11,5,27,5,7,5,23,5],n.static_l_desc=new n(n.static_ltree,t.extra_lbits,257,286,15),n.static_d_desc=new n(n.static_dtree,t.extra_dbits,0,30,15),n.static_bl_desc=new n(null,t.extra_blbits,0,19,7);var r=[new i(0,0,0,0,0),new i(4,4,8,4,1),new i(4,5,16,8,1),new i(4,6,32,32,1),new i(4,4,16,16,2),new i(8,16,32,32,2),new i(8,16,128,128,2),new i(8,32,128,256,2),new i(32,128,258,1024,2),new i(32,258,258,4096,2)],a=[\"need dictionary\",\"stream end\",\"\",\"\",\"stream error\",\"data error\",\"\",\"buffer error\",\"\",\"\"];function o(e,t,n,i){var r=e[2*t],a=e[2*n];return r>>8&255)}function ee(e,t){var n,i=t;q>16-i?(X(V|=(n=e)<>>16-q,q+=i-16):(V|=e<=8&&(Q(255&V),V>>>=8,q-=8)}function re(e,n){var i,r,a;if($.pending_buf[N+2*Z]=e>>>8&255,$.pending_buf[N+2*Z+1]=255&e,$.pending_buf[L+Z]=255&n,Z++,0===e?B[2*n]++:(j++,e--,B[2*(t._length_code[n]+256+1)]++,I[2*t.d_code(e)]++),0==(8191&Z)&&F>2){for(i=8*Z,r=z-g,a=0;a<30;a++)i+=I[2*a]*(5+t.extra_dbits[a]);if(i>>>=3,j8?X(V):q>0&&Q(255&V),V=0,q=0}function se(e,t,n){ee(0+(n?1:0),3),function(e,t,n){oe(),O=8,X(t),X(~t),$.pending_buf.set(c.subarray(e,e+t),$.pending),$.pending+=t}(e,t)}function le(i){(function(e,i,r){var a,o,s=0;F>0?(G.build_tree($),H.build_tree($),s=function(){var e;for(K(B,G.max_code),K(I,H.max_code),Y.build_tree($),e=18;e>=3&&0===C[2*t.bl_order[e]+1];e--);return $.opt_len+=3*(e+1)+5+5+4,e}(),(o=$.static_len+3+7>>>3)<=(a=$.opt_len+3+7>>>3)&&(a=o)):a=o=i+5,i+4<=a&&-1!=e?se(e,i,r):o==a?(ee(2+(r?1:0),3),ae(n.static_ltree,n.static_dtree)):(ee(4+(r?1:0),3),function(e,n,i){var r;for(ee(e-257,5),ee(n-1,5),ee(i-4,4),r=0;r=0?g:-1,z-g,i),g=z,e.flush_pending()}function fe(){var t,n,i,r;do{if(0==(r=_-D-z)&&0===z&&0===D)r=f;else if(-1==r)r--;else if(z>=f+f-262){c.set(c.subarray(f,f+f),0),E-=f,z-=f,g-=f,i=t=v;do{n=65535&p[--i],p[i]=n>=f?n-f:0}while(0!=--t);i=t=f;do{n=65535&h[--i],h[i]=n>=f?n-f:0}while(0!=--t);r+=f}if(0===e.avail_in)return;t=e.read_buf(c,z+D,r),(D+=t)>=3&&(w=((w=255&c[z])<f-262?z-(f-262):0,s=M,l=d,u=z+258,_=c[r+a-1],p=c[r+a];A>=W&&(i>>=2),s>D&&(s=D);do{if(c[(t=e)+a]==p&&c[t+a-1]==_&&c[t]==c[r]&&c[++t]==c[r+1]){r+=2,t++;do{}while(c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&c[++r]==c[++t]&&ra){if(E=e,a=n,n>=s)break;_=c[r+a-1],p=c[r+a]}}}while((e=65535&h[e&l])>o&&0!=--i);return a<=D?a:D}$.depth=[],$.bl_count=[],$.heap=[],B=[],I=[],C=[],$.pqdownheap=function(e,t){for(var n=$.heap,i=n[t],r=t<<1;r<=$.heap_len&&(r<$.heap_len&&o(e,n[r+1],n[r],$.depth)&&r++,!o(e,i,n[r],$.depth));)n[t]=n[r],t=r,r<<=1;n[t]=i},$.deflateInit=function(e,t,a,o,k,E){return o||(o=8),k||(k=8),E||(E=0),e.msg=null,-1==t&&(t=6),k<1||k>9||8!=o||a<9||a>15||t<0||t>9||E<0||E>2?-2:(e.dstate=$,d=(f=1<<(u=a))-1,x=(v=1<<(b=k+7))-1,m=Math.floor((b+3-1)/3),c=new Uint8Array(2*f),h=[],p=[],P=1<9||n<0||n>2?-2:(r[F].func!=r[t].func&&0!==e.total_in&&(i=e.deflate(1)),F!=t&&(R=r[F=t].max_lazy,W=r[F].good_length,M=r[F].nice_length,S=r[F].max_chain),T=n,i)},$.deflateSetDictionary=function(e,t,n){var r,a=n,o=0;if(!t||42!=i)return-2;if(a<3)return 0;for(a>f-262&&(o=n-(a=f-262)),c.set(t.subarray(o,o+a),0),z=a,g=a,w=((w=255&c[0])<4||o<0)return-2;if(!t.next_out||!t.next_in&&0!==t.avail_in||666==i&&4!=o)return t.msg=a[4],-2;if(0===t.avail_out)return t.msg=a[7],-5;if(e=t,W=l,l=o,42==i&&(b=8+(u-8<<4)<<8,(S=(F-1&255)>>1)>3&&(S=3),b|=S<<6,0!==z&&(b|=32),i=113,Q((B=b+=31-b%31)>>8&255),Q(255&B)),0!==$.pending){if(e.flush_pending(),0===e.avail_out)return l=-1,0}else if(0===e.avail_in&&o<=W&&4!=o)return e.msg=a[7],-5;if(666==i&&0!==e.avail_in)return t.msg=a[7],-5;if(0!==e.avail_in||0!==D||0!=o&&666!=i){switch(M=-1,r[F].func){case 0:M=function(t){var n,i=65535;for(i>s-5&&(i=s-5);;){if(D<=1){if(fe(),0===D&&0==t)return 0;if(0===D)break}if(z+=D,D=0,n=g+i,(0===z||z>=n)&&(D=z-n,z=n,le(!1),0===e.avail_out))return 0;if(z-g>=f-262&&(le(!1),0===e.avail_out))return 0}return le(4==t),0===e.avail_out?4==t?2:0:4==t?3:1}(o);break;case 1:M=function(t){for(var n,i=0;;){if(D<262){if(fe(),D<262&&0==t)return 0;if(0===D)break}if(D>=3&&(i=65535&p[w=(w<=3)if(n=re(z-E,y-3),D-=y,y<=R&&D>=3){y--;do{z++,i=65535&p[w=(w<=3&&(r=65535&p[w=(w<4096)&&(y=2)),A>=3&&y<=A){i=z+D-3,n=re(z-1-k,A-3),D-=A-1,A-=2;do{++z<=i&&(r=65535&p[w=(w<0&&t.next_in_index!=s&&(r(t.next_in_index),s=t.next_in_index)}while(t.avail_in>0||0===t.avail_out);return a=new Uint8Array(f),o.forEach(function(e){a.set(e,l),l+=e.length}),a}},this.flush=function(){var e,r,a=[],o=0,s=0;do{if(t.next_out_index=0,t.avail_out=n,1!=(e=t.deflate(4))&&0!=e)throw new Error(\"deflating: \"+t.msg);n-t.avail_out>0&&a.push(new Uint8Array(i.subarray(0,t.next_out_index))),s+=t.next_out_index}while(t.avail_in>0||0===t.avail_out);return t.deflateEnd(),r=new Uint8Array(s),a.forEach(function(e){r.set(e,o),o+=e.length}),r}}l.prototype={deflateInit:function(e,t){var n=this;return n.dstate=new s,t||(t=15),n.dstate.deflateInit(n,e,t)},deflate:function(e){var t=this;return t.dstate?t.dstate.deflate(t,e):-2},deflateEnd:function(){var e=this;if(!e.dstate)return-2;var t=e.dstate.deflateEnd();return e.dstate=null,t},deflateParams:function(e,t){var n=this;return n.dstate?n.dstate.deflateParams(n,e,t):-2},deflateSetDictionary:function(e,t){var n=this;return n.dstate?n.dstate.deflateSetDictionary(n,e,t):-2},read_buf:function(e,t,n){var i=this,r=i.avail_in;return r>n&&(r=n),0===r?0:(i.avail_in-=r,e.set(i.next_in.subarray(i.next_in_index,i.next_in_index+r),t),i.next_in_index+=r,i.total_in+=r,r)},flush_pending:function(){var e=this,t=e.dstate.pending;t>e.avail_out&&(t=e.avail_out),0!==t&&(e.next_out.set(e.dstate.pending_buf.subarray(e.dstate.pending_out,e.dstate.pending_out+t),e.next_out_index),e.next_out_index+=t,e.dstate.pending_out+=t,e.total_out+=t,e.avail_out-=t,e.dstate.pending-=t,0===e.dstate.pending&&(e.dstate.pending_out=0))}},self._zipjs_Deflater=f;var u=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],d=[96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,192,80,7,10,0,8,96,0,8,32,0,9,160,0,8,0,0,8,128,0,8,64,0,9,224,80,7,6,0,8,88,0,8,24,0,9,144,83,7,59,0,8,120,0,8,56,0,9,208,81,7,17,0,8,104,0,8,40,0,9,176,0,8,8,0,8,136,0,8,72,0,9,240,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,200,81,7,13,0,8,100,0,8,36,0,9,168,0,8,4,0,8,132,0,8,68,0,9,232,80,7,8,0,8,92,0,8,28,0,9,152,84,7,83,0,8,124,0,8,60,0,9,216,82,7,23,0,8,108,0,8,44,0,9,184,0,8,12,0,8,140,0,8,76,0,9,248,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,196,81,7,11,0,8,98,0,8,34,0,9,164,0,8,2,0,8,130,0,8,66,0,9,228,80,7,7,0,8,90,0,8,26,0,9,148,84,7,67,0,8,122,0,8,58,0,9,212,82,7,19,0,8,106,0,8,42,0,9,180,0,8,10,0,8,138,0,8,74,0,9,244,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,204,81,7,15,0,8,102,0,8,38,0,9,172,0,8,6,0,8,134,0,8,70,0,9,236,80,7,9,0,8,94,0,8,30,0,9,156,84,7,99,0,8,126,0,8,62,0,9,220,82,7,27,0,8,110,0,8,46,0,9,188,0,8,14,0,8,142,0,8,78,0,9,252,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,194,80,7,10,0,8,97,0,8,33,0,9,162,0,8,1,0,8,129,0,8,65,0,9,226,80,7,6,0,8,89,0,8,25,0,9,146,83,7,59,0,8,121,0,8,57,0,9,210,81,7,17,0,8,105,0,8,41,0,9,178,0,8,9,0,8,137,0,8,73,0,9,242,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,202,81,7,13,0,8,101,0,8,37,0,9,170,0,8,5,0,8,133,0,8,69,0,9,234,80,7,8,0,8,93,0,8,29,0,9,154,84,7,83,0,8,125,0,8,61,0,9,218,82,7,23,0,8,109,0,8,45,0,9,186,0,8,13,0,8,141,0,8,77,0,9,250,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,198,81,7,11,0,8,99,0,8,35,0,9,166,0,8,3,0,8,131,0,8,67,0,9,230,80,7,7,0,8,91,0,8,27,0,9,150,84,7,67,0,8,123,0,8,59,0,9,214,82,7,19,0,8,107,0,8,43,0,9,182,0,8,11,0,8,139,0,8,75,0,9,246,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,206,81,7,15,0,8,103,0,8,39,0,9,174,0,8,7,0,8,135,0,8,71,0,9,238,80,7,9,0,8,95,0,8,31,0,9,158,84,7,99,0,8,127,0,8,63,0,9,222,82,7,27,0,8,111,0,8,47,0,9,190,0,8,15,0,8,143,0,8,79,0,9,254,96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,193,80,7,10,0,8,96,0,8,32,0,9,161,0,8,0,0,8,128,0,8,64,0,9,225,80,7,6,0,8,88,0,8,24,0,9,145,83,7,59,0,8,120,0,8,56,0,9,209,81,7,17,0,8,104,0,8,40,0,9,177,0,8,8,0,8,136,0,8,72,0,9,241,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,201,81,7,13,0,8,100,0,8,36,0,9,169,0,8,4,0,8,132,0,8,68,0,9,233,80,7,8,0,8,92,0,8,28,0,9,153,84,7,83,0,8,124,0,8,60,0,9,217,82,7,23,0,8,108,0,8,44,0,9,185,0,8,12,0,8,140,0,8,76,0,9,249,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,197,81,7,11,0,8,98,0,8,34,0,9,165,0,8,2,0,8,130,0,8,66,0,9,229,80,7,7,0,8,90,0,8,26,0,9,149,84,7,67,0,8,122,0,8,58,0,9,213,82,7,19,0,8,106,0,8,42,0,9,181,0,8,10,0,8,138,0,8,74,0,9,245,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,205,81,7,15,0,8,102,0,8,38,0,9,173,0,8,6,0,8,134,0,8,70,0,9,237,80,7,9,0,8,94,0,8,30,0,9,157,84,7,99,0,8,126,0,8,62,0,9,221,82,7,27,0,8,110,0,8,46,0,9,189,0,8,14,0,8,142,0,8,78,0,9,253,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,195,80,7,10,0,8,97,0,8,33,0,9,163,0,8,1,0,8,129,0,8,65,0,9,227,80,7,6,0,8,89,0,8,25,0,9,147,83,7,59,0,8,121,0,8,57,0,9,211,81,7,17,0,8,105,0,8,41,0,9,179,0,8,9,0,8,137,0,8,73,0,9,243,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,203,81,7,13,0,8,101,0,8,37,0,9,171,0,8,5,0,8,133,0,8,69,0,9,235,80,7,8,0,8,93,0,8,29,0,9,155,84,7,83,0,8,125,0,8,61,0,9,219,82,7,23,0,8,109,0,8,45,0,9,187,0,8,13,0,8,141,0,8,77,0,9,251,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,199,81,7,11,0,8,99,0,8,35,0,9,167,0,8,3,0,8,131,0,8,67,0,9,231,80,7,7,0,8,91,0,8,27,0,9,151,84,7,67,0,8,123,0,8,59,0,9,215,82,7,19,0,8,107,0,8,43,0,9,183,0,8,11,0,8,139,0,8,75,0,9,247,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,207,81,7,15,0,8,103,0,8,39,0,9,175,0,8,7,0,8,135,0,8,71,0,9,239,80,7,9,0,8,95,0,8,31,0,9,159,84,7,99,0,8,127,0,8,63,0,9,223,82,7,27,0,8,111,0,8,47,0,9,191,0,8,15,0,8,143,0,8,79,0,9,255],c=[80,5,1,87,5,257,83,5,17,91,5,4097,81,5,5,89,5,1025,85,5,65,93,5,16385,80,5,3,88,5,513,84,5,33,92,5,8193,82,5,9,90,5,2049,86,5,129,192,5,24577,80,5,2,87,5,385,83,5,25,91,5,6145,81,5,7,89,5,1537,85,5,97,93,5,24577,80,5,4,88,5,769,84,5,49,92,5,12289,82,5,13,90,5,3073,86,5,193,192,5,24577],_=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],h=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,112,112],p=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],w=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];function v(){var e,t,n,i,r,a;function o(e,t,o,s,l,f,u,d,c,_,h){var p,w,v,b,x,m,g,y,k,U,z,E,D,A,S;U=0,x=o;do{n[e[t+U]]++,U++,x--}while(0!==x);if(n[0]==o)return u[0]=-1,d[0]=0,0;for(y=d[0],m=1;m<=15&&0===n[m];m++);for(g=m,yx&&(y=x),d[0]=y,A=1<E+y;){if(b++,S=(S=v-(E+=y))>y?y:S,(w=1<<(m=g-E))>p+1&&(w-=p+1,D=g,m1440)return-3;r[b]=z=_[0],_[0]+=S,0!==b?(a[b]=x,i[0]=m,i[1]=y,i[2]=z-r[b-1]-(m=x>>>E-y),c.set(i,3*(r[b-1]+m))):u[0]=z}for(i[1]=g-E,U>=o?i[0]=192:h[U]>>E;m>>=1)x^=m;for(x^=m,k=(1<257?(-3==v?c.msg=\"oversubscribed distance tree\":-5==v?(c.msg=\"incomplete distance tree\",v=-3):-4!=v&&(c.msg=\"empty distance tree with lengths\",v=-3),v):0)}}function b(){var e,t,n,i,r=this,a=0,o=0,s=0,l=0,f=0,d=0,c=0,_=0,h=0,p=0;function w(e,t,n,i,r,a,o,s){var l,f,d,c,_,h,p,w,v,b,x,m,g,y,k,U;p=s.next_in_index,w=s.avail_in,_=o.bitb,h=o.bitk,b=(v=o.write)>=f[U+1],h-=f[U+1],0!=(16&c)){for(g=f[U+2]+(_&u[c&=15]),_>>=c,h-=c;h<15;)w--,_|=(255&s.read_byte(p++))<>=f[U+1],h-=f[U+1],0!=(16&c)){for(c&=15;h>=c,h-=c,b-=g,v>=y)v-(k=v-y)>0&&2>v-k?(o.window[v++]=o.window[k++],o.window[v++]=o.window[k++],g-=2):(o.window.set(o.window.subarray(k,k+2),v),v+=2,k+=2,g-=2);else{k=v-y;do{k+=o.end}while(k<0);if(g>(c=o.end-k)){if(g-=c,v-k>0&&c>v-k)do{o.window[v++]=o.window[k++]}while(0!=--c);else o.window.set(o.window.subarray(k,k+c),v),v+=c,k+=c,c=0;k=0}}if(v-k>0&&g>v-k)do{o.window[v++]=o.window[k++]}while(0!=--g);else o.window.set(o.window.subarray(k,k+g),v),v+=g,k+=g,g=0;break}if(0!=(64&c))return s.msg=\"invalid distance code\",w+=g=h>>3<(g=s.avail_in-w)?h>>3:g,p-=g,h-=g<<3,o.bitb=_,o.bitk=h,s.avail_in=w,s.total_in+=p-s.next_in_index,s.next_in_index=p,o.write=v,-3;l+=f[U+2],c=f[U=3*(d+(l+=_&u[c]))]}break}if(0!=(64&c))return 0!=(32&c)?(w+=g=h>>3<(g=s.avail_in-w)?h>>3:g,p-=g,h-=g<<3,o.bitb=_,o.bitk=h,s.avail_in=w,s.total_in+=p-s.next_in_index,s.next_in_index=p,o.write=v,1):(s.msg=\"invalid literal/length code\",w+=g=h>>3<(g=s.avail_in-w)?h>>3:g,p-=g,h-=g<<3,o.bitb=_,o.bitk=h,s.avail_in=w,s.total_in+=p-s.next_in_index,s.next_in_index=p,o.write=v,-3);if(l+=f[U+2],0===(c=f[U=3*(d+(l+=_&u[c]))])){_>>=f[U+1],h-=f[U+1],o.window[v++]=f[U+2],b--;break}}else _>>=f[U+1],h-=f[U+1],o.window[v++]=f[U+2],b--}while(b>=258&&w>=10);return w+=g=h>>3<(g=s.avail_in-w)?h>>3:g,p-=g,h-=g<<3,o.bitb=_,o.bitk=h,s.avail_in=w,s.total_in+=p-s.next_in_index,s.next_in_index=p,o.write=v,0}r.init=function(r,a,o,s,l,f){e=0,c=r,_=a,n=o,h=s,i=l,p=f,t=null},r.proc=function(r,v,b){var x,m,g,y,k,U,z,E=0,D=0,A=0;for(A=v.next_in_index,y=v.avail_in,E=r.bitb,D=r.bitk,U=(k=r.write)=258&&y>=10&&(r.bitb=E,r.bitk=D,v.avail_in=y,v.total_in+=A-v.next_in_index,v.next_in_index=A,r.write=k,b=w(c,_,n,h,i,p,r,v),A=v.next_in_index,y=v.avail_in,E=r.bitb,D=r.bitk,U=(k=r.write)>>=t[1+(m=3*(o+(E&u[x])))],D-=t[m+1],0===(g=t[m])){l=t[m+2],e=6;break}if(0!=(16&g)){f=15&g,a=t[m+2],e=2;break}if(0==(64&g)){s=g,o=m/3+t[m+2];break}if(0!=(32&g)){e=7;break}return e=9,v.msg=\"invalid literal/length code\",b=-3,r.bitb=E,r.bitk=D,v.avail_in=y,v.total_in+=A-v.next_in_index,v.next_in_index=A,r.write=k,r.inflate_flush(v,b);case 2:for(x=f;D>=x,D-=x,s=_,t=i,o=p,e=3;case 3:for(x=s;D>=t[1+(m=3*(o+(E&u[x])))],D-=t[m+1],0!=(16&(g=t[m]))){f=15&g,d=t[m+2],e=4;break}if(0==(64&g)){s=g,o=m/3+t[m+2];break}return e=9,v.msg=\"invalid distance code\",b=-3,r.bitb=E,r.bitk=D,v.avail_in=y,v.total_in+=A-v.next_in_index,v.next_in_index=A,r.write=k,r.inflate_flush(v,b);case 4:for(x=f;D>=x,D-=x,e=5;case 5:for(z=k-d;z<0;)z+=r.end;for(;0!==a;){if(0===U&&(k==r.end&&0!==r.read&&(U=(k=0)7&&(D-=8,y++,A--),r.write=k,b=r.inflate_flush(v,b),U=(k=r.write)e.avail_out&&(n=e.avail_out),0!==n&&-5==t&&(t=0),e.avail_out-=n,e.total_out+=n,e.next_out.set(i.window.subarray(a,a+n),r),r+=n,(a+=n)==i.end&&(a=0,i.write==i.end&&(i.write=0),(n=i.write-a)>e.avail_out&&(n=e.avail_out),0!==n&&-5==t&&(t=0),e.avail_out-=n,e.total_out+=n,e.next_out.set(i.window.subarray(a,a+n),r),r+=n,a+=n),e.next_out_index=r,i.read=a,t},i.proc=function(e,t){var p,w,b,m,g,y,k,U;for(m=e.next_in_index,g=e.avail_in,w=i.bitb,b=i.bitk,k=(y=i.write)>>1){case 0:w>>>=3,w>>>=p=7&(b-=3),b-=p,r=1;break;case 1:var z=[],E=[],D=[[]],A=[[]];v.inflate_trees_fixed(z,E,D,A),d.init(z[0],E[0],D[0],0,A[0],0),w>>>=3,b-=3,r=6;break;case 2:w>>>=3,b-=3,r=3;break;case 3:return w>>>=3,b-=3,r=9,e.msg=\"invalid block type\",t=-3,i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t)}break;case 1:for(;b<32;){if(0===g)return i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);t=0,g--,w|=(255&e.read_byte(m++))<>>16&65535)!=(65535&w))return r=9,e.msg=\"invalid stored block lengths\",t=-3,i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);a=65535&w,w=b=0,r=0!==a?2:0!==c?7:0;break;case 2:if(0===g)return i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);if(0===k&&(y==i.end&&0!==i.read&&(k=(y=0)g&&(p=g),p>k&&(p=k),i.window.set(e.read_buf(m,p),y),m+=p,g-=p,y+=p,k-=p,0!=(a-=p))break;r=0!==c?7:0;break;case 3:for(;b<14;){if(0===g)return i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);t=0,g--,w|=(255&e.read_byte(m++))<29||(p>>5&31)>29)return r=9,e.msg=\"too many length or distance symbols\",t=-3,i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);if(p=258+(31&p)+(p>>5&31),!n||n.length>>=14,b-=14,s=0,r=4;case 4:for(;s<4+(o>>>10);){for(;b<3;){if(0===g)return i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);t=0,g--,w|=(255&e.read_byte(m++))<>>=3,b-=3}for(;s<19;)n[x[s++]]=0;if(l[0]=7,0!=(p=h.inflate_trees_bits(n,l,f,_,e)))return-3==(t=p)&&(n=null,r=9),i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);s=0,r=5;case 5:for(;!(s>=258+(31&(p=o))+(p>>5&31));){var S,R;for(p=l[0];b>>=p,b-=p,n[s++]=R;else{for(U=18==R?7:R-14,S=18==R?11:3;b>>=p)&u[U],w>>>=U,b-=U,(U=s)+S>258+(31&(p=o))+(p>>5&31)||16==R&&U<1)return n=null,r=9,e.msg=\"invalid bit length repeat\",t=-3,i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);R=16==R?n[U-1]:0;do{n[U++]=R}while(0!=--S);s=U}}f[0]=-1;var F=[],T=[],W=[],M=[];if(F[0]=9,T[0]=6,0!=(p=h.inflate_trees_dynamic(257+(31&(p=o)),1+(p>>5&31),n,F,T,W,M,_,e)))return-3==p&&(n=null,r=9),t=p,i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,i.inflate_flush(e,t);d.init(F[0],T[0],_,W[0],_,M[0]),r=6;case 6:if(i.bitb=w,i.bitk=b,e.avail_in=g,e.total_in+=m-e.next_in_index,e.next_in_index=m,i.write=y,1!=(t=d.proc(i,e,t)))return i.inflate_flush(e,t);if(t=0,d.free(e),m=e.next_in_index,g=e.avail_in,w=i.bitb,b=i.bitk,k=(y=i.write)15?(e.inflateEnd(n),-2):(e.wbits=i,n.istate.blocks=new m(n,1<>4)>e.istate.wbits){e.istate.mode=13,e.msg=\"invalid window size\",e.istate.marker=5;break}e.istate.mode=1;case 1:if(0===e.avail_in)return n;if(n=t,e.avail_in--,e.total_in++,i=255&e.read_byte(e.next_in_index++),((e.istate.method<<8)+i)%31!=0){e.istate.mode=13,e.msg=\"incorrect header check\",e.istate.marker=5;break}if(0==(32&i)){e.istate.mode=7;break}e.istate.mode=2;case 2:if(0===e.avail_in)return n;n=t,e.avail_in--,e.total_in++,e.istate.need=(255&e.read_byte(e.next_in_index++))<<24&4278190080,e.istate.mode=3;case 3:if(0===e.avail_in)return n;n=t,e.avail_in--,e.total_in++,e.istate.need+=(255&e.read_byte(e.next_in_index++))<<16&16711680,e.istate.mode=4;case 4:if(0===e.avail_in)return n;n=t,e.avail_in--,e.total_in++,e.istate.need+=(255&e.read_byte(e.next_in_index++))<<8&65280,e.istate.mode=5;case 5:return 0===e.avail_in?n:(n=t,e.avail_in--,e.total_in++,e.istate.need+=255&e.read_byte(e.next_in_index++),e.istate.mode=6,2);case 6:return e.istate.mode=13,e.msg=\"need dictionary\",e.istate.marker=0,-2;case 7:if(-3==(n=e.istate.blocks.proc(e,n))){e.istate.mode=13,e.istate.marker=0;break}if(0==n&&(n=t),1!=n)return n;n=t,e.istate.blocks.reset(e,e.istate.was),e.istate.mode=12;case 12:return 1;case 13:return-3;default:return-2}},e.inflateSetDictionary=function(e,t,n){var i=0,r=n;return e&&e.istate&&6==e.istate.mode?(r>=1<0&&e.next_in_index!=l&&(r(e.next_in_index),l=e.next_in_index)}while(e.avail_in>0||0===e.avail_out);return o=new Uint8Array(u),s.forEach(function(e){o.set(e,f),f+=e.length}),o}},this.flush=function(){e.inflateEnd()}}k.prototype={inflateInit:function(e){var t=this;return t.istate=new y,e||(e=15),t.istate.inflateInit(t,e)},inflate:function(e){var t=this;return t.istate?t.istate.inflate(t,e):-2},inflateEnd:function(){var e=this;if(!e.istate)return-2;var t=e.istate.inflateEnd(e);return e.istate=null,t},inflateSync:function(){var e=this;return e.istate?e.istate.inflateSync(e):-2},inflateSetDictionary:function(e,t){var n=this;return n.istate?n.istate.inflateSetDictionary(n,e,t):-2},read_byte:function(e){return this.next_in.subarray(e,e+1)[0]},read_buf:function(e,t){return this.next_in.subarray(e,e+t)}},self._zipjs_Inflater=U;var z,E=\"File format is not recognized.\",D=\"Error while reading zip file.\";try{z=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function A(){this.crc=-1}function S(){}function R(e,t){var n,i;return n=new ArrayBuffer(e),i=new Uint8Array(n),t&&i.set(t,0),{buffer:n,array:i,view:new DataView(n)}}function F(){}function T(e){var t,n=this;n.size=0,n.init=function(i,r){var a=new Blob([e],{type:\"text/plain\"});(t=new M(a)).init(function(){n.size=t.size,i()},r)},n.readUint8Array=function(e,n,i,r){t.readUint8Array(e,n,i,r)}}function W(e){var t,n=this;n.size=0,n.init=function(i){for(var r=e.length;\"=\"==e.charAt(r-1);)r--;t=e.indexOf(\",\")+1,n.size=Math.floor(.75*(r-t)),i()},n.readUint8Array=function(n,i,r){var a,o=R(i),s=4*Math.floor(n/3),l=4*Math.ceil((n+i)/3),f=self.atob(e.substring(s+t,l+t)),u=n-3*Math.floor(s/4);for(a=u;ae.size)throw new RangeError(\"offset:\"+t+\", length:\"+n+\", size:\"+e.size);return e.slice?e.slice(t,t+n):e.webkitSlice?e.webkitSlice(t,t+n):e.mozSlice?e.mozSlice(t,t+n):e.msSlice?e.msSlice(t,t+n):void 0}(e,t,n))}catch(e){r(e)}}}function B(){}function I(e){var t,n=this;n.init=function(e){t=new Blob([],{type:\"text/plain\"}),e()},n.writeUint8Array=function(e,n){t=new Blob([t,z?e:e.buffer],{type:\"text/plain\"}),n()},n.getData=function(n,i){var r=new FileReader;r.onload=function(e){n(e.target.result)},r.onerror=i,r.readAsText(t,e)}}function C(e){var t=this,n=\"\",i=\"\";t.init=function(t){n+=\"data:\"+(e||\"\")+\";base64,\",t()},t.writeUint8Array=function(e,t){var r,a=i.length,o=i;for(i=\"\",r=0;r<3*Math.floor((a+e.length)/3)-a;r++)o+=String.fromCharCode(e[r]);for(;r2?n+=self.btoa(o):i=o,t()},t.getData=function(e){e(n+self.btoa(i))}}function L(e){var t,n=this;n.init=function(n){t=new Blob([],{type:e}),n()},n.writeUint8Array=function(n,i){t=new Blob([t,z?n:n.buffer],{type:e}),i()},n.getData=function(e){e(t)}}function P(e,t,n,i,r,a,o,s,l,f){var u,d,c,_=0,h=t.sn;function p(){e.removeEventListener(\"message\",w,!1),s(d,c)}function w(t){var n=t.data,r=n.data,s=n.error;if(s)return s.toString=function(){return\"Error: \"+this.message},void l(s);if(n.sn===h)switch(\"number\"==typeof n.codecTime&&(e.codecTime+=n.codecTime),\"number\"==typeof n.crcTime&&(e.crcTime+=n.crcTime),n.type){case\"append\":r?(d+=r.length,i.writeUint8Array(r,function(){v()},f)):v();break;case\"flush\":c=n.crc,r?(d+=r.length,i.writeUint8Array(r,function(){p()},f)):p();break;case\"progress\":o&&o(u+n.loaded,a);break;case\"importScripts\":case\"newTask\":case\"echo\":break;default:console.warn(\"zip.js:launchWorkerProcess: unknown message: \",n)}}function v(){(u=524288*_)<=a?n.readUint8Array(r+u,Math.min(524288,a-u),function(n){o&&o(u,a);var i=0===u?t:{sn:h};i.type=\"append\",i.data=n;try{e.postMessage(i,[n.buffer])}catch(t){e.postMessage(i)}_++},l):e.postMessage({sn:h,type:\"flush\"})}d=0,e.addEventListener(\"message\",w,!1),v()}function Z(e,t,n,i,r,a,o,s,l,f){var u,d=0,c=0,_=\"input\"===a,h=\"output\"===a,p=new A;!function a(){var w;if((u=524288*d)127?r[n-128]:String.fromCharCode(n);return i}function O(e){return decodeURIComponent(escape(e))}function V(e){var t,n=\"\";for(t=0;t>16,n=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&n)>>11,(2016&n)>>5,2*(31&n),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((i||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(n+10,!0),e.compressedSize=t.view.getUint32(n+14,!0),e.uncompressedSize=t.view.getUint32(n+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(n+22,!0),e.extraFieldLength=t.view.getUint16(n+24,!0)):r(\"File is using Zip64 (4gb+ file size).\")):r(\"File contains encrypted entry.\")}function $(e){return unescape(encodeURIComponent(e))}function G(e){var t,n=[];for(t=0;t>>8^n[255&(t^e[i])];this.crc=t},A.prototype.get=function(){return~this.crc},A.prototype.table=function(){var e,t,n,i=[];for(e=0;e<256;e++){for(n=e,t=0;t<8;t++)1&n?n=n>>>1^3988292384:n>>>=1;i[e]=n}return i}(),S.prototype.append=function(e,t){return e},S.prototype.flush=function(){},(T.prototype=new F).constructor=T,(W.prototype=new F).constructor=W,(M.prototype=new F).constructor=M,B.prototype.getData=function(e){e(this.data)},(I.prototype=new B).constructor=I,(C.prototype=new B).constructor=C,(L.prototype=new B).constructor=L;var H={deflater:[\"z-worker.js\",\"deflate.js\"],inflater:[\"z-worker.js\",\"inflate.js\"]};function Y(e,t,n){if(null===K.workerScripts||null===K.workerScriptsPath){var i,r,a;if(K.workerScripts){if(i=K.workerScripts[e],!Array.isArray(i))return void n(new Error(\"zip.workerScripts.\"+e+\" is not an array!\"));r=i,a=document.createElement(\"a\"),i=r.map(function(e){return a.href=e,a.href})}else(i=H[e].slice(0))[0]=(K.workerScriptsPath||\"\")+i[0];var o=new Worker(i[0]);o.codecTime=o.crcTime=0,o.postMessage({type:\"importScripts\",scripts:i.slice(1)}),o.addEventListener(\"message\",function e(i){var r=i.data;if(r.error)return o.terminate(),void n(r.error);\"importScripts\"===r.type&&(o.removeEventListener(\"message\",e),o.removeEventListener(\"error\",s),t(o))}),o.addEventListener(\"error\",s)}else n(new Error(\"Either zip.workerScripts or zip.workerScriptsPath may be set, not both.\"));function s(e){o.terminate(),n(e)}}function J(e){console.error(e)}const K={Reader:F,Writer:B,BlobReader:M,Data64URIReader:W,TextReader:T,BlobWriter:L,Data64URIWriter:C,TextWriter:I,createReader:function(e,t,n){e.init(function(){!function(e,t,n){var i=0;function r(){}r.prototype.getData=function(t,r,a,o){var s=this;function l(e,i){o&&!function(e){var t=R(4);return t.view.setUint32(0,e),s.crc32==t.view.getUint32(0)}(i)?n(\"CRC failed.\"):t.getData(function(e){r(e)})}function f(e){n(e||\"Error while reading file data.\")}function u(e){n(e||\"Error while writing file data.\")}e.readUint8Array(s.offset,30,function(r){var d,c=R(r.length,r);1347093252==c.view.getUint32(0)?(q(s,c,4,!1,n),d=s.offset+30+s.filenameLength+s.extraFieldLength,t.init(function(){0===s.compressionMethod?N(s._worker,i++,e,t,d,s.compressedSize,o,l,a,f,u):function(e,t,n,i,r,a,o,s,l,f,u){var d=o?\"output\":\"none\";K.useWebWorkers?P(e,{sn:t,codecClass:\"_zipjs_Inflater\",crcType:d},n,i,r,a,l,s,f,u):Z(new U,n,i,r,a,d,l,s,f,u)}(s._worker,i++,e,t,d,s.compressedSize,o,l,a,f,u)},u)):n(E)},f)};var a={getEntries:function(t){var i=this._worker;!function(t){function i(i,r){e.readUint8Array(e.size-i,i,function(e){for(var n=e.length-22;n>=0;n--)if(80===e[n]&&75===e[n+1]&&5===e[n+2]&&6===e[n+3])return void t(new DataView(e.buffer,n,22));r()},function(){n(D)})}e.size<22?n(E):i(22,function(){i(Math.min(65558,e.size),function(){n(E)})})}(function(a){var o,s;o=a.getUint32(16,!0),s=a.getUint16(8,!0),o<0||o>=e.size?n(E):e.readUint8Array(o,e.size-o,function(e){var a,o,l,f,u=0,d=[],c=R(e.length,e);for(a=0;a0){var i=n.map(function(e){return e.webkitGetAsEntry()}).filter(function(e){return null!==e});i.length>0&&(i[0].name.match(/\\.zip$/)?this._loadZip(n[0].getAsFile()):this._loadNextEntry(new Map,i))}else 1===t.length&&t[0].name.match(/\\.zip$/)&&this._loadZip(t[0]),this._emit(\"drop\",{files:new Map(t.map(function(e){return[e.name,e]}))});else this._fail(\"Required drag-and-drop APIs are not supported in this browser.\")},t._onDragover=function(e){e.stopPropagation(),e.preventDefault(),e.dataTransfer.dropEffect=\"copy\"},t._onSelect=function(e){this._emit(\"dropstart\");var t=[].slice.call(this.inputEl.files);if(1===t.length&&this._isZip(t[0]))this._loadZip(t[0]);else{var n=new Map;t.forEach(function(e){return n.set(e.webkitRelativePath||e.name,e)}),this._emit(\"drop\",{files:n})}},t._loadNextEntry=function(e,t){var n=this,i=t.pop();if(i)if(i.isFile)i.file(function(r){e.set(i.fullPath,r),n._loadNextEntry(e,t)},function(){return console.error(\"Could not load file: %s\",i.fullPath)});else if(i.isDirectory){var r=i.createReader();r.readEntries(function i(a){a.length?(t=t.concat(a),r.readEntries(i)):n._loadNextEntry(e,t)})}else console.warn(\"Unknown asset type: \"+i.fullPath),this._loadNextEntry(e,t);else this._emit(\"drop\",{files:e})},t._loadZip=function(e){var t=this,n=[],i=new Map,r=new be.FS,a=function e(t){t.directory?t.children.forEach(e):\".\"!==t.name[0]&&n.push(new Promise(function(e){t.getData(new K.BlobWriter,function(n){n.name=t.name,i.set(t.getFullname(),n),e()})}))};r.importBlob(e,function(){a(r.root),Promise.all(n).then(function(){t._emit(\"drop\",{files:i,archive:e})})})},t._isZip=function(e){return\"application/zip\"===e.type||e.name.match(/\\.zip$/)},t._fail=function(e){this._emit(\"droperror\",{message:e})},e}();export{xe as SimpleDropzone};\n//# sourceMappingURL=simple-dropzone.module.js.map\n","/**\n * Copyright 2004-present Facebook. All Rights Reserved.\n *\n * @providesModule UserAgent_DEPRECATED\n */\n\n/**\n * Provides entirely client-side User Agent and OS detection. You should prefer\n * the non-deprecated UserAgent module when possible, which exposes our\n * authoritative server-side PHP-based detection to the client.\n *\n * Usage is straightforward:\n *\n * if (UserAgent_DEPRECATED.ie()) {\n * // IE\n * }\n *\n * You can also do version checks:\n *\n * if (UserAgent_DEPRECATED.ie() >= 7) {\n * // IE7 or better\n * }\n *\n * The browser functions will return NaN if the browser does not match, so\n * you can also do version compares the other way:\n *\n * if (UserAgent_DEPRECATED.ie() < 7) {\n * // IE6 or worse\n * }\n *\n * Note that the version is a float and may include a minor version number,\n * so you should always use range operators to perform comparisons, not\n * strict equality.\n *\n * **Note:** You should **strongly** prefer capability detection to browser\n * version detection where it's reasonable:\n *\n * http://www.quirksmode.org/js/support.html\n *\n * Further, we have a large number of mature wrapper functions and classes\n * which abstract away many browser irregularities. Check the documentation,\n * grep for things, or ask on javascript@lists.facebook.com before writing yet\n * another copy of \"event || window.event\".\n *\n */\n\nvar _populated = false;\n\n// Browsers\nvar _ie, _firefox, _opera, _webkit, _chrome;\n\n// Actual IE browser for compatibility mode\nvar _ie_real_version;\n\n// Platforms\nvar _osx, _windows, _linux, _android;\n\n// Architectures\nvar _win64;\n\n// Devices\nvar _iphone, _ipad, _native;\n\nvar _mobile;\n\nfunction _populate() {\n if (_populated) {\n return;\n }\n\n _populated = true;\n\n // To work around buggy JS libraries that can't handle multi-digit\n // version numbers, Opera 10's user agent string claims it's Opera\n // 9, then later includes a Version/X.Y field:\n //\n // Opera/9.80 (foo) Presto/2.2.15 Version/10.10\n var uas = navigator.userAgent;\n var agent = /(?:MSIE.(\\d+\\.\\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\\d+\\.\\d+))|(?:Opera(?:.+Version.|.)(\\d+\\.\\d+))|(?:AppleWebKit.(\\d+(?:\\.\\d+)?))|(?:Trident\\/\\d+\\.\\d+.*rv:(\\d+\\.\\d+))/.exec(uas);\n var os = /(Mac OS X)|(Windows)|(Linux)/.exec(uas);\n\n _iphone = /\\b(iPhone|iP[ao]d)/.exec(uas);\n _ipad = /\\b(iP[ao]d)/.exec(uas);\n _android = /Android/i.exec(uas);\n _native = /FBAN\\/\\w+;/i.exec(uas);\n _mobile = /Mobile/i.exec(uas);\n\n // Note that the IE team blog would have you believe you should be checking\n // for 'Win64; x64'. But MSDN then reveals that you can actually be coming\n // from either x64 or ia64; so ultimately, you should just check for Win64\n // as in indicator of whether you're in 64-bit IE. 32-bit IE on 64-bit\n // Windows will send 'WOW64' instead.\n _win64 = !!(/Win64/.exec(uas));\n\n if (agent) {\n _ie = agent[1] ? parseFloat(agent[1]) : (\n agent[5] ? parseFloat(agent[5]) : NaN);\n // IE compatibility mode\n if (_ie && document && document.documentMode) {\n _ie = document.documentMode;\n }\n // grab the \"true\" ie version from the trident token if available\n var trident = /(?:Trident\\/(\\d+.\\d+))/.exec(uas);\n _ie_real_version = trident ? parseFloat(trident[1]) + 4 : _ie;\n\n _firefox = agent[2] ? parseFloat(agent[2]) : NaN;\n _opera = agent[3] ? parseFloat(agent[3]) : NaN;\n _webkit = agent[4] ? parseFloat(agent[4]) : NaN;\n if (_webkit) {\n // We do not add the regexp to the above test, because it will always\n // match 'safari' only since 'AppleWebKit' appears before 'Chrome' in\n // the userAgent string.\n agent = /(?:Chrome\\/(\\d+\\.\\d+))/.exec(uas);\n _chrome = agent && agent[1] ? parseFloat(agent[1]) : NaN;\n } else {\n _chrome = NaN;\n }\n } else {\n _ie = _firefox = _opera = _chrome = _webkit = NaN;\n }\n\n if (os) {\n if (os[1]) {\n // Detect OS X version. If no version number matches, set _osx to true.\n // Version examples: 10, 10_6_1, 10.7\n // Parses version number as a float, taking only first two sets of\n // digits. If only one set of digits is found, returns just the major\n // version number.\n var ver = /(?:Mac OS X (\\d+(?:[._]\\d+)?))/.exec(uas);\n\n _osx = ver ? parseFloat(ver[1].replace('_', '.')) : true;\n } else {\n _osx = false;\n }\n _windows = !!os[2];\n _linux = !!os[3];\n } else {\n _osx = _windows = _linux = false;\n }\n}\n\nvar UserAgent_DEPRECATED = {\n\n /**\n * Check if the UA is Internet Explorer.\n *\n *\n * @return float|NaN Version number (if match) or NaN.\n */\n ie: function() {\n return _populate() || _ie;\n },\n\n /**\n * Check if we're in Internet Explorer compatibility mode.\n *\n * @return bool true if in compatibility mode, false if\n * not compatibility mode or not ie\n */\n ieCompatibilityMode: function() {\n return _populate() || (_ie_real_version > _ie);\n },\n\n\n /**\n * Whether the browser is 64-bit IE. Really, this is kind of weak sauce; we\n * only need this because Skype can't handle 64-bit IE yet. We need to remove\n * this when we don't need it -- tracked by #601957.\n */\n ie64: function() {\n return UserAgent_DEPRECATED.ie() && _win64;\n },\n\n /**\n * Check if the UA is Firefox.\n *\n *\n * @return float|NaN Version number (if match) or NaN.\n */\n firefox: function() {\n return _populate() || _firefox;\n },\n\n\n /**\n * Check if the UA is Opera.\n *\n *\n * @return float|NaN Version number (if match) or NaN.\n */\n opera: function() {\n return _populate() || _opera;\n },\n\n\n /**\n * Check if the UA is WebKit.\n *\n *\n * @return float|NaN Version number (if match) or NaN.\n */\n webkit: function() {\n return _populate() || _webkit;\n },\n\n /**\n * For Push\n * WILL BE REMOVED VERY SOON. Use UserAgent_DEPRECATED.webkit\n */\n safari: function() {\n return UserAgent_DEPRECATED.webkit();\n },\n\n /**\n * Check if the UA is a Chrome browser.\n *\n *\n * @return float|NaN Version number (if match) or NaN.\n */\n chrome : function() {\n return _populate() || _chrome;\n },\n\n\n /**\n * Check if the user is running Windows.\n *\n * @return bool `true' if the user's OS is Windows.\n */\n windows: function() {\n return _populate() || _windows;\n },\n\n\n /**\n * Check if the user is running Mac OS X.\n *\n * @return float|bool Returns a float if a version number is detected,\n * otherwise true/false.\n */\n osx: function() {\n return _populate() || _osx;\n },\n\n /**\n * Check if the user is running Linux.\n *\n * @return bool `true' if the user's OS is some flavor of Linux.\n */\n linux: function() {\n return _populate() || _linux;\n },\n\n /**\n * Check if the user is running on an iPhone or iPod platform.\n *\n * @return bool `true' if the user is running some flavor of the\n * iPhone OS.\n */\n iphone: function() {\n return _populate() || _iphone;\n },\n\n mobile: function() {\n return _populate() || (_iphone || _ipad || _android || _mobile);\n },\n\n nativeApp: function() {\n // webviews inside of the native apps\n return _populate() || _native;\n },\n\n android: function() {\n return _populate() || _android;\n },\n\n ipad: function() {\n return _populate() || _ipad;\n }\n};\n\nmodule.exports = UserAgent_DEPRECATED;\n","/**\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule ExecutionEnvironment\n */\n\n/*jslint evil: true */\n\n'use strict';\n\nvar canUseDOM = !!(\n typeof window !== 'undefined' &&\n window.document &&\n window.document.createElement\n);\n\n/**\n * Simple, lightweight module assisting with the detection and context of\n * Worker. Helps avoid circular dependencies and allows code to reason about\n * whether or not they are in a Worker, even if they never include the main\n * `ReactWorker` dependency.\n */\nvar ExecutionEnvironment = {\n\n canUseDOM: canUseDOM,\n\n canUseWorkers: typeof Worker !== 'undefined',\n\n canUseEventListeners:\n canUseDOM && !!(window.addEventListener || window.attachEvent),\n\n canUseViewport: canUseDOM && !!window.screen,\n\n isInWorker: !canUseDOM // For now, this is true - might change in the future.\n\n};\n\nmodule.exports = ExecutionEnvironment;\n","/**\n * Copyright 2013-2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule isEventSupported\n */\n\n'use strict';\n\nvar ExecutionEnvironment = require('./ExecutionEnvironment');\n\nvar useHasFeature;\nif (ExecutionEnvironment.canUseDOM) {\n useHasFeature =\n document.implementation &&\n document.implementation.hasFeature &&\n // always returns true in newer browsers as per the standard.\n // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature\n document.implementation.hasFeature('', '') !== true;\n}\n\n/**\n * Checks if an event is supported in the current execution environment.\n *\n * NOTE: This will not work correctly for non-generic events such as `change`,\n * `reset`, `load`, `error`, and `select`.\n *\n * Borrows from Modernizr.\n *\n * @param {string} eventNameSuffix Event name, e.g. \"click\".\n * @param {?boolean} capture Check if the capture phase is supported.\n * @return {boolean} True if the event is supported.\n * @internal\n * @license Modernizr 3.0.0pre (Custom Build) | MIT\n */\nfunction isEventSupported(eventNameSuffix, capture) {\n if (!ExecutionEnvironment.canUseDOM ||\n capture && !('addEventListener' in document)) {\n return false;\n }\n\n var eventName = 'on' + eventNameSuffix;\n var isSupported = eventName in document;\n\n if (!isSupported) {\n var element = document.createElement('div');\n element.setAttribute(eventName, 'return;');\n isSupported = typeof element[eventName] === 'function';\n }\n\n if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') {\n // This is the only way to test support for the `wheel` event in IE9+.\n isSupported = document.implementation.hasFeature('Events.wheel', '3.0');\n }\n\n return isSupported;\n}\n\nmodule.exports = isEventSupported;\n","/**\n * Copyright (c) 2015, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n * @providesModule normalizeWheel\n * @typechecks\n */\n\n'use strict';\n\nvar UserAgent_DEPRECATED = require('./UserAgent_DEPRECATED');\n\nvar isEventSupported = require('./isEventSupported');\n\n\n// Reasonable defaults\nvar PIXEL_STEP = 10;\nvar LINE_HEIGHT = 40;\nvar PAGE_HEIGHT = 800;\n\n/**\n * Mouse wheel (and 2-finger trackpad) support on the web sucks. It is\n * complicated, thus this doc is long and (hopefully) detailed enough to answer\n * your questions.\n *\n * If you need to react to the mouse wheel in a predictable way, this code is\n * like your bestest friend. * hugs *\n *\n * As of today, there are 4 DOM event types you can listen to:\n *\n * 'wheel' -- Chrome(31+), FF(17+), IE(9+)\n * 'mousewheel' -- Chrome, IE(6+), Opera, Safari\n * 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother!\n * 'DOMMouseScroll' -- FF(0.9.7+) since 2003\n *\n * So what to do? The is the best:\n *\n * normalizeWheel.getEventType();\n *\n * In your event callback, use this code to get sane interpretation of the\n * deltas. This code will return an object with properties:\n *\n * spinX -- normalized spin speed (use for zoom) - x plane\n * spinY -- \" - y plane\n * pixelX -- normalized distance (to pixels) - x plane\n * pixelY -- \" - y plane\n *\n * Wheel values are provided by the browser assuming you are using the wheel to\n * scroll a web page by a number of lines or pixels (or pages). Values can vary\n * significantly on different platforms and browsers, forgetting that you can\n * scroll at different speeds. Some devices (like trackpads) emit more events\n * at smaller increments with fine granularity, and some emit massive jumps with\n * linear speed or acceleration.\n *\n * This code does its best to normalize the deltas for you:\n *\n * - spin is trying to normalize how far the wheel was spun (or trackpad\n * dragged). This is super useful for zoom support where you want to\n * throw away the chunky scroll steps on the PC and make those equal to\n * the slow and smooth tiny steps on the Mac. Key data: This code tries to\n * resolve a single slow step on a wheel to 1.\n *\n * - pixel is normalizing the desired scroll delta in pixel units. You'll\n * get the crazy differences between browsers, but at least it'll be in\n * pixels!\n *\n * - positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This\n * should translate to positive value zooming IN, negative zooming OUT.\n * This matches the newer 'wheel' event.\n *\n * Why are there spinX, spinY (or pixels)?\n *\n * - spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn\n * with a mouse. It results in side-scrolling in the browser by default.\n *\n * - spinY is what you expect -- it's the classic axis of a mouse wheel.\n *\n * - I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and\n * probably is by browsers in conjunction with fancy 3D controllers .. but\n * you know.\n *\n * Implementation info:\n *\n * Examples of 'wheel' event if you scroll slowly (down) by one step with an\n * average mouse:\n *\n * OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120)\n * OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12)\n * OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A)\n * Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120)\n * Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)\n *\n * On the trackpad:\n *\n * OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6)\n * OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)\n *\n * On other/older browsers.. it's more complicated as there can be multiple and\n * also missing delta values.\n *\n * The 'wheel' event is more standard:\n *\n * http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n *\n * The basics is that it includes a unit, deltaMode (pixels, lines, pages), and\n * deltaX, deltaY and deltaZ. Some browsers provide other values to maintain\n * backward compatibility with older events. Those other values help us\n * better normalize spin speed. Example of what the browsers provide:\n *\n * | event.wheelDelta | event.detail\n * ------------------+------------------+--------------\n * Safari v5/OS X | -120 | 0\n * Safari v5/Win7 | -120 | 0\n * Chrome v17/OS X | -120 | 0\n * Chrome v17/Win7 | -120 | 0\n * IE9/Win7 | -120 | undefined\n * Firefox v4/OS X | undefined | 1\n * Firefox v4/Win7 | undefined | 3\n *\n */\nfunction normalizeWheel(/*object*/ event) /*object*/ {\n var sX = 0, sY = 0, // spinX, spinY\n pX = 0, pY = 0; // pixelX, pixelY\n\n // Legacy\n if ('detail' in event) { sY = event.detail; }\n if ('wheelDelta' in event) { sY = -event.wheelDelta / 120; }\n if ('wheelDeltaY' in event) { sY = -event.wheelDeltaY / 120; }\n if ('wheelDeltaX' in event) { sX = -event.wheelDeltaX / 120; }\n\n // side scrolling on FF with DOMMouseScroll\n if ( 'axis' in event && event.axis === event.HORIZONTAL_AXIS ) {\n sX = sY;\n sY = 0;\n }\n\n pX = sX * PIXEL_STEP;\n pY = sY * PIXEL_STEP;\n\n if ('deltaY' in event) { pY = event.deltaY; }\n if ('deltaX' in event) { pX = event.deltaX; }\n\n if ((pX || pY) && event.deltaMode) {\n if (event.deltaMode == 1) { // delta in LINE units\n pX *= LINE_HEIGHT;\n pY *= LINE_HEIGHT;\n } else { // delta in PAGE units\n pX *= PAGE_HEIGHT;\n pY *= PAGE_HEIGHT;\n }\n }\n\n // Fall-back if spin cannot be determined\n if (pX && !sX) { sX = (pX < 1) ? -1 : 1; }\n if (pY && !sY) { sY = (pY < 1) ? -1 : 1; }\n\n return { spinX : sX,\n spinY : sY,\n pixelX : pX,\n pixelY : pY };\n}\n\n\n/**\n * The best combination if you prefer spinX + spinY normalization. It favors\n * the older DOMMouseScroll for Firefox, as FF does not include wheelDelta with\n * 'wheel' event, making spin speed determination impossible.\n */\nnormalizeWheel.getEventType = function() /*string*/ {\n return (UserAgent_DEPRECATED.firefox())\n ? 'DOMMouseScroll'\n : (isEventSupported('wheel'))\n ? 'wheel'\n : 'mousewheel';\n};\n\nmodule.exports = normalizeWheel;\n","module.exports = require('./src/normalizeWheel.js');\n","import { Observable, merge, fromEvent } from 'rxjs';\nimport { map, filter, startWith, takeUntil, mergeMap, pairwise } from 'rxjs/operators';\nimport { GltfState } from '../../gltf-source/GltfState/gltf_state.js';\n\nimport { SimpleDropzone } from 'simple-dropzone';\nimport { vec2 } from 'gl-matrix';\n\nimport normalizeWheel from 'normalize-wheel';\n\n// this class wraps all the observables for the gltf sample viewer state\n// the data streams coming out of this should match the data required in GltfState\n// as close as possible\nclass UIModel\n{\n constructor(app, modelPathProvider, environments)\n {\n this.app = app;\n this.pathProvider = modelPathProvider;\n\n this.app.models = this.pathProvider.getAllKeys();\n\n const queryString = window.location.search;\n const urlParams = new URLSearchParams(queryString);\n const modelURL = urlParams.get(\"model\");\n\n let dropdownGltfChanged = undefined;\n if (modelURL === null)\n {\n dropdownGltfChanged = app.modelChanged$.pipe(\n map(data => data.event.msg),\n startWith(\"Sphere\"),\n map(value => {\n app.flavours = this.pathProvider.getModelFlavours(value);\n app.selectedFlavour = \"glTF\";\n return this.pathProvider.resolve(value, app.selectedFlavour);\n }),\n map( value => ({mainFile: value, additionalFiles: undefined})),\n );\n } else {\n dropdownGltfChanged = app.modelChanged$.pipe(\n map(data => data.event.msg),\n map(value => {\n app.flavours = this.pathProvider.getModelFlavours(value);\n app.selectedFlavour = \"glTF\";\n return this.pathProvider.resolve(value, app.selectedFlavour);\n }),\n map( value => ({mainFile: value, additionalFiles: undefined})),\n );\n } \n\n const dropdownFlavourChanged = app.flavourChanged$.pipe(\n map(data => data.event.msg),\n map(value => {\n return this.pathProvider.resolve(app.selectedModel, value);\n }),\n map( value => ({mainFile: value, additionalFiles: undefined})),\n );\n\n this.scene = app.sceneChanged$.pipe(map(data => data.event.msg));\n this.camera = app.cameraChanged$.pipe(map(data => data.event.msg));\n this.environmentRotation = app.environmentRotationChanged$.pipe(map(data => data.event.msg));\n this.app.environments = environments;\n const selectedEnvironment = app.$watchAsObservable('selectedEnvironment').pipe(\n map(event => event.newValue),\n map( environmentName => this.app.environments[environmentName].hdr_path)\n );\n const initialEnvironment = \"base_environment\";\n this.app.selectedEnvironment = initialEnvironment;\n\n this.app.tonemaps = Object.keys(GltfState.ToneMaps).map((key) => {\n return {title: GltfState.ToneMaps[key]};\n });\n this.tonemap = app.tonemapChanged$.pipe(\n map(data => data.event.msg),\n startWith(GltfState.ToneMaps.ACES_HILL_EXPOSURE_BOOST)\n );\n\n this.app.debugchannels = Object.keys(GltfState.DebugOutput).map((key) => {\n return {title: GltfState.DebugOutput[key]};\n });\n this.debugchannel = app.debugchannelChanged$.pipe(\n map(data => data.event.msg),\n startWith(GltfState.DebugOutput.NONE)\n );\n\n this.exposure = app.exposureChanged$.pipe(map(data => data.event.msg));\n this.skinningEnabled = app.skinningChanged$.pipe(map(data => data.event.msg));\n this.morphingEnabled = app.morphingChanged$.pipe(map(data => data.event.msg));\n this.clearcoatEnabled = app.clearcoatChanged$.pipe(map(data => data.event.msg));\n this.sheenEnabled = app.sheenChanged$.pipe(map(data => data.event.msg));\n this.transmissionEnabled = app.transmissionChanged$.pipe(map(data => data.event.msg));\n this.volumeEnabled = app.$watchAsObservable('volumeEnabled').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.iorEnabled = app.$watchAsObservable('iorEnabled').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.iridescenceEnabled = app.$watchAsObservable('iridescenceEnabled').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.specularEnabled = app.$watchAsObservable('specularEnabled').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.emissiveStrengthEnabled = app.$watchAsObservable('emissiveStrengthEnabled').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.iblEnabled = app.iblChanged$.pipe(map(data => data.event.msg));\n this.iblIntensity = app.iblIntensityChanged$.pipe(map(data => data.event.msg));\n this.punctualLightsEnabled = app.punctualLightsChanged$.pipe(map(data => data.event.msg));\n this.renderEnvEnabled = app.$watchAsObservable('renderEnv').pipe(\n map( ({ newValue, oldValue }) => newValue));\n this.blurEnvEnabled = app.blurEnvChanged$.pipe(map(data => data.event.msg));\n this.addEnvironment = app.$watchAsObservable('uploadedHDR').pipe(\n map(event => event.newValue)\n );\n this.captureCanvas = app.captureCanvas$.pipe(map(event => event.newValue));\n this.cameraValuesExport = app.cameraExport$.pipe(map(event => event.newValue),);\n\n const initialClearColor = \"#9C9C9C\";\n this.app.clearColor = initialClearColor;\n this.clearColor = app.colorChanged$.pipe(\n filter(value => value.event !== undefined),\n map(data => data.event.msg),\n startWith(initialClearColor),\n map(hex => {\n // convert hex string to rgb values\n var result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result ? [\n parseInt(result[1], 16),\n parseInt(result[2], 16),\n parseInt(result[3], 16),\n 255\n ] : null;\n })\n );\n\n this.animationPlay = app.animationPlayChanged$.pipe(map(data => data.event.msg));\n this.activeAnimations = app.$watchAsObservable('selectedAnimations').pipe(\n map( ({ newValue, oldValue }) => newValue)\n );\n\n const canvas = document.getElementById(\"canvas\");\n this.registerDropZoneUIHandle(canvas);\n const inputObservables = UIModel.getInputObservables(canvas, this.app);\n this.model = merge(dropdownGltfChanged, dropdownFlavourChanged, inputObservables.gltfDropped);\n this.hdr = merge(inputObservables.hdrDropped, selectedEnvironment, this.addEnvironment).pipe(\n startWith(environments[initialEnvironment].hdr_path)\n );\n\n const hdrUIChange = merge(inputObservables.hdrDropped, this.addEnvironment);\n hdrUIChange.subscribe( hdrPath => {\n this.app.environments[hdrPath.name] = {\n title: hdrPath.name,\n hdr_path: hdrPath,\n };\n this.app.selectedEnvironment = hdrPath.name;\n });\n\n this.variant = app.variantChanged$.pipe(map(data => data.event.msg));\n\n this.model.subscribe(() => {\n // remove last filename\n if(this.app.models[this.app.models.length -1] === this.lastDroppedFilename)\n {\n this.app.models.pop();\n this.lastDroppedFilename = undefined;\n }\n });\n\n let dropedGLtfFileName = inputObservables.gltfDropped.pipe(\n map( (data) => {\n return data.mainFile.name;\n })\n );\n\n if (modelURL !== null){\n let loadFromUrlObservable = new Observable(subscriber => { subscriber.next({mainFile: modelURL, additionalFiles: undefined});});\n dropedGLtfFileName = merge(dropedGLtfFileName, loadFromUrlObservable.pipe(map((data) => {return data.mainFile;} )));\n this.model = merge(this.model, loadFromUrlObservable);\n }\n\n dropedGLtfFileName.subscribe( (filename) => {\n if(filename !== undefined)\n {\n filename = filename.split('/').pop();\n let fileExtension = filename.split('.').pop();;\n filename = filename.substr(0, filename.lastIndexOf('.'));\n\n this.app.models.push(filename);\n this.app.selectedModel = filename;\n this.lastDroppedFilename = filename;\n\n app.flavours = [fileExtension];\n app.selectedFlavour = fileExtension;\n }\n });\n\n this.orbit = inputObservables.orbit;\n this.pan = inputObservables.pan;\n this.zoom = inputObservables.zoom;\n }\n\n // Updated method\n updatePathProvider(newPathProvider) {\n this.pathProvider = newPathProvider;\n this.app.models = this.pathProvider.getAllKeys();\n \n // If there's a currently selected model, try to find a matching one in the new provider\n if (this.app.selectedModel) {\n const currentModelName = this.app.selectedModel;\n const availableModels = this.pathProvider.getAllKeys();\n \n // Check if the current model exists in the new path provider\n if (availableModels.includes(currentModelName)) {\n // If it exists, force a reload\n this.app.modelChanged$.next({event:{ msg: currentModelName }});\n } else {\n // If it doesn't exist, select the first available model\n if (availableModels.length > 0) {\n this.app.modelChanged$.next({event:{ msg: availableModels[0] }});\n } else {\n this.app.selectedModel = null;\n }\n }\n }\n }\n\n // app has to be the vuejs app instance\n static getInputObservables(inputDomElement, app)\n {\n const observables = {};\n\n const simpleDropzoneObservabel = new Observable(subscriber => {\n const dropCtrl = new SimpleDropzone(inputDomElement, inputDomElement);\n dropCtrl.on('drop', ({files}) => {\n app.showDropDownOverlay = false;\n subscriber.next(files);\n });\n dropCtrl.on('droperror', () => {\n app.showDropDownOverlay = false;\n subscriber.error();\n });\n });\n observables.filesDropped = simpleDropzoneObservabel.pipe(\n map(files => Array.from(files.values()))\n );\n\n observables.gltfDropped = observables.filesDropped.pipe(\n // filter out any non .gltf or .glb files\n\n map( (files) => {\n // restructure the data by separating mainFile (gltf/glb) from additionalFiles\n const mainFile = files.find( (file) => file.name.endsWith(\".glb\") || file.name.endsWith(\".gltf\"));\n const additionalFiles = files.filter( (file) => file !== mainFile);\n return {mainFile: mainFile, additionalFiles: additionalFiles};\n }),\n filter(files => files.mainFile !== undefined),\n );\n observables.hdrDropped = observables.filesDropped.pipe(\n map( (files) => {\n // extract only the hdr file from the stream of files\n return files.find( (file) => file.name.endsWith(\".hdr\"));\n }),\n filter(file => file !== undefined),\n );\n\n const move = fromEvent(document, 'mousemove');\n const mousedown = fromEvent(inputDomElement, 'mousedown');\n const cancelMouse = merge(fromEvent(document, 'mouseup'), fromEvent(document, 'mouseleave'));\n\n const mouseOrbit = mousedown.pipe(\n filter( event => event.button === 0 && event.shiftKey === false),\n mergeMap(() => move.pipe(takeUntil(cancelMouse))),\n map( mouse => ({deltaPhi: mouse.movementX, deltaTheta: mouse.movementY }))\n );\n\n const mousePan = mousedown.pipe(\n filter( event => event.button === 1 || event.shiftKey === true),\n mergeMap(() => move.pipe(takeUntil(cancelMouse))),\n map( mouse => ({deltaX: mouse.movementX, deltaY: mouse.movementY }))\n );\n\n const smbZoom = mousedown.pipe(\n filter( event => event.button === 2),\n mergeMap(() => move.pipe(takeUntil(cancelMouse))),\n map( mouse => ({deltaZoom: mouse.movementY }))\n );\n const wheelZoom = fromEvent(inputDomElement, 'wheel').pipe(\n map(wheelEvent => normalizeWheel(wheelEvent)),\n map(normalizedZoom => ({deltaZoom: normalizedZoom.spinY }))\n );\n inputDomElement.addEventListener('onscroll', event => event.preventDefault(), false);\n const mouseZoom = merge(smbZoom, wheelZoom);\n\n const touchmove = fromEvent(document, 'touchmove');\n const touchstart = fromEvent(inputDomElement, 'touchstart');\n const touchend = merge(fromEvent(inputDomElement, 'touchend'), fromEvent(inputDomElement, 'touchcancel'));\n \n const touchOrbit = touchstart.pipe(\n filter( event => event.touches.length === 1),\n mergeMap(() => touchmove.pipe(takeUntil(touchend))),\n map( event => event.touches[0]),\n pairwise(),\n map( ([oldTouch, newTouch]) => {\n return { \n deltaPhi: newTouch.pageX - oldTouch.pageX, \n deltaTheta: newTouch.pageY - oldTouch.pageY \n };\n })\n );\n\n const touchZoom = touchstart.pipe(\n filter( event => event.touches.length === 2),\n mergeMap(() => touchmove.pipe(takeUntil(touchend))),\n map( event => {\n const pos1 = vec2.fromValues(event.touches[0].pageX, event.touches[0].pageY);\n const pos2 = vec2.fromValues(event.touches[1].pageX, event.touches[1].pageY);\n return vec2.dist(pos1, pos2);\n }),\n pairwise(),\n map( ([oldDist, newDist]) => ({ deltaZoom: newDist - oldDist }))\n );\n\n inputDomElement.addEventListener('ontouchmove', event => event.preventDefault(), false);\n\n observables.orbit = merge(mouseOrbit, touchOrbit);\n observables.pan = mousePan;\n observables.zoom = merge(mouseZoom, touchZoom);\n\n // disable context menu\n inputDomElement.oncontextmenu = () => false;\n\n return observables;\n }\n\n registerDropZoneUIHandle(inputDomElement)\n {\n const self = this;\n inputDomElement.addEventListener('dragenter', function(event) {\n self.app.showDropDownOverlay = true;\n });\n inputDomElement.addEventListener('dragleave', function(event) {\n self.app.showDropDownOverlay = false;\n });\n }\n\n attachGltfLoaded(glTFLoadedStateObservable)\n {\n const gltfLoadedAndInit = glTFLoadedStateObservable.pipe(\n map( state => state.gltf )\n );\n\n // update scenes\n const sceneIndices = gltfLoadedAndInit.pipe(\n map( (gltf) => {\n return gltf.scenes.map( (scene, index) => {\n let name = scene.name;\n if(name === \"\" || name === undefined)\n {\n name = index;\n }\n return {title: name, index: index};\n });\n })\n );\n sceneIndices.subscribe( (scenes) => {\n this.app.scenes = scenes;\n });\n\n const loadedSceneIndex = glTFLoadedStateObservable.pipe(\n map( (state) => state.sceneIndex)\n );\n loadedSceneIndex.subscribe( (scene) => {\n this.app.selectedScene = scene;\n });\n\n // update cameras\n this.attachCameraChangeObservable(glTFLoadedStateObservable);\n\n const variants = gltfLoadedAndInit.pipe(\n map( (gltf) => {\n if(gltf.variants !== undefined)\n {\n return gltf.variants.map( (variant, index) => {\n return {title: variant.name};\n });\n }\n return [];\n }),\n map(variants => {\n // Add a \"None\" variant to the beginning\n variants.unshift({title: \"None\"});\n return variants;\n })\n );\n variants.subscribe( (variants) => {\n this.app.materialVariants = variants;\n });\n\n gltfLoadedAndInit.subscribe(\n (_) => {this.app.setAnimationState(true);\n }\n );\n\n const xmpData = gltfLoadedAndInit.pipe(\n map( (gltf) => {\n if(gltf.extensions !== undefined && gltf.extensions.KHR_xmp_json_ld !== undefined)\n {\n if(gltf.asset.extensions !== undefined && gltf.asset.extensions.KHR_xmp_json_ld !== undefined)\n {\n let xmpPacket = gltf.extensions.KHR_xmp_json_ld.packets[gltf.asset.extensions.KHR_xmp_json_ld.packet];\n return xmpPacket;\n }\n }\n return [];\n })\n );\n xmpData.subscribe( (xmpData) => {\n this.app.xmp = xmpData;\n });\n\n const animations = gltfLoadedAndInit.pipe(\n map( gltf => gltf.animations.map( (anim, index) => {\n let name = anim.name;\n if (name === undefined || name === \"\")\n {\n name = index;\n }\n return {\n title: name,\n index: index\n };\n }))\n );\n animations.subscribe( animations => {\n this.app.animations = animations;\n });\n\n glTFLoadedStateObservable.pipe(\n map( state => state.animationIndices)\n ).subscribe( animationIndices => {\n this.app.selectedAnimations = animationIndices;\n });\n }\n\n updateStatistics(statisticsUpdateObservable)\n {\n statisticsUpdateObservable.subscribe(\n data => {\n let statistics = {};\n statistics[\"Mesh Count\"] = data.meshCount;\n statistics[\"Triangle Count\"] = data.faceCount;\n statistics[\"Opaque Material Count\"] = data.opaqueMaterialsCount;\n statistics[\"Transparent Material Count\"] = data.transparentMaterialsCount;\n this.app.statistics = statistics;\n }\n );\n }\n\n disabledAnimations(disabledAnimationsObservable)\n {\n disabledAnimationsObservable.subscribe(\n data => { this.app.disabledAnimations = data; }\n );\n }\n\n attachCameraChangeObservable(sceneChangeObservable)\n {\n const cameraIndices = sceneChangeObservable.pipe(\n map( (state) => {\n let gltf = state.gltf;\n let cameraIndices = [{title: \"User Camera\", index: -1}];\n if (gltf.scenes[state.sceneIndex] !== undefined)\n {\n cameraIndices.push(...gltf.cameras.map( (camera, index) => {\n if(gltf.scenes[state.sceneIndex].includesNode(gltf, camera.node))\n {\n let name = camera.name;\n if(name === \"\" || name === undefined)\n {\n name = index;\n }\n return {title: name, index: index};\n }\n }));\n }\n cameraIndices = cameraIndices.filter(function(el) {\n return el !== undefined;\n });\n return cameraIndices;\n })\n );\n cameraIndices.subscribe( (cameras) => {\n this.app.cameras = cameras;\n });\n const loadedCameraIndex = sceneChangeObservable.pipe(\n map( (state) => {\n return state.cameraIndex;\n })\n );\n loadedCameraIndex.subscribe( index => {\n if(index === undefined)\n {\n index = -1;\n }\n this.app.selectedCamera = index;\n });\n }\n\n copyToClipboard(text) {\n var dummy = document.createElement(\"textarea\");\n document.body.appendChild(dummy);\n dummy.value = text;\n dummy.select();\n document.execCommand(\"copy\");\n document.body.removeChild(dummy);\n }\n\n goToLoadingState() {\n this.app.goToLoadingState();\n }\n exitLoadingState()\n {\n this.app.exitLoadingState();\n }\n}\n\nexport { UIModel };\n","/*!\n * Vue.js v2.7.16\n * (c) 2014-2023 Evan You\n * Released under the MIT License.\n */\nvar emptyObject = Object.freeze({});\nvar isArray = Array.isArray;\n// These helpers produce better VM code in JS engines due to their\n// explicitness and function inlining.\nfunction isUndef(v) {\n return v === undefined || v === null;\n}\nfunction isDef(v) {\n return v !== undefined && v !== null;\n}\nfunction isTrue(v) {\n return v === true;\n}\nfunction isFalse(v) {\n return v === false;\n}\n/**\n * Check if value is primitive.\n */\nfunction isPrimitive(value) {\n return (typeof value === 'string' ||\n typeof value === 'number' ||\n // $flow-disable-line\n typeof value === 'symbol' ||\n typeof value === 'boolean');\n}\nfunction isFunction(value) {\n return typeof value === 'function';\n}\n/**\n * Quick object check - this is primarily used to tell\n * objects from primitive values when we know the value\n * is a JSON-compliant type.\n */\nfunction isObject(obj) {\n return obj !== null && typeof obj === 'object';\n}\n/**\n * Get the raw type string of a value, e.g., [object Object].\n */\nvar _toString = Object.prototype.toString;\nfunction toRawType(value) {\n return _toString.call(value).slice(8, -1);\n}\n/**\n * Strict object type check. Only returns true\n * for plain JavaScript objects.\n */\nfunction isPlainObject(obj) {\n return _toString.call(obj) === '[object Object]';\n}\nfunction isRegExp(v) {\n return _toString.call(v) === '[object RegExp]';\n}\n/**\n * Check if val is a valid array index.\n */\nfunction isValidArrayIndex(val) {\n var n = parseFloat(String(val));\n return n >= 0 && Math.floor(n) === n && isFinite(val);\n}\nfunction isPromise(val) {\n return (isDef(val) &&\n typeof val.then === 'function' &&\n typeof val.catch === 'function');\n}\n/**\n * Convert a value to a string that is actually rendered.\n */\nfunction toString(val) {\n return val == null\n ? ''\n : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString)\n ? JSON.stringify(val, replacer, 2)\n : String(val);\n}\nfunction replacer(_key, val) {\n // avoid circular deps from v3\n if (val && val.__v_isRef) {\n return val.value;\n }\n return val;\n}\n/**\n * Convert an input value to a number for persistence.\n * If the conversion fails, return original string.\n */\nfunction toNumber(val) {\n var n = parseFloat(val);\n return isNaN(n) ? val : n;\n}\n/**\n * Make a map and return a function for checking if a key\n * is in that map.\n */\nfunction makeMap(str, expectsLowerCase) {\n var map = Object.create(null);\n var list = str.split(',');\n for (var i = 0; i < list.length; i++) {\n map[list[i]] = true;\n }\n return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; };\n}\n/**\n * Check if a tag is a built-in tag.\n */\nvar isBuiltInTag = makeMap('slot,component', true);\n/**\n * Check if an attribute is a reserved attribute.\n */\nvar isReservedAttribute = makeMap('key,ref,slot,slot-scope,is');\n/**\n * Remove an item from an array.\n */\nfunction remove$2(arr, item) {\n var len = arr.length;\n if (len) {\n // fast path for the only / last item\n if (item === arr[len - 1]) {\n arr.length = len - 1;\n return;\n }\n var index = arr.indexOf(item);\n if (index > -1) {\n return arr.splice(index, 1);\n }\n }\n}\n/**\n * Check whether an object has the property.\n */\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\nfunction hasOwn(obj, key) {\n return hasOwnProperty.call(obj, key);\n}\n/**\n * Create a cached version of a pure function.\n */\nfunction cached(fn) {\n var cache = Object.create(null);\n return function cachedFn(str) {\n var hit = cache[str];\n return hit || (cache[str] = fn(str));\n };\n}\n/**\n * Camelize a hyphen-delimited string.\n */\nvar camelizeRE = /-(\\w)/g;\nvar camelize = cached(function (str) {\n return str.replace(camelizeRE, function (_, c) { return (c ? c.toUpperCase() : ''); });\n});\n/**\n * Capitalize a string.\n */\nvar capitalize = cached(function (str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n});\n/**\n * Hyphenate a camelCase string.\n */\nvar hyphenateRE = /\\B([A-Z])/g;\nvar hyphenate = cached(function (str) {\n return str.replace(hyphenateRE, '-$1').toLowerCase();\n});\n/**\n * Simple bind polyfill for environments that do not support it,\n * e.g., PhantomJS 1.x. Technically, we don't need this anymore\n * since native bind is now performant enough in most browsers.\n * But removing it would mean breaking code that was able to run in\n * PhantomJS 1.x, so this must be kept for backward compatibility.\n */\n/* istanbul ignore next */\nfunction polyfillBind(fn, ctx) {\n function boundFn(a) {\n var l = arguments.length;\n return l\n ? l > 1\n ? fn.apply(ctx, arguments)\n : fn.call(ctx, a)\n : fn.call(ctx);\n }\n boundFn._length = fn.length;\n return boundFn;\n}\nfunction nativeBind(fn, ctx) {\n return fn.bind(ctx);\n}\n// @ts-expect-error bind cannot be `undefined`\nvar bind$1 = Function.prototype.bind ? nativeBind : polyfillBind;\n/**\n * Convert an Array-like object to a real Array.\n */\nfunction toArray(list, start) {\n start = start || 0;\n var i = list.length - start;\n var ret = new Array(i);\n while (i--) {\n ret[i] = list[i + start];\n }\n return ret;\n}\n/**\n * Mix properties into target object.\n */\nfunction extend(to, _from) {\n for (var key in _from) {\n to[key] = _from[key];\n }\n return to;\n}\n/**\n * Merge an Array of Objects into a single Object.\n */\nfunction toObject(arr) {\n var res = {};\n for (var i = 0; i < arr.length; i++) {\n if (arr[i]) {\n extend(res, arr[i]);\n }\n }\n return res;\n}\n/* eslint-disable no-unused-vars */\n/**\n * Perform no operation.\n * Stubbing args to make Flow happy without leaving useless transpiled code\n * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/).\n */\nfunction noop(a, b, c) { }\n/**\n * Always return false.\n */\nvar no = function (a, b, c) { return false; };\n/* eslint-enable no-unused-vars */\n/**\n * Return the same value.\n */\nvar identity = function (_) { return _; };\n/**\n * Generate a string containing static keys from compiler modules.\n */\nfunction genStaticKeys$1(modules) {\n return modules\n .reduce(function (keys, m) { return keys.concat(m.staticKeys || []); }, [])\n .join(',');\n}\n/**\n * Check if two values are loosely equal - that is,\n * if they are plain objects, do they have the same shape?\n */\nfunction looseEqual(a, b) {\n if (a === b)\n return true;\n var isObjectA = isObject(a);\n var isObjectB = isObject(b);\n if (isObjectA && isObjectB) {\n try {\n var isArrayA = Array.isArray(a);\n var isArrayB = Array.isArray(b);\n if (isArrayA && isArrayB) {\n return (a.length === b.length &&\n a.every(function (e, i) {\n return looseEqual(e, b[i]);\n }));\n }\n else if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n else if (!isArrayA && !isArrayB) {\n var keysA = Object.keys(a);\n var keysB = Object.keys(b);\n return (keysA.length === keysB.length &&\n keysA.every(function (key) {\n return looseEqual(a[key], b[key]);\n }));\n }\n else {\n /* istanbul ignore next */\n return false;\n }\n }\n catch (e) {\n /* istanbul ignore next */\n return false;\n }\n }\n else if (!isObjectA && !isObjectB) {\n return String(a) === String(b);\n }\n else {\n return false;\n }\n}\n/**\n * Return the first index at which a loosely equal value can be\n * found in the array (if value is a plain object, the array must\n * contain an object of the same shape), or -1 if it is not present.\n */\nfunction looseIndexOf(arr, val) {\n for (var i = 0; i < arr.length; i++) {\n if (looseEqual(arr[i], val))\n return i;\n }\n return -1;\n}\n/**\n * Ensure a function is called only once.\n */\nfunction once(fn) {\n var called = false;\n return function () {\n if (!called) {\n called = true;\n fn.apply(this, arguments);\n }\n };\n}\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is#polyfill\nfunction hasChanged(x, y) {\n if (x === y) {\n return x === 0 && 1 / x !== 1 / y;\n }\n else {\n return x === x || y === y;\n }\n}\n\nvar SSR_ATTR = 'data-server-rendered';\nvar ASSET_TYPES = ['component', 'directive', 'filter'];\nvar LIFECYCLE_HOOKS = [\n 'beforeCreate',\n 'created',\n 'beforeMount',\n 'mounted',\n 'beforeUpdate',\n 'updated',\n 'beforeDestroy',\n 'destroyed',\n 'activated',\n 'deactivated',\n 'errorCaptured',\n 'serverPrefetch',\n 'renderTracked',\n 'renderTriggered'\n];\n\nvar config = {\n /**\n * Option merge strategies (used in core/util/options)\n */\n // $flow-disable-line\n optionMergeStrategies: Object.create(null),\n /**\n * Whether to suppress warnings.\n */\n silent: false,\n /**\n * Show production mode tip message on boot?\n */\n productionTip: process.env.NODE_ENV !== 'production',\n /**\n * Whether to enable devtools\n */\n devtools: process.env.NODE_ENV !== 'production',\n /**\n * Whether to record perf\n */\n performance: false,\n /**\n * Error handler for watcher errors\n */\n errorHandler: null,\n /**\n * Warn handler for watcher warns\n */\n warnHandler: null,\n /**\n * Ignore certain custom elements\n */\n ignoredElements: [],\n /**\n * Custom user key aliases for v-on\n */\n // $flow-disable-line\n keyCodes: Object.create(null),\n /**\n * Check if a tag is reserved so that it cannot be registered as a\n * component. This is platform-dependent and may be overwritten.\n */\n isReservedTag: no,\n /**\n * Check if an attribute is reserved so that it cannot be used as a component\n * prop. This is platform-dependent and may be overwritten.\n */\n isReservedAttr: no,\n /**\n * Check if a tag is an unknown element.\n * Platform-dependent.\n */\n isUnknownElement: no,\n /**\n * Get the namespace of an element\n */\n getTagNamespace: noop,\n /**\n * Parse the real tag name for the specific platform.\n */\n parsePlatformTagName: identity,\n /**\n * Check if an attribute must be bound using property, e.g. value\n * Platform-dependent.\n */\n mustUseProp: no,\n /**\n * Perform updates asynchronously. Intended to be used by Vue Test Utils\n * This will significantly reduce performance if set to false.\n */\n async: true,\n /**\n * Exposed for legacy reasons\n */\n _lifecycleHooks: LIFECYCLE_HOOKS\n};\n\n/**\n * unicode letters used for parsing html tags, component names and property paths.\n * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname\n * skipping \\u10000-\\uEFFFF due to it freezing up PhantomJS\n */\nvar unicodeRegExp = /a-zA-Z\\u00B7\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u203F-\\u2040\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD/;\n/**\n * Check if a string starts with $ or _\n */\nfunction isReserved(str) {\n var c = (str + '').charCodeAt(0);\n return c === 0x24 || c === 0x5f;\n}\n/**\n * Define a property.\n */\nfunction def(obj, key, val, enumerable) {\n Object.defineProperty(obj, key, {\n value: val,\n enumerable: !!enumerable,\n writable: true,\n configurable: true\n });\n}\n/**\n * Parse simple path.\n */\nvar bailRE = new RegExp(\"[^\".concat(unicodeRegExp.source, \".$_\\\\d]\"));\nfunction parsePath(path) {\n if (bailRE.test(path)) {\n return;\n }\n var segments = path.split('.');\n return function (obj) {\n for (var i = 0; i < segments.length; i++) {\n if (!obj)\n return;\n obj = obj[segments[i]];\n }\n return obj;\n };\n}\n\n// can we use __proto__?\nvar hasProto = '__proto__' in {};\n// Browser environment sniffing\nvar inBrowser = typeof window !== 'undefined';\nvar UA = inBrowser && window.navigator.userAgent.toLowerCase();\nvar isIE = UA && /msie|trident/.test(UA);\nvar isIE9 = UA && UA.indexOf('msie 9.0') > 0;\nvar isEdge = UA && UA.indexOf('edge/') > 0;\nUA && UA.indexOf('android') > 0;\nvar isIOS = UA && /iphone|ipad|ipod|ios/.test(UA);\nUA && /chrome\\/\\d+/.test(UA) && !isEdge;\nUA && /phantomjs/.test(UA);\nvar isFF = UA && UA.match(/firefox\\/(\\d+)/);\n// Firefox has a \"watch\" function on Object.prototype...\n// @ts-expect-error firebox support\nvar nativeWatch = {}.watch;\nvar supportsPassive = false;\nif (inBrowser) {\n try {\n var opts = {};\n Object.defineProperty(opts, 'passive', {\n get: function () {\n /* istanbul ignore next */\n supportsPassive = true;\n }\n }); // https://github.com/facebook/flow/issues/285\n window.addEventListener('test-passive', null, opts);\n }\n catch (e) { }\n}\n// this needs to be lazy-evaled because vue may be required before\n// vue-server-renderer can set VUE_ENV\nvar _isServer;\nvar isServerRendering = function () {\n if (_isServer === undefined) {\n /* istanbul ignore if */\n if (!inBrowser && typeof global !== 'undefined') {\n // detect presence of vue-server-renderer and avoid\n // Webpack shimming the process\n _isServer =\n global['process'] && global['process'].env.VUE_ENV === 'server';\n }\n else {\n _isServer = false;\n }\n }\n return _isServer;\n};\n// detect devtools\nvar devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__;\n/* istanbul ignore next */\nfunction isNative(Ctor) {\n return typeof Ctor === 'function' && /native code/.test(Ctor.toString());\n}\nvar hasSymbol = typeof Symbol !== 'undefined' &&\n isNative(Symbol) &&\n typeof Reflect !== 'undefined' &&\n isNative(Reflect.ownKeys);\nvar _Set; // $flow-disable-line\n/* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) {\n // use native Set when available.\n _Set = Set;\n}\nelse {\n // a non-standard Set polyfill that only works with primitive keys.\n _Set = /** @class */ (function () {\n function Set() {\n this.set = Object.create(null);\n }\n Set.prototype.has = function (key) {\n return this.set[key] === true;\n };\n Set.prototype.add = function (key) {\n this.set[key] = true;\n };\n Set.prototype.clear = function () {\n this.set = Object.create(null);\n };\n return Set;\n }());\n}\n\nvar currentInstance = null;\n/**\n * This is exposed for compatibility with v3 (e.g. some functions in VueUse\n * relies on it). Do not use this internally, just use `currentInstance`.\n *\n * @internal this function needs manual type declaration because it relies\n * on previously manually authored types from Vue 2\n */\nfunction getCurrentInstance() {\n return currentInstance && { proxy: currentInstance };\n}\n/**\n * @internal\n */\nfunction setCurrentInstance(vm) {\n if (vm === void 0) { vm = null; }\n if (!vm)\n currentInstance && currentInstance._scope.off();\n currentInstance = vm;\n vm && vm._scope.on();\n}\n\n/**\n * @internal\n */\nvar VNode = /** @class */ (function () {\n function VNode(tag, data, children, text, elm, context, componentOptions, asyncFactory) {\n this.tag = tag;\n this.data = data;\n this.children = children;\n this.text = text;\n this.elm = elm;\n this.ns = undefined;\n this.context = context;\n this.fnContext = undefined;\n this.fnOptions = undefined;\n this.fnScopeId = undefined;\n this.key = data && data.key;\n this.componentOptions = componentOptions;\n this.componentInstance = undefined;\n this.parent = undefined;\n this.raw = false;\n this.isStatic = false;\n this.isRootInsert = true;\n this.isComment = false;\n this.isCloned = false;\n this.isOnce = false;\n this.asyncFactory = asyncFactory;\n this.asyncMeta = undefined;\n this.isAsyncPlaceholder = false;\n }\n Object.defineProperty(VNode.prototype, \"child\", {\n // DEPRECATED: alias for componentInstance for backwards compat.\n /* istanbul ignore next */\n get: function () {\n return this.componentInstance;\n },\n enumerable: false,\n configurable: true\n });\n return VNode;\n}());\nvar createEmptyVNode = function (text) {\n if (text === void 0) { text = ''; }\n var node = new VNode();\n node.text = text;\n node.isComment = true;\n return node;\n};\nfunction createTextVNode(val) {\n return new VNode(undefined, undefined, undefined, String(val));\n}\n// optimized shallow clone\n// used for static nodes and slot nodes because they may be reused across\n// multiple renders, cloning them avoids errors when DOM manipulations rely\n// on their elm reference.\nfunction cloneVNode(vnode) {\n var cloned = new VNode(vnode.tag, vnode.data, \n // #7975\n // clone children array to avoid mutating original in case of cloning\n // a child.\n vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory);\n cloned.ns = vnode.ns;\n cloned.isStatic = vnode.isStatic;\n cloned.key = vnode.key;\n cloned.isComment = vnode.isComment;\n cloned.fnContext = vnode.fnContext;\n cloned.fnOptions = vnode.fnOptions;\n cloned.fnScopeId = vnode.fnScopeId;\n cloned.asyncMeta = vnode.asyncMeta;\n cloned.isCloned = true;\n return cloned;\n}\n\n/* not type checking this file because flow doesn't play well with Proxy */\nvar initProxy;\nif (process.env.NODE_ENV !== 'production') {\n var allowedGlobals_1 = makeMap('Infinity,undefined,NaN,isFinite,isNaN,' +\n 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' +\n 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,' +\n 'require' // for Webpack/Browserify\n );\n var warnNonPresent_1 = function (target, key) {\n warn$2(\"Property or method \\\"\".concat(key, \"\\\" is not defined on the instance but \") +\n 'referenced during render. Make sure that this property is reactive, ' +\n 'either in the data option, or for class-based components, by ' +\n 'initializing the property. ' +\n 'See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target);\n };\n var warnReservedPrefix_1 = function (target, key) {\n warn$2(\"Property \\\"\".concat(key, \"\\\" must be accessed with \\\"$data.\").concat(key, \"\\\" because \") +\n 'properties starting with \"$\" or \"_\" are not proxied in the Vue instance to ' +\n 'prevent conflicts with Vue internals. ' +\n 'See: https://v2.vuejs.org/v2/api/#data', target);\n };\n var hasProxy_1 = typeof Proxy !== 'undefined' && isNative(Proxy);\n if (hasProxy_1) {\n var isBuiltInModifier_1 = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact');\n config.keyCodes = new Proxy(config.keyCodes, {\n set: function (target, key, value) {\n if (isBuiltInModifier_1(key)) {\n warn$2(\"Avoid overwriting built-in modifier in config.keyCodes: .\".concat(key));\n return false;\n }\n else {\n target[key] = value;\n return true;\n }\n }\n });\n }\n var hasHandler_1 = {\n has: function (target, key) {\n var has = key in target;\n var isAllowed = allowedGlobals_1(key) ||\n (typeof key === 'string' &&\n key.charAt(0) === '_' &&\n !(key in target.$data));\n if (!has && !isAllowed) {\n if (key in target.$data)\n warnReservedPrefix_1(target, key);\n else\n warnNonPresent_1(target, key);\n }\n return has || !isAllowed;\n }\n };\n var getHandler_1 = {\n get: function (target, key) {\n if (typeof key === 'string' && !(key in target)) {\n if (key in target.$data)\n warnReservedPrefix_1(target, key);\n else\n warnNonPresent_1(target, key);\n }\n return target[key];\n }\n };\n initProxy = function initProxy(vm) {\n if (hasProxy_1) {\n // determine which proxy handler to use\n var options = vm.$options;\n var handlers = options.render && options.render._withStripped ? getHandler_1 : hasHandler_1;\n vm._renderProxy = new Proxy(vm, handlers);\n }\n else {\n vm._renderProxy = vm;\n }\n };\n}\n\n/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\n\nvar uid$2 = 0;\nvar pendingCleanupDeps = [];\nvar cleanupDeps = function () {\n for (var i = 0; i < pendingCleanupDeps.length; i++) {\n var dep = pendingCleanupDeps[i];\n dep.subs = dep.subs.filter(function (s) { return s; });\n dep._pending = false;\n }\n pendingCleanupDeps.length = 0;\n};\n/**\n * A dep is an observable that can have multiple\n * directives subscribing to it.\n * @internal\n */\nvar Dep = /** @class */ (function () {\n function Dep() {\n // pending subs cleanup\n this._pending = false;\n this.id = uid$2++;\n this.subs = [];\n }\n Dep.prototype.addSub = function (sub) {\n this.subs.push(sub);\n };\n Dep.prototype.removeSub = function (sub) {\n // #12696 deps with massive amount of subscribers are extremely slow to\n // clean up in Chromium\n // to workaround this, we unset the sub for now, and clear them on\n // next scheduler flush.\n this.subs[this.subs.indexOf(sub)] = null;\n if (!this._pending) {\n this._pending = true;\n pendingCleanupDeps.push(this);\n }\n };\n Dep.prototype.depend = function (info) {\n if (Dep.target) {\n Dep.target.addDep(this);\n if (process.env.NODE_ENV !== 'production' && info && Dep.target.onTrack) {\n Dep.target.onTrack(__assign({ effect: Dep.target }, info));\n }\n }\n };\n Dep.prototype.notify = function (info) {\n // stabilize the subscriber list first\n var subs = this.subs.filter(function (s) { return s; });\n if (process.env.NODE_ENV !== 'production' && !config.async) {\n // subs aren't sorted in scheduler if not running async\n // we need to sort them now to make sure they fire in correct\n // order\n subs.sort(function (a, b) { return a.id - b.id; });\n }\n for (var i = 0, l = subs.length; i < l; i++) {\n var sub = subs[i];\n if (process.env.NODE_ENV !== 'production' && info) {\n sub.onTrigger &&\n sub.onTrigger(__assign({ effect: subs[i] }, info));\n }\n sub.update();\n }\n };\n return Dep;\n}());\n// The current target watcher being evaluated.\n// This is globally unique because only one watcher\n// can be evaluated at a time.\nDep.target = null;\nvar targetStack = [];\nfunction pushTarget(target) {\n targetStack.push(target);\n Dep.target = target;\n}\nfunction popTarget() {\n targetStack.pop();\n Dep.target = targetStack[targetStack.length - 1];\n}\n\n/*\n * not type checking this file because flow doesn't play well with\n * dynamically accessing methods on Array prototype\n */\nvar arrayProto = Array.prototype;\nvar arrayMethods = Object.create(arrayProto);\nvar methodsToPatch = [\n 'push',\n 'pop',\n 'shift',\n 'unshift',\n 'splice',\n 'sort',\n 'reverse'\n];\n/**\n * Intercept mutating methods and emit events\n */\nmethodsToPatch.forEach(function (method) {\n // cache original method\n var original = arrayProto[method];\n def(arrayMethods, method, function mutator() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var result = original.apply(this, args);\n var ob = this.__ob__;\n var inserted;\n switch (method) {\n case 'push':\n case 'unshift':\n inserted = args;\n break;\n case 'splice':\n inserted = args.slice(2);\n break;\n }\n if (inserted)\n ob.observeArray(inserted);\n // notify change\n if (process.env.NODE_ENV !== 'production') {\n ob.dep.notify({\n type: \"array mutation\" /* TriggerOpTypes.ARRAY_MUTATION */,\n target: this,\n key: method\n });\n }\n else {\n ob.dep.notify();\n }\n return result;\n });\n});\n\nvar arrayKeys = Object.getOwnPropertyNames(arrayMethods);\nvar NO_INITIAL_VALUE = {};\n/**\n * In some cases we may want to disable observation inside a component's\n * update computation.\n */\nvar shouldObserve = true;\nfunction toggleObserving(value) {\n shouldObserve = value;\n}\n// ssr mock dep\nvar mockDep = {\n notify: noop,\n depend: noop,\n addSub: noop,\n removeSub: noop\n};\n/**\n * Observer class that is attached to each observed\n * object. Once attached, the observer converts the target\n * object's property keys into getter/setters that\n * collect dependencies and dispatch updates.\n */\nvar Observer = /** @class */ (function () {\n function Observer(value, shallow, mock) {\n if (shallow === void 0) { shallow = false; }\n if (mock === void 0) { mock = false; }\n this.value = value;\n this.shallow = shallow;\n this.mock = mock;\n // this.value = value\n this.dep = mock ? mockDep : new Dep();\n this.vmCount = 0;\n def(value, '__ob__', this);\n if (isArray(value)) {\n if (!mock) {\n if (hasProto) {\n value.__proto__ = arrayMethods;\n /* eslint-enable no-proto */\n }\n else {\n for (var i = 0, l = arrayKeys.length; i < l; i++) {\n var key = arrayKeys[i];\n def(value, key, arrayMethods[key]);\n }\n }\n }\n if (!shallow) {\n this.observeArray(value);\n }\n }\n else {\n /**\n * Walk through all properties and convert them into\n * getter/setters. This method should only be called when\n * value type is Object.\n */\n var keys = Object.keys(value);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n defineReactive(value, key, NO_INITIAL_VALUE, undefined, shallow, mock);\n }\n }\n }\n /**\n * Observe a list of Array items.\n */\n Observer.prototype.observeArray = function (value) {\n for (var i = 0, l = value.length; i < l; i++) {\n observe(value[i], false, this.mock);\n }\n };\n return Observer;\n}());\n// helpers\n/**\n * Attempt to create an observer instance for a value,\n * returns the new observer if successfully observed,\n * or the existing observer if the value already has one.\n */\nfunction observe(value, shallow, ssrMockReactivity) {\n if (value && hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {\n return value.__ob__;\n }\n if (shouldObserve &&\n (ssrMockReactivity || !isServerRendering()) &&\n (isArray(value) || isPlainObject(value)) &&\n Object.isExtensible(value) &&\n !value.__v_skip /* ReactiveFlags.SKIP */ &&\n !isRef(value) &&\n !(value instanceof VNode)) {\n return new Observer(value, shallow, ssrMockReactivity);\n }\n}\n/**\n * Define a reactive property on an Object.\n */\nfunction defineReactive(obj, key, val, customSetter, shallow, mock, observeEvenIfShallow) {\n if (observeEvenIfShallow === void 0) { observeEvenIfShallow = false; }\n var dep = new Dep();\n var property = Object.getOwnPropertyDescriptor(obj, key);\n if (property && property.configurable === false) {\n return;\n }\n // cater for pre-defined getter/setters\n var getter = property && property.get;\n var setter = property && property.set;\n if ((!getter || setter) &&\n (val === NO_INITIAL_VALUE || arguments.length === 2)) {\n val = obj[key];\n }\n var childOb = shallow ? val && val.__ob__ : observe(val, false, mock);\n Object.defineProperty(obj, key, {\n enumerable: true,\n configurable: true,\n get: function reactiveGetter() {\n var value = getter ? getter.call(obj) : val;\n if (Dep.target) {\n if (process.env.NODE_ENV !== 'production') {\n dep.depend({\n target: obj,\n type: \"get\" /* TrackOpTypes.GET */,\n key: key\n });\n }\n else {\n dep.depend();\n }\n if (childOb) {\n childOb.dep.depend();\n if (isArray(value)) {\n dependArray(value);\n }\n }\n }\n return isRef(value) && !shallow ? value.value : value;\n },\n set: function reactiveSetter(newVal) {\n var value = getter ? getter.call(obj) : val;\n if (!hasChanged(value, newVal)) {\n return;\n }\n if (process.env.NODE_ENV !== 'production' && customSetter) {\n customSetter();\n }\n if (setter) {\n setter.call(obj, newVal);\n }\n else if (getter) {\n // #7981: for accessor properties without setter\n return;\n }\n else if (!shallow && isRef(value) && !isRef(newVal)) {\n value.value = newVal;\n return;\n }\n else {\n val = newVal;\n }\n childOb = shallow ? newVal && newVal.__ob__ : observe(newVal, false, mock);\n if (process.env.NODE_ENV !== 'production') {\n dep.notify({\n type: \"set\" /* TriggerOpTypes.SET */,\n target: obj,\n key: key,\n newValue: newVal,\n oldValue: value\n });\n }\n else {\n dep.notify();\n }\n }\n });\n return dep;\n}\nfunction set(target, key, val) {\n if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target))) {\n warn$2(\"Cannot set reactive property on undefined, null, or primitive value: \".concat(target));\n }\n if (isReadonly(target)) {\n process.env.NODE_ENV !== 'production' && warn$2(\"Set operation on key \\\"\".concat(key, \"\\\" failed: target is readonly.\"));\n return;\n }\n var ob = target.__ob__;\n if (isArray(target) && isValidArrayIndex(key)) {\n target.length = Math.max(target.length, key);\n target.splice(key, 1, val);\n // when mocking for SSR, array methods are not hijacked\n if (ob && !ob.shallow && ob.mock) {\n observe(val, false, true);\n }\n return val;\n }\n if (key in target && !(key in Object.prototype)) {\n target[key] = val;\n return val;\n }\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' &&\n warn$2('Avoid adding reactive properties to a Vue instance or its root $data ' +\n 'at runtime - declare it upfront in the data option.');\n return val;\n }\n if (!ob) {\n target[key] = val;\n return val;\n }\n defineReactive(ob.value, key, val, undefined, ob.shallow, ob.mock);\n if (process.env.NODE_ENV !== 'production') {\n ob.dep.notify({\n type: \"add\" /* TriggerOpTypes.ADD */,\n target: target,\n key: key,\n newValue: val,\n oldValue: undefined\n });\n }\n else {\n ob.dep.notify();\n }\n return val;\n}\nfunction del(target, key) {\n if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target))) {\n warn$2(\"Cannot delete reactive property on undefined, null, or primitive value: \".concat(target));\n }\n if (isArray(target) && isValidArrayIndex(key)) {\n target.splice(key, 1);\n return;\n }\n var ob = target.__ob__;\n if (target._isVue || (ob && ob.vmCount)) {\n process.env.NODE_ENV !== 'production' &&\n warn$2('Avoid deleting properties on a Vue instance or its root $data ' +\n '- just set it to null.');\n return;\n }\n if (isReadonly(target)) {\n process.env.NODE_ENV !== 'production' &&\n warn$2(\"Delete operation on key \\\"\".concat(key, \"\\\" failed: target is readonly.\"));\n return;\n }\n if (!hasOwn(target, key)) {\n return;\n }\n delete target[key];\n if (!ob) {\n return;\n }\n if (process.env.NODE_ENV !== 'production') {\n ob.dep.notify({\n type: \"delete\" /* TriggerOpTypes.DELETE */,\n target: target,\n key: key\n });\n }\n else {\n ob.dep.notify();\n }\n}\n/**\n * Collect dependencies on array elements when the array is touched, since\n * we cannot intercept array element access like property getters.\n */\nfunction dependArray(value) {\n for (var e = void 0, i = 0, l = value.length; i < l; i++) {\n e = value[i];\n if (e && e.__ob__) {\n e.__ob__.dep.depend();\n }\n if (isArray(e)) {\n dependArray(e);\n }\n }\n}\n\nfunction reactive(target) {\n makeReactive(target, false);\n return target;\n}\n/**\n * Return a shallowly-reactive copy of the original object, where only the root\n * level properties are reactive. It also does not auto-unwrap refs (even at the\n * root level).\n */\nfunction shallowReactive(target) {\n makeReactive(target, true);\n def(target, \"__v_isShallow\" /* ReactiveFlags.IS_SHALLOW */, true);\n return target;\n}\nfunction makeReactive(target, shallow) {\n // if trying to observe a readonly proxy, return the readonly version.\n if (!isReadonly(target)) {\n if (process.env.NODE_ENV !== 'production') {\n if (isArray(target)) {\n warn$2(\"Avoid using Array as root value for \".concat(shallow ? \"shallowReactive()\" : \"reactive()\", \" as it cannot be tracked in watch() or watchEffect(). Use \").concat(shallow ? \"shallowRef()\" : \"ref()\", \" instead. This is a Vue-2-only limitation.\"));\n }\n var existingOb = target && target.__ob__;\n if (existingOb && existingOb.shallow !== shallow) {\n warn$2(\"Target is already a \".concat(existingOb.shallow ? \"\" : \"non-\", \"shallow reactive object, and cannot be converted to \").concat(shallow ? \"\" : \"non-\", \"shallow.\"));\n }\n }\n var ob = observe(target, shallow, isServerRendering() /* ssr mock reactivity */);\n if (process.env.NODE_ENV !== 'production' && !ob) {\n if (target == null || isPrimitive(target)) {\n warn$2(\"value cannot be made reactive: \".concat(String(target)));\n }\n if (isCollectionType(target)) {\n warn$2(\"Vue 2 does not support reactive collection types such as Map or Set.\");\n }\n }\n }\n}\nfunction isReactive(value) {\n if (isReadonly(value)) {\n return isReactive(value[\"__v_raw\" /* ReactiveFlags.RAW */]);\n }\n return !!(value && value.__ob__);\n}\nfunction isShallow(value) {\n return !!(value && value.__v_isShallow);\n}\nfunction isReadonly(value) {\n return !!(value && value.__v_isReadonly);\n}\nfunction isProxy(value) {\n return isReactive(value) || isReadonly(value);\n}\nfunction toRaw(observed) {\n var raw = observed && observed[\"__v_raw\" /* ReactiveFlags.RAW */];\n return raw ? toRaw(raw) : observed;\n}\nfunction markRaw(value) {\n // non-extensible objects won't be observed anyway\n if (Object.isExtensible(value)) {\n def(value, \"__v_skip\" /* ReactiveFlags.SKIP */, true);\n }\n return value;\n}\n/**\n * @internal\n */\nfunction isCollectionType(value) {\n var type = toRawType(value);\n return (type === 'Map' || type === 'WeakMap' || type === 'Set' || type === 'WeakSet');\n}\n\n/**\n * @internal\n */\nvar RefFlag = \"__v_isRef\";\nfunction isRef(r) {\n return !!(r && r.__v_isRef === true);\n}\nfunction ref$1(value) {\n return createRef(value, false);\n}\nfunction shallowRef(value) {\n return createRef(value, true);\n}\nfunction createRef(rawValue, shallow) {\n if (isRef(rawValue)) {\n return rawValue;\n }\n var ref = {};\n def(ref, RefFlag, true);\n def(ref, \"__v_isShallow\" /* ReactiveFlags.IS_SHALLOW */, shallow);\n def(ref, 'dep', defineReactive(ref, 'value', rawValue, null, shallow, isServerRendering()));\n return ref;\n}\nfunction triggerRef(ref) {\n if (process.env.NODE_ENV !== 'production' && !ref.dep) {\n warn$2(\"received object is not a triggerable ref.\");\n }\n if (process.env.NODE_ENV !== 'production') {\n ref.dep &&\n ref.dep.notify({\n type: \"set\" /* TriggerOpTypes.SET */,\n target: ref,\n key: 'value'\n });\n }\n else {\n ref.dep && ref.dep.notify();\n }\n}\nfunction unref(ref) {\n return isRef(ref) ? ref.value : ref;\n}\nfunction proxyRefs(objectWithRefs) {\n if (isReactive(objectWithRefs)) {\n return objectWithRefs;\n }\n var proxy = {};\n var keys = Object.keys(objectWithRefs);\n for (var i = 0; i < keys.length; i++) {\n proxyWithRefUnwrap(proxy, objectWithRefs, keys[i]);\n }\n return proxy;\n}\nfunction proxyWithRefUnwrap(target, source, key) {\n Object.defineProperty(target, key, {\n enumerable: true,\n configurable: true,\n get: function () {\n var val = source[key];\n if (isRef(val)) {\n return val.value;\n }\n else {\n var ob = val && val.__ob__;\n if (ob)\n ob.dep.depend();\n return val;\n }\n },\n set: function (value) {\n var oldValue = source[key];\n if (isRef(oldValue) && !isRef(value)) {\n oldValue.value = value;\n }\n else {\n source[key] = value;\n }\n }\n });\n}\nfunction customRef(factory) {\n var dep = new Dep();\n var _a = factory(function () {\n if (process.env.NODE_ENV !== 'production') {\n dep.depend({\n target: ref,\n type: \"get\" /* TrackOpTypes.GET */,\n key: 'value'\n });\n }\n else {\n dep.depend();\n }\n }, function () {\n if (process.env.NODE_ENV !== 'production') {\n dep.notify({\n target: ref,\n type: \"set\" /* TriggerOpTypes.SET */,\n key: 'value'\n });\n }\n else {\n dep.notify();\n }\n }), get = _a.get, set = _a.set;\n var ref = {\n get value() {\n return get();\n },\n set value(newVal) {\n set(newVal);\n }\n };\n def(ref, RefFlag, true);\n return ref;\n}\nfunction toRefs(object) {\n if (process.env.NODE_ENV !== 'production' && !isReactive(object)) {\n warn$2(\"toRefs() expects a reactive object but received a plain one.\");\n }\n var ret = isArray(object) ? new Array(object.length) : {};\n for (var key in object) {\n ret[key] = toRef(object, key);\n }\n return ret;\n}\nfunction toRef(object, key, defaultValue) {\n var val = object[key];\n if (isRef(val)) {\n return val;\n }\n var ref = {\n get value() {\n var val = object[key];\n return val === undefined ? defaultValue : val;\n },\n set value(newVal) {\n object[key] = newVal;\n }\n };\n def(ref, RefFlag, true);\n return ref;\n}\n\nvar rawToReadonlyFlag = \"__v_rawToReadonly\";\nvar rawToShallowReadonlyFlag = \"__v_rawToShallowReadonly\";\nfunction readonly(target) {\n return createReadonly(target, false);\n}\nfunction createReadonly(target, shallow) {\n if (!isPlainObject(target)) {\n if (process.env.NODE_ENV !== 'production') {\n if (isArray(target)) {\n warn$2(\"Vue 2 does not support readonly arrays.\");\n }\n else if (isCollectionType(target)) {\n warn$2(\"Vue 2 does not support readonly collection types such as Map or Set.\");\n }\n else {\n warn$2(\"value cannot be made readonly: \".concat(typeof target));\n }\n }\n return target;\n }\n if (process.env.NODE_ENV !== 'production' && !Object.isExtensible(target)) {\n warn$2(\"Vue 2 does not support creating readonly proxy for non-extensible object.\");\n }\n // already a readonly object\n if (isReadonly(target)) {\n return target;\n }\n // already has a readonly proxy\n var existingFlag = shallow ? rawToShallowReadonlyFlag : rawToReadonlyFlag;\n var existingProxy = target[existingFlag];\n if (existingProxy) {\n return existingProxy;\n }\n var proxy = Object.create(Object.getPrototypeOf(target));\n def(target, existingFlag, proxy);\n def(proxy, \"__v_isReadonly\" /* ReactiveFlags.IS_READONLY */, true);\n def(proxy, \"__v_raw\" /* ReactiveFlags.RAW */, target);\n if (isRef(target)) {\n def(proxy, RefFlag, true);\n }\n if (shallow || isShallow(target)) {\n def(proxy, \"__v_isShallow\" /* ReactiveFlags.IS_SHALLOW */, true);\n }\n var keys = Object.keys(target);\n for (var i = 0; i < keys.length; i++) {\n defineReadonlyProperty(proxy, target, keys[i], shallow);\n }\n return proxy;\n}\nfunction defineReadonlyProperty(proxy, target, key, shallow) {\n Object.defineProperty(proxy, key, {\n enumerable: true,\n configurable: true,\n get: function () {\n var val = target[key];\n return shallow || !isPlainObject(val) ? val : readonly(val);\n },\n set: function () {\n process.env.NODE_ENV !== 'production' &&\n warn$2(\"Set operation on key \\\"\".concat(key, \"\\\" failed: target is readonly.\"));\n }\n });\n}\n/**\n * Returns a reactive-copy of the original object, where only the root level\n * properties are readonly, and does NOT unwrap refs nor recursively convert\n * returned properties.\n * This is used for creating the props proxy object for stateful components.\n */\nfunction shallowReadonly(target) {\n return createReadonly(target, true);\n}\n\nfunction computed(getterOrOptions, debugOptions) {\n var getter;\n var setter;\n var onlyGetter = isFunction(getterOrOptions);\n if (onlyGetter) {\n getter = getterOrOptions;\n setter = process.env.NODE_ENV !== 'production'\n ? function () {\n warn$2('Write operation failed: computed value is readonly');\n }\n : noop;\n }\n else {\n getter = getterOrOptions.get;\n setter = getterOrOptions.set;\n }\n var watcher = isServerRendering()\n ? null\n : new Watcher(currentInstance, getter, noop, { lazy: true });\n if (process.env.NODE_ENV !== 'production' && watcher && debugOptions) {\n watcher.onTrack = debugOptions.onTrack;\n watcher.onTrigger = debugOptions.onTrigger;\n }\n var ref = {\n // some libs rely on the presence effect for checking computed refs\n // from normal refs, but the implementation doesn't matter\n effect: watcher,\n get value() {\n if (watcher) {\n if (watcher.dirty) {\n watcher.evaluate();\n }\n if (Dep.target) {\n if (process.env.NODE_ENV !== 'production' && Dep.target.onTrack) {\n Dep.target.onTrack({\n effect: Dep.target,\n target: ref,\n type: \"get\" /* TrackOpTypes.GET */,\n key: 'value'\n });\n }\n watcher.depend();\n }\n return watcher.value;\n }\n else {\n return getter();\n }\n },\n set value(newVal) {\n setter(newVal);\n }\n };\n def(ref, RefFlag, true);\n def(ref, \"__v_isReadonly\" /* ReactiveFlags.IS_READONLY */, onlyGetter);\n return ref;\n}\n\nvar mark;\nvar measure;\nif (process.env.NODE_ENV !== 'production') {\n var perf_1 = inBrowser && window.performance;\n /* istanbul ignore if */\n if (perf_1 &&\n // @ts-ignore\n perf_1.mark &&\n // @ts-ignore\n perf_1.measure &&\n // @ts-ignore\n perf_1.clearMarks &&\n // @ts-ignore\n perf_1.clearMeasures) {\n mark = function (tag) { return perf_1.mark(tag); };\n measure = function (name, startTag, endTag) {\n perf_1.measure(name, startTag, endTag);\n perf_1.clearMarks(startTag);\n perf_1.clearMarks(endTag);\n // perf.clearMeasures(name)\n };\n }\n}\n\nvar normalizeEvent = cached(function (name) {\n var passive = name.charAt(0) === '&';\n name = passive ? name.slice(1) : name;\n var once = name.charAt(0) === '~'; // Prefixed last, checked first\n name = once ? name.slice(1) : name;\n var capture = name.charAt(0) === '!';\n name = capture ? name.slice(1) : name;\n return {\n name: name,\n once: once,\n capture: capture,\n passive: passive\n };\n});\nfunction createFnInvoker(fns, vm) {\n function invoker() {\n var fns = invoker.fns;\n if (isArray(fns)) {\n var cloned = fns.slice();\n for (var i = 0; i < cloned.length; i++) {\n invokeWithErrorHandling(cloned[i], null, arguments, vm, \"v-on handler\");\n }\n }\n else {\n // return handler return value for single handlers\n return invokeWithErrorHandling(fns, null, arguments, vm, \"v-on handler\");\n }\n }\n invoker.fns = fns;\n return invoker;\n}\nfunction updateListeners(on, oldOn, add, remove, createOnceHandler, vm) {\n var name, cur, old, event;\n for (name in on) {\n cur = on[name];\n old = oldOn[name];\n event = normalizeEvent(name);\n if (isUndef(cur)) {\n process.env.NODE_ENV !== 'production' &&\n warn$2(\"Invalid handler for event \\\"\".concat(event.name, \"\\\": got \") + String(cur), vm);\n }\n else if (isUndef(old)) {\n if (isUndef(cur.fns)) {\n cur = on[name] = createFnInvoker(cur, vm);\n }\n if (isTrue(event.once)) {\n cur = on[name] = createOnceHandler(event.name, cur, event.capture);\n }\n add(event.name, cur, event.capture, event.passive, event.params);\n }\n else if (cur !== old) {\n old.fns = cur;\n on[name] = old;\n }\n }\n for (name in oldOn) {\n if (isUndef(on[name])) {\n event = normalizeEvent(name);\n remove(event.name, oldOn[name], event.capture);\n }\n }\n}\n\nfunction mergeVNodeHook(def, hookKey, hook) {\n if (def instanceof VNode) {\n def = def.data.hook || (def.data.hook = {});\n }\n var invoker;\n var oldHook = def[hookKey];\n function wrappedHook() {\n hook.apply(this, arguments);\n // important: remove merged hook to ensure it's called only once\n // and prevent memory leak\n remove$2(invoker.fns, wrappedHook);\n }\n if (isUndef(oldHook)) {\n // no existing hook\n invoker = createFnInvoker([wrappedHook]);\n }\n else {\n /* istanbul ignore if */\n if (isDef(oldHook.fns) && isTrue(oldHook.merged)) {\n // already a merged invoker\n invoker = oldHook;\n invoker.fns.push(wrappedHook);\n }\n else {\n // existing plain hook\n invoker = createFnInvoker([oldHook, wrappedHook]);\n }\n }\n invoker.merged = true;\n def[hookKey] = invoker;\n}\n\nfunction extractPropsFromVNodeData(data, Ctor, tag) {\n // we are only extracting raw values here.\n // validation and default values are handled in the child\n // component itself.\n var propOptions = Ctor.options.props;\n if (isUndef(propOptions)) {\n return;\n }\n var res = {};\n var attrs = data.attrs, props = data.props;\n if (isDef(attrs) || isDef(props)) {\n for (var key in propOptions) {\n var altKey = hyphenate(key);\n if (process.env.NODE_ENV !== 'production') {\n var keyInLowerCase = key.toLowerCase();\n if (key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase)) {\n tip(\"Prop \\\"\".concat(keyInLowerCase, \"\\\" is passed to component \") +\n \"\".concat(formatComponentName(\n // @ts-expect-error tag is string\n tag || Ctor), \", but the declared prop name is\") +\n \" \\\"\".concat(key, \"\\\". \") +\n \"Note that HTML attributes are case-insensitive and camelCased \" +\n \"props need to use their kebab-case equivalents when using in-DOM \" +\n \"templates. You should probably use \\\"\".concat(altKey, \"\\\" instead of \\\"\").concat(key, \"\\\".\"));\n }\n }\n checkProp(res, props, key, altKey, true) ||\n checkProp(res, attrs, key, altKey, false);\n }\n }\n return res;\n}\nfunction checkProp(res, hash, key, altKey, preserve) {\n if (isDef(hash)) {\n if (hasOwn(hash, key)) {\n res[key] = hash[key];\n if (!preserve) {\n delete hash[key];\n }\n return true;\n }\n else if (hasOwn(hash, altKey)) {\n res[key] = hash[altKey];\n if (!preserve) {\n delete hash[altKey];\n }\n return true;\n }\n }\n return false;\n}\n\n// The template compiler attempts to minimize the need for normalization by\n// statically analyzing the template at compile time.\n//\n// For plain HTML markup, normalization can be completely skipped because the\n// generated render function is guaranteed to return Array. There are\n// two cases where extra normalization is needed:\n// 1. When the children contains components - because a functional component\n// may return an Array instead of a single root. In this case, just a simple\n// normalization is needed - if any child is an Array, we flatten the whole\n// thing with Array.prototype.concat. It is guaranteed to be only 1-level deep\n// because functional components already normalize their own children.\nfunction simpleNormalizeChildren(children) {\n for (var i = 0; i < children.length; i++) {\n if (isArray(children[i])) {\n return Array.prototype.concat.apply([], children);\n }\n }\n return children;\n}\n// 2. When the children contains constructs that always generated nested Arrays,\n// e.g.